package com.zcloud.basic.info.command;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.zcloud.basic.info.domain.enums.UserEmploymentFlagEnum;
import com.zcloud.basic.info.domain.enums.UserRZFlagEnum;
import com.zcloud.basic.info.domain.gateway.RzUserGateway;
import com.zcloud.basic.info.domain.gateway.RzUserRecordGateway;
import com.zcloud.basic.info.domain.gateway.UserChangeRecordGateway;
import com.zcloud.basic.info.domain.gateway.UserGateway;
import com.zcloud.basic.info.domain.model.RzUserE;
import com.zcloud.basic.info.domain.model.RzUserRecordE;
import com.zcloud.basic.info.domain.model.UserChangeRecordE;
import com.zcloud.basic.info.domain.model.UserE;
import com.zcloud.basic.info.dto.RzUserRecordAddCmd;
import com.alibaba.cola.exception.BizException;
import com.zcloud.basic.info.persistence.dataobject.*;
import com.zcloud.basic.info.persistence.repository.*;
import com.zcloud.gbscommon.utils.UuidUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * web-app
 *
 * @Author SondonYong
 * @Date 2025-12-05 14:00:37
 */
@Component
@AllArgsConstructor
public class RzUserRecordAddExe {
    private final RzUserRecordGateway rzUserRecordGateway;
    private final RzUserRecordRepository rzUserRecordRepository;
    private final RzUserRepository rzUserRepository;
    private final RzUserGateway rzUserGateway;
    private final UserRepository userRepository;
    private final UserGateway userGateway;
    private final CorpInfoRepository corpInfoRepository;
    private final DepartmentRepository departmentRepository;
    private final UserChangeRecordRepository userChangeRecordRepository;
    private final UserChangeRecordGateway userChangeRecordGateway;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(RzUserRecordAddCmd cmd) {
        RzUserRecordE rzUserRecordE = new RzUserRecordE();
        BeanUtils.copyProperties(cmd, rzUserRecordE);
        boolean res = false;
        try {
            res = rzUserRecordGateway.add(rzUserRecordE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean executeJsonArray(JSONArray jsonArray) {
        try{
            if(jsonArray == null){
                return false;
            }

            List<RzUserRecordE> rzUserRecordEList = new ArrayList<>();
            for (Object o : jsonArray) {
                JSONObject json = new JSONObject(o);
                RzUserRecordE rzUserRecordE = new RzUserRecordE();
                rzUserRecordE.initFromRZ(json);
                rzUserRecordEList.add(rzUserRecordE);

                /**
                 * 通过手机号和身份证号来判断人资人员表是否有数据,
                 * 如果没有则插入,
                 * 如果有, 则更新人资人员表数据
                 *
                 * 同时判断统一用户管理是否有这个人, 如果有, 则将是否存在人资状态改为:是
                 * 同时将状态改为2-信息变更中
                 * 如果没有, 则给这个人创建个账号
                 *
                 * 插入人员变动记录表
                 */
                // 人资
                RzUserDO rzUserDO = rzUserRepository.getByPhoneAndIdCardNumber(rzUserRecordE.getPhoneNumber(), rzUserRecordE.getIdCardNumber());
                if(rzUserDO == null){
                    RzUserE rzUserE = new RzUserE();
                    rzUserE.initByRzUserRecord(rzUserRecordE);
                    rzUserGateway.add(rzUserE);
                }else {
                    RzUserE rzUserE = new RzUserE();
                    rzUserE.initByRzUserRecord(rzUserRecordE);
                    rzUserE.setId(rzUserDO.getId());
                    rzUserGateway.update(rzUserE);
                }

                // 统一用户管理
                UserDO userDO = userRepository.getByPhoneAndIdCard(rzUserRecordE.getPhoneNumber(), rzUserRecordE.getIdCardNumber());
                if(userDO != null){
                    userDO.setRzFlag(UserRZFlagEnum.YES.getCode());
                    UserE userE = new UserE();
                    BeanUtils.copyProperties(userDO, userE);
                    // 位置不可变
                    userE.setEmploymentFlag(UserEmploymentFlagEnum.INFO_CHANGE.getCode());
                    userGateway.update(userE);
                    // 查询企业名称和部门名称
                    CorpInfoDO corpInfoDO = corpInfoRepository.getById(userE.getCorpinfoId());
                    DepartmentDO departmentDO = departmentRepository.getById(userE.getDepartmentId());
                    // 变更记录表
                    UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
                    // 变更之前的老状态, 不然变更记录之前的状态就是2-信息变更中了
                    userE.setEmploymentFlag(userDO.getEmploymentFlag());
                    userChangeRecordE.initUserAddFromRZ(userE, rzUserRecordE, userE.getId(), corpInfoDO.getCorpName(), departmentDO.getName());
                    userChangeRecordGateway.add(userChangeRecordE);
                }else {
                    // todo 创建新用户 暂时放在一个分公司下, 等公司和部门对应关系有了再改
                    UserE userE = new UserE();
                    CorpInfoDO corpInfo = corpInfoRepository.getCorpInfoByCorpName("冬泳分公司账号");
                    Long roleId = userRepository.getDefaultRoleId();
                    if (roleId == null){
                        throw new BizException("未创建默认通用角色，请联系管理员");
                    }
                    userE.initFromRZ(corpInfo.getId(), roleId, rzUserRecordE);
                    userE.setUserId(UuidUtil.get32UUID());
                    userE.setMainCorpFlag(0);
                    userGateway.add(userE);

                    // 变更记录表
                    UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
                    userE.setPostName(null);
                    userChangeRecordE.initUserAddFromRZ(userE, rzUserRecordE, userE.getId(), null, null);
                    userChangeRecordGateway.add(userChangeRecordE);
                }

            }

            if(CollUtil.isNotEmpty(rzUserRecordEList)){
                rzUserRecordRepository.addBatch(BeanUtil.copyToList(rzUserRecordEList, RzUserRecordDO.class));
            }

            return true;

        }catch (Exception e){
            // 发生错误, 记录发送过来的数据
            RzUserRecordE recordE = new RzUserRecordE();
            recordE.setEmployeeImages(jsonArray.toString());
            recordE.setRemarks(e.getMessage());
            rzUserRecordGateway.add(recordE);
            throw new BizException(e.getMessage());
        }

    }

}

