package com.zcloud.basic.info.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.system.client.unit.facade.UnitFacade;
import com.jjb.saas.system.client.user.facade.UserFacade;
import com.jjb.saas.system.client.user.request.UserUpdateQuitCmd;
import com.zcloud.basic.info.domain.gateway.CorpInfoGateway;
import com.zcloud.basic.info.persistence.dataobject.CorpInfoDO;
import com.zcloud.basic.info.persistence.dataobject.UserDO;
import com.zcloud.basic.info.persistence.repository.CorpInfoRepository;
import com.zcloud.basic.info.persistence.repository.DepartmentRepository;
import com.zcloud.basic.info.persistence.repository.PostRepository;
import com.zcloud.basic.info.persistence.repository.UserRepository;
import com.zcloud.gbscommon.utils.Const;
import com.zcloud.gbscommon.utils.ZcloudRedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-10-29 16:02:17
 */
@Component
@AllArgsConstructor
@Slf4j
public class CorpInfoRemoveExe {
    private final CorpInfoGateway corpInfoGateway;
    private final UserRepository userRepository;
    private final PostRepository postRepository;
    private final DepartmentRepository departmentRepository;
    private final CorpInfoRepository corpInfoRepository;
    @DubboReference
    private UserFacade userFacade;
    @DubboReference
    private UnitFacade unitFacade;
//    @Autowired
//    private ZcloudRedisUtil zcloudRedisUtil;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long id) {
        boolean res = corpInfoGateway.deletedCorpInfoById(id);
        if (!res) {
            throw new BizException("删除失败");
        }
        //删除redis数据
      //  zcloudRedisUtil.del(Const.REDIS_CORP_PREFIX+id);
        return true;
    }

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

    @Transactional(rollbackFor = Exception.class)
    public void deleteCorpAndDown(List<Long> ids) {
        List<CorpInfoDO> corpList = corpInfoRepository.listByIds(ids);
        if (corpList != null && !corpList.isEmpty()){
            for (CorpInfoDO corp : corpList){
                log.info("开始清理企业数据："+corp.getCorpName()+"____"+corp.getId()+"------------------");
                List<UserDO> userList = userRepository.listByCorpInfoId(corp.getId());

                try {
                    // 1. 先调用远程服务删除底座数据，确保底座数据删除成功
                    log.info("底座---开始删除租户数据----------------------------------------");
                    unitFacade.delete(corp.getId());
                    log.info("底座---删除租户数据完成----------------------------------------");

                    log.info("开始清理用户数据数据----------------------------------------");
                    for (UserDO user : userList){
                        log.info("底座---开始清理用户数据："+user.getName()+"____"+user.getId());

//                        Response quit = userFacade.quit(quitCmd);
                        if (!user.getId().equals(user.getCorpinfoId())){

                            log.info(user.getId()+"-------"+ corp.getId());
                            if (corp.getBroadType() == 2){  // 企业
                                userFacade.delete(user.getId());
                            } else if (corp.getBroadType() == 3){ // 相关方
                                UserUpdateQuitCmd quitCmd = new UserUpdateQuitCmd();
                                quitCmd.setId(user.getId());
                                userFacade.quit(quitCmd);
                            }
                        }
                        log.info("底座---清理用户数据完成："+user.getName()+"____"+user.getId());
                    }
                    log.info("清理用户数据完成----------------------------------------");

                    // 2. 远程服务删除成功后，再执行本地软删除
                    userRepository.deleteByCorpInfoId(corp.getId());
                    postRepository.deleteByCorpInfoId(corp.getId());
                    departmentRepository.deleteByCorpInfoId(corp.getId());
                    corpInfoRepository.deleteById(corp.getId());
                        log.info("清理企业数据完成："+corp.getCorpName()+"____"+corp.getId()+"------------------");
                } catch (Exception e) {
                    log.error("清理企业{}数据异常：", corp.getCorpName(), e);
                    // 抛出异常，触发事务回滚
                    throw new BizException("清理企业" + corp.getCorpName() + "数据异常：" + e.getMessage());
                }
            }
        }
    }
}

