package cn.hnthyy.thmz.controller.mz;

import cn.hnthyy.thmz.Utils.DateUtil;
import cn.hnthyy.thmz.Utils.JsonUtil;
import cn.hnthyy.thmz.Utils.Md5Util;
import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.comment.UserLoginToken;
import cn.hnthyy.thmz.common.Constants;
import cn.hnthyy.thmz.entity.his.mz.Employee;
import cn.hnthyy.thmz.entity.thmz.User;
import cn.hnthyy.thmz.enums.WorkingStatusEnum;
import cn.hnthyy.thmz.enums.YesNoEnum;
import cn.hnthyy.thmz.service.his.mz.EmployeeService;
import cn.hnthyy.thmz.service.thmz.TokenService;
import cn.hnthyy.thmz.service.thmz.UserService;
import lombok.extern.slf4j.Slf4j;
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.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {
//    @Autowired
//    private XtUserServiceImpl xtUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     * @param userParam
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(@RequestBody User userParam) {
        Map<String, Object> resultMap = new HashMap<>();
        if (userParam == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "登录失败,登录参数错误");
            return resultMap;
        }
        if (StringUtils.isBlank(userParam.getUserCode())) {
            resultMap.put("code", -1);
            resultMap.put("message", "登录失败,工号不能为空");
            return resultMap;
        }
        if (StringUtils.isBlank(userParam.getPassword())) {
            resultMap.put("code", -1);
            resultMap.put("message", "登录失败,密码不能为空");
            return resultMap;
        }
        User user = userService.queryUserByCode(userParam.getUserCode());
        if (user == null) {
//            XtUser xtUser = xtUserService.queryXtUserByName(userParam.getUserCode());
//            if (xtUser == null) {
//                resultMap.put("code", -1);
//                resultMap.put("message", "登录失败,用户不存在,请联系管理员");
//                return resultMap;
//            }
            Employee employee = employeeService.queryByCodeRs(userParam.getUserCode());
            if (employee == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "登录失败,用户不存在,请联系管理员");
                return resultMap;
            }
            Integer workStatus = employee.getMark();
            if(workStatus==null){
                workStatus=YesNoEnum.YES.code.equals(employee.getDelFlag()) ? WorkingStatusEnum.CIZHI.code : WorkingStatusEnum.WORKING.code;
            }
            user = new User(employee.getEmployeeCode(),userParam.getUserCode(), employee.getEmployeeName(),workStatus);
            userService.saveUser(user);
        }
        try {
            if (!Md5Util.checkPassword(userParam.getPassword(), user.getPassword())) {
                resultMap.put("code", -1);
                resultMap.put("message", "登录失败,工号或者密码错误，请重新输入");
                return resultMap;
            }
        } catch (Exception e) {
            log.error("校验用户名和密码错误，错误信息：{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "登录失败,系统发生未知错误，请重稍后重试或联系管理员");
            return resultMap;
        }
        if (!WorkingStatusEnum.WORKING.code.equals(user.getStatus())) {
            resultMap.put("code", -1);
            resultMap.put("message", "登录失败,账号状态为非在职，请联系管理员");
            return resultMap;
        }
        Date deadTime = DateUtil.getDate(Constants.JWT_TTL);
        String token =TokenUtil.createJWT(JsonUtil.object2Json(user),deadTime);
        resultMap.put("code", 0);
        resultMap.put("token", token);
        resultMap.put("userID", userParam.getUserCode());
        resultMap.put("message", "恭喜您，登录成功！");
        return resultMap;
    }




    /**
     * 注销
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/login-out", method = RequestMethod.POST)
    public Map<String, Object> loginOut(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String token = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(token)){
            token=token.replace("Bearer ","");
        }
        if (token == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "失败失败,token参数错误");
            return resultMap;
        }
        tokenService.expiryToken(token);
        resultMap.put("code", 0);
        resultMap.put("token", token);
        resultMap.put("message", "注销登录成功！");
        return resultMap;
    }








}
