package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.*;
import com.hfkj.common.utils.MD5Util;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.MenuTreeModel;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping(value = "/login")
@Api(value = "登录")
public class LoginController {

    private static Logger log = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private SecUserService secUserService;

    @Resource
    private SecRoleService secRoleService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private BsAgentService agentService;

    @Resource
    private BsSalesmanService salesmanService;

    @Resource
    private BsMerService merService;

    @Resource
    private BsStoreService storeService;

    @Resource
    private BsOrganizationService bsOrganizationService;

    @Resource
    private SecPermissionService secPermissionService;

    @RequestMapping(value="/userLogin",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "机构用户登录（{'loginName':'','password':''}）")
    public ResponseData userLogin(@RequestBody String reqBody, HttpServletRequest request, HttpServletResponse response) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            String loginName = jsonObject.getString("loginName");
            String password = jsonObject.getString("password");
            if(StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
                log.error("login error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            //查询用户
            SecUser secUser = secUserService.userLogin(loginName, MD5Util.encode(password.getBytes()));
            if(secUser == null || secUser.getObjectType() == null){
                log.error("login error!","账号或密码错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.PASSWORD_ERROR, "");
            }
            UserInfoModel userInfoModel = new UserInfoModel();
            secUser.setPassword(null);
            userInfoModel.setSecUser(secUser);			//用户信息

            //查询用户角色
            SecRole secRole = secRoleService.getRoleByUserId(secUser.getId());
            if (secRole == null) {
                log.error("login error!","用户未分配角色");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_ROLE_PERMISSION_ALLOT_ERROR, "");
            }else if(secRole.getEnableStatus() != 1) {
                log.error("login error!","该角色已禁用");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_ROLE_PERMISSION_ALLOT_ERROR, "");
            }

            // 拥有的菜单权限集合
            List<MenuTreeModel> menuList = secPermissionService.findMenuByUserId(secUser.getId());
            // 拥有的按钮权限集合
            List<SecPermission> buttonList = secPermissionService.findBtnByUserId(secUser.getId());
            // 查询所有拥有权限集合
            List<SecPermission> permissionList = secPermissionService.findPermissionByUserId(secUser.getId());
            userInfoModel.setSecRole(secRole);
            userInfoModel.setMenuList(menuList);
            userInfoModel.setButtonList(buttonList);
            userInfoModel.setPermissionList(permissionList);

            // 根据用户来源返回登录数据
            if (Objects.equals(secUser.getObjectType(), SecUserTypeEnum.type0.getNumber())) {
                // 公司员工（超级管理员和单位员工）
                //查询公司
                BsCompany bsCompany = bsCompanyService.getCompanyById(secUser.getCompanyId());
                if(bsCompany == null){
                    log.error("login error!","未找到公司");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COMPANY, "");
                }
                if(bsCompany.getStatus() == 0){
                    log.error("login error!","公司状态错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.BS_COMPANY_UNAVAILABLE, "");
                }
                if(secUser.getOrganizationId() != null){
                    //用户部门信息
                    BsOrganization bsOrganization = bsOrganizationService.findById(secUser.getOrganizationId());
                    userInfoModel.setBsOrganization(bsOrganization);    //部门信息
                }
                userInfoModel.setBsCompany(bsCompany);  //公司信息

            } else if (Objects.equals(secUser.getObjectType(), SecUserTypeEnum.type1.getNumber())) {
                // 公司员工（超级管理员和单位员工）
                //查询公司
                BsCompany bsCompany = bsCompanyService.getCompanyById(secUser.getCompanyId());
                if(bsCompany == null){
                    log.error("login error!","未找到公司");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COMPANY, "");
                }
                if(bsCompany.getStatus() == 0){
                    log.error("login error!","公司状态错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.BS_COMPANY_UNAVAILABLE, "");
                }
                if(secUser.getOrganizationId() != null){
                    //用户部门信息
                    BsOrganization bsOrganization = bsOrganizationService.findById(secUser.getOrganizationId());
                    userInfoModel.setBsOrganization(bsOrganization);    //部门信息
                }
                userInfoModel.setBsCompany(bsCompany);  //公司信息

            } else if (Objects.equals(secUser.getObjectType(), SecUserTypeEnum.type2.getNumber())) {
                // 查询代理商信息
                BsAgent agent = agentService.getAgent(secUser.getObjectId());
                if (agent == null) {
                    log.error("login error!","未找到代理商信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商信息");
                }
                if (agent.getStatus().equals(AgentStatusEnum.status0.getNumber())) {
                    log.error("login error!","未找到代理商信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商信息");
                }
                if (agent.getStatus().equals(AgentStatusEnum.status2.getNumber())) {
                    log.error("login error!","代理商已被停用");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理商已被停用，请联系平台。");
                }
                userInfoModel.setAgent(agent);

            } else if (Objects.equals(secUser.getObjectType(), SecUserTypeEnum.type3.getNumber())) {
                // 查询代理商信息
                BsSalesman salesman = salesmanService.getSalesman(secUser.getObjectId());
                if (salesman == null) {
                    log.error("login error!","未找到业务员信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到业务员信息");
                }
                if (salesman.getStatus().equals(SalesmanStatusEnum.status0.getNumber())) {
                    log.error("login error!","未找到业务员信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到业务员信息");
                }
                if (salesman.getStatus().equals(SalesmanStatusEnum.status2.getNumber())) {
                    log.error("login error!","业务员已被停用");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "业务员已被停用，请联系平台。");
                }
                userInfoModel.setSalesman(salesman);

            } else if (Objects.equals(secUser.getObjectType(), SecUserTypeEnum.type4.getNumber())) {
                // 查询商户信息
                BsMer mer = merService.getMer(secUser.getObjectId());
                if (mer == null) {
                    log.error("login error!","未找到商户信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户信息");
                }
                if (mer.getMerStatus().equals(MerStatusEnum.status0.getNumber())) {
                    log.error("login error!","未找到商户信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户信息");
                }
                if (!mer.getMerStatus().equals(MerStatusEnum.status1.getNumber())) {
                    log.error("login error!","商户状态不正常，暂时无法登录。请联系平台");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户状态不正常，暂时无法登录。请联系平台");
                }
                userInfoModel.setMer(mer);

            } else if (Objects.equals(secUser.getObjectType(), SecUserTypeEnum.type5.getNumber())) {
                // 查询门店信息
                BsStore store = storeService.getStoreById(secUser.getObjectId());
                if (store == null) {
                    log.error("login error!","未找到门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店");
                }
                if (!store.getStatus().equals(StoreStatusEnum.status2.getNumber())) {
                    log.error("login error!","门店已被停用");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "门店已被停用，请联系平台。");
                }
                // 查询商户信息
                BsMer mer = merService.getMer(store.getMerId());
                if (mer == null) {
                    log.error("login error!","未找到商户信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户信息");
                }
                if (mer.getMerStatus().equals(MerStatusEnum.status0.getNumber())) {
                    log.error("login error!","未找到商户信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户信息");
                }
                if (!mer.getMerStatus().equals(MerStatusEnum.status1.getNumber())) {
                    log.error("login error!","商户状态不正常，暂时无法登录。请联系平台");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户状态不正常，暂时无法登录。请联系平台");
                }
                userInfoModel.setStore(store);

            } else {
                log.error("login error!","未知登录角色类型");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知登录角色类型");
            }
            String aesStr = AESEncodeUtil.aesEncrypt(secUser.getId().toString());
            userInfoModel.setToken(aesStr);
            SessionObject so = new SessionObject(aesStr, secUser.getObjectType(), userInfoModel);
            userCenter.save(request, response, so);
            return ResponseMsgUtil.success(so);
        } catch (Exception e) {
            log.error("login error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/checkVerifyCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "校验验证码 （{'phone':'','code':''}）")
    public ResponseData checkVerifyCode(@RequestBody String reqBody){
        try {
            if(StringUtils.isBlank(reqBody)) {
                log.error("login error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            String phone = jsonObject.getString("phone");
            String code = jsonObject.getString("code");
            if(StringUtils.isBlank(phone) || StringUtils.isBlank(code)) {
                log.error("login error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            VerifyCode verifyCode = VerifyCodeStorage.getDate(phone);
            if (verifyCode != null && verifyCode.getObject().equals(code)) {
                // 清除记录，验证码只能验证一次
                //2020-08-06暂不做清除处理
                //VerifyCodeStorage.remove(phone);
                return ResponseMsgUtil.success(true);
            } else {
                return ResponseMsgUtil.success(false);
            }
        } catch (Exception e) {
            log.error("login error!",e);
            return ResponseMsgUtil.exception(e);
        }

    }

    @RequestMapping(value="/isLogin",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试是否登录")
    public ResponseData isLogin(HttpServletRequest request, HttpServletResponse response){
        boolean islogin = false;
        try {
            islogin = userCenter.isLogin(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("user logout error:"+e);
        }
        return ResponseMsgUtil.success(islogin);
    }

    @RequestMapping(value="/logout",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "登出")
    public ResponseData logout(HttpServletRequest request, HttpServletResponse response){
        try {
            userCenter.remove(request, response);
            return ResponseMsgUtil.success("退出成功");

        } catch (Exception e) {
            log.error("login error!",e);
            return ResponseMsgUtil.exception(e);
        }

    }
}
