package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.*;
import com.hai.common.utils.MD5Util;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.*;
import com.hai.model.MenuTreeModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
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;

@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 HighMerchantService highMerchantService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private BsOrganizationService bsOrganizationService;

    @Resource
    private SecPermissionService secPermissionService;

    @Resource
    private HighTyAgentService tyAgentService;

    @Resource
    private HighTySalesmanService tySalesmanService;

    @Resource
    private HighAgentService highAgentService;

    @Resource
    private HighGasStaffService gasStaffService;

    @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);

            // 根据用户来源返回登录数据  0：超级管理员  1：公司  2：商户  3：门店
            if (secUser.getObjectType() == 0 || secUser.getObjectType() == 1) {
                // 公司员工（超级管理员和单位员工）
                //查询公司
                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 (secUser.getObjectType() == 2) {

                // 查询商户
                HighMerchant merchant = highMerchantService.getMerchantById(secUser.getObjectId());
                if(merchant == null){
                    log.error("login error!","未找到商户");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
                }

                if(merchant.getStatus() != 1) {
                    log.error("login error!","商户状态不正常，请联系管理员");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STATUS_ERROR, "");
                }
                userInfoModel.setMerchant(merchant);

            } else if (secUser.getObjectType() == 3) {
                // 查询门店
                HighMerchantStore merchantStore = highMerchantStoreService.getMerchantStoreById(secUser.getObjectId());
                if(merchantStore == null){
                    log.error("login error!","未找到商户门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STORE_NOF_FOUND, "");
                }

                if(merchantStore.getStatus() != 1) {
                    log.error("login error!","未找到商户门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STORE_NOF_FOUND, "");
                }
                userInfoModel.setMerchantStore(merchantStore);

            } else if (secUser.getObjectType() == 4) {
                // 查询门店
                HighAgent highAgent = highAgentService.findByAgentMsgId(secUser.getObjectId());
                if(highAgent == null){
                    log.error("login error!","未找到代理商");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "");
                }
                if(highAgent.getStatus() != 1) {
                    log.error("login error!","代理商状态异常，请联系管理员");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理商状态异常，请联系管理员");
                }
                userInfoModel.setHighAgent(highAgent);

            } else if (secUser.getObjectType() == 5) {
                 // 查询管理人员

            }  else if (secUser.getObjectType() == 6) {
                // 查询团油代理商
                HighTyAgent tyAgent = tyAgentService.getDetailById(secUser.getObjectId());
                if (tyAgent == null) {
                    log.error("login error!","未找到代理商");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "未找到代理商");
                }
                if (!tyAgent.getStatus().equals(1)) {
                    log.error("login error!","代理商状态错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "代理商状态错误");
                }
                userInfoModel.setHighTyAgent(tyAgent);

            }  else if (secUser.getObjectType() == 7) {
                // 查询团油业务员
                HighTySalesman tySalesman = tySalesmanService.getDetailById(secUser.getObjectId());
                if (tySalesman == null) {
                    log.error("login error!","未找到业务员");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "未找到业务员");
                }
                if (!tySalesman.getStatus().equals(1)) {
                    log.error("login error!","业务员状态错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "业务员状态错误");
                }
                userInfoModel.setHighTySalesman(tySalesman);

            } else if (secUser.getObjectType() == 8) {
                // 查询加油站员工信息
                HighGasStaff gasStaff = gasStaffService.getStaffDetailById(secUser.getObjectId());
                if (gasStaff == null) {
                    log.error("login error!","未找到员工信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "未找到员工信息");
                }
                if (!gasStaff.getStatus().equals(1)) {
                    log.error("login error!","账户状态异常");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "账户状态异常");
                }
                userInfoModel.setGasStaff(gasStaff);

                // 查询门店
                HighMerchantStore merchantStore = highMerchantStoreService.getMerchantStoreById(gasStaff.getMerchantStoreId());
                if(merchantStore == null) {
                    log.error("login error!","未找到商户门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STORE_NOF_FOUND, "");
                }
                if(merchantStore.getStatus() != 1) {
                    log.error("login error!","未找到商户门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STORE_NOF_FOUND, "");
                }
                userInfoModel.setMerchantStore(merchantStore);
            } else {
                log.error("login error!","用户信息错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            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);
        }

    }
}
