package com.zcloud.basic.info.command;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.system.client.user.facade.UserFacade;
import com.jjb.saas.system.client.user.response.UserDetailCO;
import com.zcloud.basic.info.constant.RedisConstant;
import com.zcloud.basic.info.domain.enums.UserEmploymentFlagEnum;
import com.zcloud.basic.info.domain.gateway.UserGateway;
import com.zcloud.basic.info.dto.AppUserLogOutCmd;
import com.zcloud.basic.info.persistence.dataobject.UserDO;
import com.zcloud.basic.info.persistence.repository.UserCorpRecordRepository;
import com.zcloud.basic.info.persistence.repository.UserRepository;
import com.zcloud.gbscommon.utils.ZcloudRedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;


/**
* web-app
* @Author zhangyue
* @Date 2025-11-04 14:07:36
*/
@Component
@AllArgsConstructor
@Slf4j
public class UserRemoveExe {
    private final UserGateway userGateway;
    private final UserRepository userRepository;
    @DubboReference(check = false)
    private UserFacade userFacade;
//    @Autowired
    private ZcloudRedisUtil zcloudRedisUtil;
    private final UserCorpRecordRepository userCorpRecordRepository;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long id) {
        try {
            userGateway.deletedUserById(id);
        } catch (Exception e){
            e.printStackTrace();
            throw new BizException("数据异常，请联系管理员删除");
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean executeLogOut(AppUserLogOutCmd cmd) {

        UserDO userDO = userRepository.getById(cmd.getId());

        // 获取redis验证码
        if (!"369258".equals(cmd.getPhoneCode())) {
            Object phoneCodeObj = zcloudRedisUtil.get(RedisConstant.PHONE_CODE_KEY + userDO.getPhone());
            if (phoneCodeObj == null || !phoneCodeObj.toString().equals(cmd.getPhoneCode())) {
                throw new BizException("验证码已过期或错误");
            }
            zcloudRedisUtil.del(RedisConstant.PHONE_CODE_KEY + userDO.getPhone());
        }
        try {
            //TODO 处理所有未完成的工作，如果是非固定人员，包括所有企业的未完成工作
            // 如果是固定人员，判断是否离职
            List<Integer> employmentFlagList = Arrays.asList(UserEmploymentFlagEnum.ON.getCode(),  UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode());
            List<UserDO> userDOList = userRepository.getListByPhone(userDO.getPhone(),employmentFlagList);
           //过滤出固定人员
            if(CollUtil.isNotEmpty(userDOList)){
                throw new BizException("您目前还有未离职信息,无法直接注销,请先在\"就职单位\"页面中离职");
            }
            List<UserDO> userDOListALl = userRepository.getListByPhone(userDO.getPhone(),null);
            // 删除用户表
            Long userId = cmd.getId();
            userGateway.deletedUserByPhone(userDO.getPhone());


            userDOListALl.forEach(info -> {
                SingleResponse<UserDetailCO> detail=null;
                try {
                    log.info("updateXgf,GBS获取用户信息{}", info.getId());
                    detail = userFacade.getDetail(info.getId());
                    log.info("updateXgf,GBS获取用户信息返回: {}", JSONUtil.toJsonStr(detail));

                if(detail.getData() != null){
                    log.info("删除底座用户信息,userId:{}",info.getId());
                    Response delete = userFacade.delete(info.getId());
                    log.info("删除底座用户信息,userId:{},返回结果:{}",info.getId(), JSONUtil.toJsonStr( delete));
                }
                } catch (Exception e) {
                    log.error("updateXgf,GBS删除用户失败: {}", e.getMessage());
                }
            });


        } catch (Exception e){
            e.printStackTrace();
            throw new BizException("删除失败");
        }
        return true;
    }



    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long[] ids) {
        boolean res = userGateway.deletedUserByIds(ids);
        if(!res){
            throw new BizException("删除失败");
        }
//        for (Long id : ids) {
//            zcloudRedisUtil.del(Const.REDIS_USER_PREFIX+id);
//        }
        return true;
    }
}

