package com.gyee.wisdom.alarm.sharding.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gyee.wisdom.alarm.sharding.RSA.RSAService;
import com.gyee.wisdom.alarm.sharding.entity.AlarmUser;
import com.gyee.wisdom.alarm.sharding.entity.Alertrule2;
import com.gyee.wisdom.alarm.sharding.service.AlarmUserService;
import com.gyee.wisdom.alarm.sharding.util.UserLoginToken;
import com.gyee.wisdom.alarm.sharding.util.RequestWrapper;
import com.gyee.wisdom.alarm.sharding.util.ResponseWrapper;
import com.gyee.wisdom.alarm.sharding.util.TokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @descrition:
 * @author:Wanghs
 * @date:2020-04-24
 */
@RestController
@RequestMapping("/user")
public class AlarmUserController {

    @Autowired
    private AlarmUserService alarmUserService;

    @Autowired
    private RSAService rsaService;


    @PostMapping(value = "/login")
    @ResponseBody
    public ResponseWrapper login(@RequestBody RequestWrapper<Object> requestData) {
        ResponseWrapper<AlarmUser> wrapper = null;
        try {
            //将请求数据进行解密
            String obj = requestData.getData().toString();
            String jsonData = RSAService.translateByPublicKey(obj, requestData.getPublicKey());
            AlarmUser user = JSONObject.parseObject(jsonData, AlarmUser.class);

            AlarmUser dataUser = alarmUserService.login(user);

            if (dataUser != null) {
                String token = "";
                token = TokenUtil.createJwtToken(dataUser.getUserName());
                AlarmUser data = new AlarmUser();
                data.setChineseName(dataUser.getChineseName());
                data.setUserName(dataUser.getUserName());
                data.setId(dataUser.getId());
                data.setIdentity(dataUser.getIdentity());
                wrapper = ResponseWrapper.success("登陆成功", data);
                wrapper.setToken(token);
            } else {
                wrapper = ResponseWrapper.error("用户名或密码错误");
            }

        } catch (Exception ex) {
            wrapper = ResponseWrapper.error("请求错误");
        } finally {
            return wrapper;
        }

    }


    @PostMapping(value = "/register")
    @ResponseBody
    public ResponseWrapper<AlarmUser> registers(@RequestBody RequestWrapper<Object> requestData) {
        ResponseWrapper<AlarmUser> wrapper = null;
        try {
            String obj = requestData.getData().toString();
            String jsonData = RSAService.translateByPublicKey(obj, requestData.getPublicKey());
            AlarmUser user = JSONObject.parseObject(jsonData, AlarmUser.class);
            wrapper = dataCheck(user);
            AlarmUser existUser = alarmUserService.isExistUser(user.getUserName());
            if (existUser != null) {
                wrapper.setMsg("用户名已存在");
                wrapper.setSuccess(false);
            }
            if (wrapper.getSuccess()) {
                int result = alarmUserService.registerUser(user);
                if (result <= 0) {
                    wrapper.setSuccess(false);
                    if (result == -999) {
                        wrapper.setMsg("注册失败请联系管理员");
                    } else {
                        wrapper.setMsg("操作数据库失败");
                    }

                    wrapper.setSuccess(false);
                }
            }
        } catch (Exception ex) {
            wrapper = ResponseWrapper.error("请求失败,请重试");
        } finally {
            return wrapper;
        }


    }

    @PostMapping(value = "/registers")
    @ResponseBody
    public ResponseWrapper<AlarmUser> register(@RequestBody AlarmUser user) {
        ResponseWrapper<AlarmUser> wrapper = null;
        wrapper = dataCheck(user);
        AlarmUser existUser = alarmUserService.isExistUser(user.getUserName());
        if (existUser != null) {
            wrapper.setMsg("用户名已存在");
            wrapper.setSuccess(false);
        }
        if (wrapper.getSuccess()) {
            int result = alarmUserService.registerUser(user);
            if (result <= 0) {
                wrapper.setSuccess(false);
                if (result == -999) {
                    wrapper.setMsg("注册失败请联系管理员");
                } else {
                    wrapper.setMsg("操作数据库失败");
                }
                wrapper.setSuccess(false);
            } else {
                wrapper = ResponseWrapper.success("添加成功");
            }
        }
        return wrapper;

    }


    @PostMapping(value = "/edituser")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<AlarmUser> editAlarmUser(HttpServletRequest request,@RequestBody AlarmUser alarmUser) {

        ResponseWrapper<AlarmUser> wrapper = null;
        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();

        AlarmUser existUser = alarmUserService.isExistUser(userName);
        //如果当前登录用户和要编辑的用户名一致，或当前登录人为admin，则允许进行编辑
        if((existUser!=null&&existUser.getUserName().equals(alarmUser.getUserName())||existUser.getIdentity().equals("admin"))){
            int result = alarmUserService.updateUser(alarmUser);
            if (result <= 0) {
                if (result == -999) {
                    wrapper=ResponseWrapper.error("编辑用户错误,请联系管理员");
                } else {
                    wrapper=ResponseWrapper.error("操作数据库失败");
                }

                wrapper.setSuccess(false);
            } else {
                wrapper=ResponseWrapper.success("编辑成功");
            }
        }else{
            wrapper=ResponseWrapper.error("您不是管理员或编辑用户不是您本人");
        }
        return wrapper;
    }

    //获取所有用户,仅限于管理员进行用户密码重置
    //@UserLoginToken
    @PostMapping(value = "/get")
    @ResponseBody
    public ResponseWrapper<List<AlarmUser>> getAllUser(@RequestBody RequestWrapper<Object> requestData) {

        ResponseWrapper wrapper = null;
        Claims claims = TokenUtil.parseJWT(requestData.getToken());
        String tokenUserName = (String) claims.get("jti");
        if (!tokenUserName.equals("admin")) {
            wrapper = ResponseWrapper.error("没有权限!", new ArrayList<>());
        } else {
            List<AlarmUser> lst = alarmUserService.getAllUser();
            wrapper = ResponseWrapper.success("请求成功!", lst);
        }

        return wrapper;
    }

    @GetMapping(value = "/getall")
    public List<AlarmUser> getAllUser1() {
        List<AlarmUser> lst = alarmUserService.getAllUser();
        return lst;
    }


    //删除用户
    @DeleteMapping(value = "/{id}")
    @ResponseBody
    public ResponseWrapper deleteAlarmUser(@PathVariable("id") String id) {
        ResponseWrapper wrapper = null;
        int s = alarmUserService.deleteAlarmUser(id);
        if (s > 0) {
            wrapper = ResponseWrapper.success("删除成功!", s);
            return wrapper;
        } else {
            wrapper = ResponseWrapper.error("删除失败!");
            return wrapper;
        }

    }

    private ResponseWrapper<AlarmUser> dataCheck(AlarmUser user) {
        ResponseWrapper<AlarmUser> wrapper = null;
        String msg = "";
        boolean result = true;
        if (StringUtils.isBlank(user.getUserName())) {
            msg = "用户名不能为空";
            result = false;
        } else if (StringUtils.isBlank(user.getPassWord())) {
            msg = "密码不能为空";
            result = false;
        } else if (StringUtils.isBlank(user.getChineseName())) {
            msg = "姓名不能为空";
            result = false;
        }

        if (result) {
            wrapper = ResponseWrapper.success(msg, user);
        } else {
            wrapper = ResponseWrapper.error(msg, user);
        }
        return wrapper;
    }


}
