package com.zcloud.basic.info.domain.model;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.annotation.TableField;
import com.jjb.saas.framework.domain.model.BaseE;
import com.zcloud.basic.info.domain.enums.CorpTypeEnum;
import com.zcloud.basic.info.domain.enums.UserFlowFlagEnum;
import com.zcloud.basic.info.domain.gateway.DepartmentGateway;
import com.zcloud.gbscommon.excelEntity.UserExcelExportEntity;
import com.zcloud.gbscommon.excelEntity.UserExcelImportEntity;
import com.zcloud.gbscommon.utils.ExcelUtils;
import com.zcloud.gbscommon.utils.MD5;
import com.zcloud.gbscommon.utils.Sm2Util;
import com.zcloud.gbscommon.utils.Tools;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * web-domain
 *
 * @Author zhangyue
 * @Date 2025-11-04 14:07:34
 */
@Data
public class UserE extends BaseE {
    //GBS用户id
    private Long id;
    //业务主键id老系统id
    private String userId;
    //登录账号
    private String username;
    //姓名
    private String name;
    //企业id
    private Long corpinfoId;
    //是否主账号1是0否
    private Integer mainCorpFlag;
    //用户类型,1监管2企业3相关方
    private Integer userType;
    //部门id
    private Long departmentId;
    //岗位id
    private Long postId;
    //角色id
    private Long roleId;
    //邮箱
    private String email;
    //人员类型编码（主要负责人等）
    private String personnelType;
    //人员类型翻译
    private String personnelTypeName;
    //民族编码问一下有没有组件
    private String nation;
    //民族名称
    private String nationName;
    //身份证号
    private String userIdCard;
    //人脸头像url
    private String userAvatarUrl;
    //现住址
    private String currentAddress;
    //户口所在地
    private String locationAddress;

    private String rankLevel;
    private String phone;

    private String rankLevelName;

    //企业名称
    private String corpinfoName;
    //部门名称
    private String departmentName;
    //岗位名称
    private String postName;
    //人员在部门中的排序
    private Integer sort;
    //乐观锁
    private Integer version;
    //创建人
    private Long createId;
    //创建人姓名
    private String createName;
    //创建时间
    private LocalDateTime createTime;
    //更新人
    private Long updateId;
    //修改人名称
    private String updateName;
    //更新时间
    private LocalDateTime updateTime;
    //描述
    private String remarks;
    //是否删除
    private String deleteEnum;
    //租户ID
    private Long tenantId;
    //机构ID
    private Long orgId;
    //环境
    private String env;
    //是否部门领导0否1是
    private Integer departmentLeaderFlag;
    //是否分管领导0否1是
    private Integer deputyLeaderFlag;
    //文化程度 数据字典
    private String culturalLevel;
    //文化程度名称
    private String culturalLevelName;
    //婚姻状态
    private String maritalStatus;
    //婚姻状态名称
    private String maritalStatusName;
    //政治面貌
    private String politicalAffiliation;
    //政治面貌名称
    private String politicalAffiliationName;

    //密码
    private String password;
    //密码
    private String newPassword;
    // 入职状态
    private Integer employmentFlag;
    // 入职状态
    private Integer flowFlag;
    private Integer rzFlag;
    // 父级租户id
    private final Long parentTenantId = 1989259383784415232L;
    // 默认密码
    private final String defaultPassword = "Aa@12345678";

    private final String publicKey = "0402df2195296d4062ac85ad766994d73e871b887e18efb9a9a06b4cebc72372869b7da6c347c129dee2b46a0f279ff066b01c76208c2a052af75977c722a2ccee";
    // 年龄
    private Integer age;

    //生日
    private String birthday;

    // 性别
    private String sex;



    public void initAdd(Long tenantId, UserE userE) {
        if(StringUtils.isEmpty(userE.getUserId())){
            userE.setUserId(Tools.get32UUID());
        }
        userE.setTenantId(!ObjectUtils.isEmpty(userE.getTenantId()) ? userE.getTenantId() : tenantId);
        userE.setCorpinfoId(!ObjectUtils.isEmpty(userE.getCorpinfoId()) ? userE.getCorpinfoId() : tenantId);
        userE.setEmploymentFlag(1);
        userE.setPassword(defaultPassword);
    }

    public void initFromRZ(Long corpinfoId, Long roleId, RzUserRecordE rzUserRecordE){
        this.setCorpinfoId(corpinfoId);
        this.setDepartmentId(corpinfoId);
        this.setName(rzUserRecordE.getEmployeeName());
        this.setPhone(rzUserRecordE.getPhoneNumber());
        this.setUsername(rzUserRecordE.getPhoneNumber());
        this.setRoleId(roleId);
        this.setPostName(rzUserRecordE.getPositionName());
        this.setUserIdCard(rzUserRecordE.getIdCardNumber());
    }

    /**
     * 校验密码是否相同, 并且是否符合规范
     */
    public void checkPassword(String password, String confirmPassword) {
        if (!password.equals(confirmPassword)) {
            throw new BizException("两次输入的密码不一致");
        }
        if (password.length() < 8 || password.length() > 32) {
            throw new BizException("密码长度必须在8到32个字符之间");
        }
        if (!password.matches("^[A-Za-z\\d!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?]{8,32}$")) {
            throw new BizException("密码必须包含大小写字母和数字，且长度大于8");
        }

        // 检查至少包含两种类型
        int typeCount = 0;
        if (password.matches(".*[A-Za-z].*")) typeCount++;  // 包含字母
        if (password.matches(".*\\d.*")) typeCount++;        // 包含数字
        if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) typeCount++;  // 包含符号

        if (typeCount < 2) {
            throw new BizException("密码必须包含两种以上的字符类型");
        }

    }


    /**
     * 校验验证码
     */

    /**
     * 人员修改过程中，是否存在转岗、入职离职
     *
     * @param oldUserE
     * @param newUserE
     * @return
     */
    public boolean verifyTransferPosition(UserE oldUserE, UserE newUserE) {
        if (!oldUserE.getCorpinfoId().equals(newUserE.getCorpinfoId())) {
            return true;
        }
        if (!oldUserE.getDepartmentId().equals(newUserE.getDepartmentId())) {
            return true;
        }
        if (!oldUserE.getPostId().equals(newUserE.getPostId())) {
            return true;
        }
        if (!oldUserE.getEmploymentFlag().equals(newUserE.getEmploymentFlag())) {
            return true;
        }
        return false;
    }

    public void checkNull(List<UserE> userList) {
        if (CollUtil.isNotEmpty(userList)) {
            throw new BizException("岗位有相应人员，请解除相关岗位信息后删除。");
        }
    }


    // 导出
    public void exportUserTable(HttpServletResponse httpServletResponse, List<UserExcelExportEntity> userExcelEntities) {
        try {
            ExcelUtils.exportExcel(httpServletResponse, UserExcelExportEntity.class, "人员信息", userExcelEntities);
        } catch (Exception e) {
            throw new BizException("导出失败");
        }
    }

    public void initCorpInfo(CorpInfoE examTypeE, Long departmentId, Long corpInfoId) {
        this.setId(corpInfoId);
        this.setName(examTypeE.getCorpName());
        this.setUsername(examTypeE.getCorpName());
        this.setDepartmentId(departmentId);
        this.setUserType(CorpTypeEnum.getUserTypeByCode(examTypeE.getType()));
        this.setCorpinfoId(corpInfoId);
        this.setOrgId(examTypeE.getTenantId());
        this.setTenantId(examTypeE.getTenantId());
    }

    public void dataProcessingRights(Long tenantId, Map<String, Object> params) {
        if (ObjectUtils.isEmpty(params.get("allFlag")) && ObjectUtils.isEmpty(params.get("eqCorpinfoId"))) {
            params.put("eqCorpinfoId", tenantId);
        }
    }

    public void resetPassword() {
        String encrypt = Sm2Util.encryptHex(MD5.md5(defaultPassword), publicKey);
        this.setPassword(encrypt);
    }

    public void encryptionPassword() {

        this.setPassword(Sm2Util.encryptHex(MD5.md5(password), publicKey));
        if (StringUtils.isNotEmpty(newPassword)) {
            this.setNewPassword(Sm2Util.encryptHex(MD5.md5(newPassword), publicKey));
        }
    }

    public void setOldFlowInfo(UserCorpE userCorpE) {
        this.setDepartmentId(userCorpE.getDepartmentId());
        this.setPostId(userCorpE.getPostId());
        this.setDepartmentName(userCorpE.getDepartmentName());
        this.setPostName(userCorpE.getPostName());
        this.setCorpinfoName(userCorpE.getCorpinfoName());
        this.setCorpinfoId(userCorpE.getCorpinfoId());
        this.setEmploymentFlag(userCorpE.getEmploymentFlag());
    }
}

