package cn.iocoder.yudao.module.staff.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.common.CommonErrorCodeConstants;
import cn.iocoder.yudao.common.RepairRoleEnum;
import cn.iocoder.yudao.common.SystemEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.staff.service.ApiAppLoginService;
import cn.iocoder.yudao.module.staff.vo.StaffLoginBody;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleReqDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.PhoneCodeUtil;
import cn.iocoder.yudao.util.RedisCache;
import cn.iocoder.yudao.util.SendSmsUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Service
public class ApiAppLoginServiceImpl implements ApiAppLoginService {
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    @Lazy
    private RedisCache redisCache2;
    @Autowired
    private PhoneCodeUtil phoneCodeUtil;
    @Autowired
    private AdminUserService userService;
    @Resource
    private PermissionApi permissionApi;
    @Resource
    private RoleApi roleApi;
    /**
     * 登录发送验证码
     *
     * @param phone 手机号
     * @param systemCode 系统标识
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     * @author vinjor-M
     * @date 14:06 2024/10/16
     **/
    @Override
    public CommonResult<?> loginSmsCode(String phone,String systemCode) {
        String msg;
        AdminUserDO userDO = new AdminUserDO();
        userDO.setMobile(phone);
        if (ObjectUtil.isEmpty(adminUserApi.getUserByMobile(phone))){
            msg = "手机号'" + phone + "不存在请先注册";
            return error(500, msg);
        }
        String msgCode = phoneCodeUtil.generateVerificationCode();
        redisCache2.setCacheObject(phone+"-loginCode",msgCode,300, TimeUnit.SECONDS);
        SendSmsUtil.sendMsg(msgCode,phone,"1400852709", SystemEnum.getSystem(systemCode).getAppName(),"1917285");
        return success("验证码成功生成");
    }

    /**
     * 员工app登录通用方法
     *
     * @param loginBody 请求体
     * @return cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginReqVO
     * @author vinjor-M
     * @date 15:23 2024/10/16
     **/
    @SneakyThrows
    @Override
    public AdminUserDO loginApp(StaffLoginBody loginBody) {
        AdminUserDO user = new AdminUserDO();
        String userName = loginBody.getUsername();
        if (StringUtils.isNotEmpty(userName)) {
            //手机号密码登录
            user = userService.getUserByUsername(userName,loginBody.getTenantId());
        } else {
            //验证码登录--TODO 先不管
        }
        if (ObjectUtil.isEmpty(user)) {
            throw new Exception(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST.getMsg());
        }
        // 获取登录用户的角色信息
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(user.getId());
        if (ObjectUtil.isEmpty(roleIdsByUserId) || roleIdsByUserId.size() == 0) {
            throw new Exception(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST.getMsg());
        }
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        //所拥有的角色code集和
        List<String> roleCodeList = new ArrayList<>();
        //所拥有的角色名称集和
        List<String> roleNames = new ArrayList<>();
        for (RoleReqDTO item : roleList) {
            if (roleIdsByUserId.contains(item.getId())) {
                roleCodeList.add(item.getCode());
                roleNames.add(item.getName());
            }
        }
        //默认无权限登录
        boolean flag = false;
        if (SystemEnum.REPAIR.getCode().equals(loginBody.getSysCode())) {
            //维修业务系统
            flag = this.checkRepairCanLogin(user, roleCodeList);
        } else if (SystemEnum.INSPECTION.getCode().equals(loginBody.getSysCode())) {
            //检测业务系统

        } else if (SystemEnum.SCHOOL.getCode().equals(loginBody.getSysCode())) {
            //驾校业务系统

        } else if (SystemEnum.RESCUE.getCode().equals(loginBody.getSysCode())) {
            //救援业务系统
            flag = (loginBody.getType().equals("0") && roleNames.contains("调度中心")) || (loginBody.getType().equals("0") && roleNames.contains("交警大队"));
        } else if (SystemEnum.INSURE.getCode().equals(loginBody.getSysCode())) {
            //保险业务系统

        } else {
            //错误的业务系统标识
            throw new Exception(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST.getMsg());
        }
        // 角色是否可以登录
        if (!flag) {
            throw new Exception(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST.getMsg());
        }
        return user;
    }

    /**
     * 检查是否可以登录维修系统
     * @author vinjor-M
     * @date 15:34 2024/10/16
     * @param user 当前用户
    * @param roleCodeList 已有的角色code
     * @return boolean
    **/
    private boolean checkRepairCanLogin(AdminUserDO user,List<String> roleCodeList){
        boolean flag = false;
        List<String> thisRoleCodeList = new ArrayList<>();
        List<String> thisRoleNameList = new ArrayList<>();
        if(roleCodeList.contains(RepairRoleEnum.ADMIN.getCode())){
            //维修业务管理员
            flag = true;
            thisRoleCodeList.add(RepairRoleEnum.ADMIN.getCode());
            thisRoleNameList.add(RepairRoleEnum.ADMIN.getName());
        }else if(roleCodeList.contains(RepairRoleEnum.INSPECTION.getCode())){
            //总检
            flag = true;
            thisRoleCodeList.add(RepairRoleEnum.INSPECTION.getCode());
            thisRoleNameList.add(RepairRoleEnum.INSPECTION.getName());
        }else if(roleCodeList.contains(RepairRoleEnum.ADVISOR.getCode())){
            //维修服务顾问
            flag = true;
            thisRoleCodeList.add(RepairRoleEnum.ADVISOR.getCode());
            thisRoleNameList.add(RepairRoleEnum.ADVISOR.getName());
        }else if(roleCodeList.contains(RepairRoleEnum.WAREHOUSE.getCode())){
            //维修仓库管理员
            flag = true;
            thisRoleCodeList.add(RepairRoleEnum.WAREHOUSE.getCode());
            thisRoleNameList.add(RepairRoleEnum.WAREHOUSE.getName());
        }else if(roleCodeList.contains(RepairRoleEnum.REPAIR_STAFF.getCode())){
            //维修工
            flag = true;
            thisRoleCodeList.add(RepairRoleEnum.REPAIR_STAFF.getCode());
            thisRoleNameList.add(RepairRoleEnum.REPAIR_STAFF.getName());
        }
        user.setRoleCodes(String.join(",",thisRoleCodeList));
        user.setRoleNames(String.join(",",thisRoleNameList));
        return flag;
    }
}
