package com.mortals.xhx.busiz.h5.web;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.CookieService;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.base.login.web.LoginForm;
import com.mortals.xhx.base.system.menu.model.MenuEntity;
import com.mortals.xhx.base.system.menu.service.MenuService;
import com.mortals.xhx.base.system.resource.service.ResourceService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffService;
import com.mortals.xhx.module.window.model.WindowOwnerEntity;
import com.mortals.xhx.module.window.model.WindowOwnerQuery;
import com.mortals.xhx.module.window.service.WindowOwnerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.mortals.xhx.common.key.ErrorCode.*;

@RestController
@Slf4j
@RequestMapping("/api/v1/login")
public class ApiLoginController extends BaseJsonBodyController {

    @Autowired
    private UserService userService;
    @Autowired
    private IAuthTokenService authTokenService;

    @Autowired
    private IDingPersonService dingPersonService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private WindowOwnerService windowOwnerService;


    @RequestMapping("login")
    public String login(@RequestBody LoginForm loginForm) throws Exception {


        JSONObject ret = new JSONObject();
        JSONObject data = new JSONObject();
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        String ip = super.getRequestIP(request);
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, "未获取到用户信息，请重新登录");
            return ret.toJSONString();
        }
        UserEntity userEntity = null;
        try {
            if (ObjectUtils.isEmpty(loginForm.getCode())) {
                throw new AppException("钉钉code不能为空！");
            }
            //根据code 查询钉钉用户id
            Rest<String> personRest = dingPersonService.getPersonByCode(loginForm.getCode());
            if (personRest.getCode() != YesNoEnum.YES.getValue()) {
                throw new AppException(DING_AUTH_FAIL,String.format("获取钉钉用户异常,%s", personRest.getMsg()));
            }
            userEntity = userService.doLogin(loginName, password, ip);

            if (!ObjectUtils.isEmpty(loginForm.getCode())) {
                //更新绑定钉钉
                userEntity.setDingUserId(loginForm.getCode());
                userService.getUserDao().update(userEntity);
            }
            StaffEntity staffEntity = null;
            if(userEntity.getCustomerId()!=null){
                staffEntity = staffService.getCache(userEntity.getCustomerId().toString());
            }
            if(staffEntity!=null){
                WindowOwnerEntity windowOwnerEntity = windowOwnerService.selectOne(new WindowOwnerQuery().staffId(staffEntity.getId()));
                if(windowOwnerEntity == null){
                    userEntity.setUserType(1);    //工作人员
                }else {
                    if(windowOwnerEntity.getInspect()==1){
                        userEntity.setUserType(3);   //具有巡检的窗口负责人
                    }else {
                        userEntity.setUserType(2);   //普通窗口负责人
                    }
                    if(StringUtils.isNotEmpty(windowOwnerEntity.getStaffIds())){
                        List<Long> staffIdList = Arrays.asList(windowOwnerEntity.getStaffIds().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                        windowOwnerEntity.setStaffCount(staffIdList.size());
                    }else {
                        windowOwnerEntity.setStaffCount(0);
                    }
                    windowOwnerEntity.setWindowOwnerDetailList(null);
                    data.put("windowOwner", windowOwnerEntity);
                }
            }else {
                throw new AppException("当前用户不支持H5登录!");
            }
//            HashSet<Integer> set = new HashSet<>();
//            set.add(0);
//            set.add(2);
//            set.add(3);
//
//            if (ObjectUtils.isEmpty(userEntity.getUserType()) || !set.contains(userEntity.getUserType())) {
//                throw new AppException("当前用户不支持H5登录!");
//            }

            data.put("id", userEntity.getId());
            data.put("staffId", userEntity.getCustomerId());
            data.put("userType", userEntity.getUserType());
            userEntity.setLoginTime(System.currentTimeMillis());
            userEntity.setToken(IdUtil.fastSimpleUUID());
            userEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
            String token = authTokenService.createToken(userEntity);
            data.put("token", token);
            ret.put(KEY_RESULT_DATA, data);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
            recordSysLog(request, userEntity, "钉钉用户登录系统成功!");
            return ret.toJSONString();
        } catch (AppException e) {
            log.error("dinding login error ", e);
            ret.put(KEY_RESULT_CODE, e.getCode());
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        } catch (Exception e) {
            log.error("系统异常 error ", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        recordSysLog(request, "退出登录");
        super.removeCurrUser(request);
    }


    @RequestMapping("parseToken")
    public IUser parseToken() throws Exception {
        IUser userEntity = authTokenService.getLoginUser(request);
        if (!ObjectUtils.isEmpty(userEntity)) {
            authTokenService.verifyToken(userEntity);
            return userEntity;
        }
        return null;
    }
}
