package com.zcloud.basic.info.command.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.jjb.saas.security.starter.api.co.DecryptCmd;
import com.zcloud.basic.info.command.convertor.CorpInfoCoConvertor;
import com.zcloud.basic.info.domain.enums.CorpFormTypeEnum;
import com.zcloud.basic.info.domain.enums.CorpTypeEnum;
import com.zcloud.basic.info.domain.enums.UserTypeEnum;
import com.zcloud.basic.info.domain.model.CorpDepartmentE;
import com.zcloud.basic.info.domain.model.DepartmentE;
import com.zcloud.basic.info.domain.model.UserE;
import com.zcloud.basic.info.dto.*;
import com.zcloud.basic.info.dto.clientobject.CorpDepartmentCO;
import com.zcloud.basic.info.dto.clientobject.CorpInfoCO;
import com.zcloud.basic.info.dto.clientobject.CorpUserMiddleCO;
import com.zcloud.basic.info.dto.clientobject.UserCO;
import com.zcloud.basic.info.persistence.dataobject.*;
import com.zcloud.basic.info.persistence.repository.*;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-10-29 16:02:17
 */
@Component
@AllArgsConstructor
public class CorpInfoQueryExe {
    private final CorpInfoRepository corpInfoRepository;
    private final CorpInfoCoConvertor corpInfoCoConvertor;
    private final DepartmentRepository departmentRepository;
    private final PostRepository postRepository;
    private final UserRepository userRepository;
    private final UserQualificationInfoRepository userQualificationInfoRepository;
    private final CorpFormRepository corpFormRepository;
    private final CorpInfoCoConvertor corpFormCoConvertor;
//    private final SecurityClientApi securityClientApi;
//    private final DesenstizationClientUtil desenstizationClientUtil;


    /**
     * 分页
     *
     * @param corpInfoPageQry
     * @return
     */
    public PageResponse<CorpInfoCO> execute(CorpInfoPageQry corpInfoPageQry) {

        Map<String, Object> parmas = PageQueryHelper.toHashMap(corpInfoPageQry);
        if (corpInfoPageQry.getLeCreateTime() != null) {
            parmas.put("leCreateTime", corpInfoPageQry.getLeCreateTime().plusDays(1));
        }
        PageResponse<CorpInfoDO> pageResponse = corpInfoRepository.listPage(parmas);
        List<CorpInfoCO> examCenterCOS = corpInfoCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        processList(examCenterCOS, pageResponse);
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }
    /**
     * 分页
     *
     * @param corpInfoPageQry
     * @return
     */
    public PageResponse<CorpInfoCO> executeBasic(CorpInfoPageQry corpInfoPageQry) {

        Map<String, Object> parmas = PageQueryHelper.toHashMap(corpInfoPageQry);
        if (corpInfoPageQry.getLeCreateTime() != null) {
            parmas.put("leCreateTime", corpInfoPageQry.getLeCreateTime().plusDays(1));
        }
        PageResponse<CorpInfoDO> pageResponse = corpInfoRepository.listBasicPage(parmas);
        List<CorpInfoCO> examCenterCOS = corpInfoCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        processList(examCenterCOS, pageResponse);
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    private void processList(List<CorpInfoCO> examCenterCOS, PageResponse<CorpInfoDO> pageResponse){

        //examCenterCOS获取id集合
        List<Long> corpInfoIdList = examCenterCOS.stream().map(CorpInfoCO::getId).collect(Collectors.toList());
        List<CorpFormDO> corpFormDOList = corpFormRepository.getCorpListByTypeList(corpInfoIdList, Arrays.asList(CorpFormTypeEnum.SELECTFROM.getCode()));
        //corpFormDOList 按照企业分组
        Map<Long, List<CorpFormDO>> groupedByCorpInfoId = corpFormDOList.stream()
                .collect(Collectors.groupingBy(CorpFormDO::getInfoId));
        // 组装营业执照和多选框
        examCenterCOS.forEach(info -> {
            if (CollUtil.isNotEmpty(groupedByCorpInfoId) && CollUtil.isNotEmpty(groupedByCorpInfoId.get(info.getId()))) {
                //infoByTypeList name按照逗号分隔
                info.setSelectfromString(groupedByCorpInfoId.get(info.getId()).stream()
                        .map(CorpFormDO::getItemName)
                        .collect(Collectors.joining(",")));
            }
        });
    }

    public PageResponse<CorpInfoCO> executeNoPms(CorpInfoPageQry corpInfoPageQry) {

        Map<String, Object> parmas = PageQueryHelper.toHashMap(corpInfoPageQry);
        if (corpInfoPageQry.getLeCreateTime() != null) {
            parmas.put("leCreateTime", corpInfoPageQry.getLeCreateTime().plusDays(1));
        }
        PageResponse<CorpInfoDO> pageResponse = corpInfoRepository.listPageNoPms(parmas);
        List<CorpInfoCO> examCenterCOS = corpInfoCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        //examCenterCOS获取id集合
        List<Long> corpInfoIdList = examCenterCOS.stream().map(CorpInfoCO::getId).collect(Collectors.toList());
        List<CorpFormDO> corpFormDOList = corpFormRepository.getCorpListByTypeList(corpInfoIdList, Arrays.asList(CorpFormTypeEnum.SELECTFROM.getCode()));
        //corpFormDOList 按照企业分组
        Map<Long, List<CorpFormDO>> groupedByCorpInfoId = corpFormDOList.stream()
                .collect(Collectors.groupingBy(CorpFormDO::getInfoId));
        // 组装营业执照和多选框
        examCenterCOS.forEach(info -> {
            if (CollUtil.isNotEmpty(groupedByCorpInfoId) && CollUtil.isNotEmpty(groupedByCorpInfoId.get(info.getId()))) {
                //infoByTypeList name按照逗号分隔
                info.setSelectfromString(groupedByCorpInfoId.get(info.getId()).stream()
                        .map(CorpFormDO::getItemName)
                        .collect(Collectors.joining(",")));
            }
        });
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public MultiResponse<CorpInfoCO> executeListAll(CorpInfoQry corpInfoQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(corpInfoQry);
        List<CorpInfoDO> corpInfoDOList = corpInfoRepository.listAll(params);
        List<CorpInfoCO> corpInfoCOList = corpInfoCoConvertor.converDOsToCOs(corpInfoDOList);
        return MultiResponse.of(corpInfoCOList);
    }
    public CorpInfoCO info(Long id) {
        CorpInfoDO corpInfoDO = corpInfoRepository.getById(id);
        if (corpInfoDO == null){
            throw new BizException("数据不存在");
        }
        CorpInfoCO corpInfoCO = new CorpInfoCO();
        BeanUtils.copyProperties(corpInfoDO, corpInfoCO);

        List<Integer> typeList = Arrays.asList(CorpFormTypeEnum.SELECTFROM.getCode());
        List<CorpFormDO> infoByTypeList = corpFormRepository.getInfoByTypeList(corpInfoCO.getId(), typeList);

        Map<Integer, List<CorpFormDO>> groupedByType = infoByTypeList.stream()
                .collect(Collectors.groupingBy(CorpFormDO::getType));
        corpInfoCO.setSelectfromList(corpFormCoConvertor.converDOsToItemCOs(groupedByType.get(CorpFormTypeEnum.SELECTFROM.getCode())));
        return corpInfoCO;
    }
    public DecryptCmd CorpInfoEncryCO(UserCheckPassWordCmd userCheckPassWordCmd) {
        UserE userE = new UserE();
        BeanUtils.copyProperties(userCheckPassWordCmd, userE);
        userE.encryptionPassword();

        Boolean checkStatus = userRepository.checkUserPassWordEncryInfo(userE.getPassword());
       if(!checkStatus){
            throw new BizException("密码错误");
        }
        String token = AuthContext.getToken();
       DecryptCmd decryptCmd = new DecryptCmd();
       decryptCmd.setExtValues(userCheckPassWordCmd.getExtValues());
       decryptCmd.setFieldKey(userCheckPassWordCmd.getFieldKey());
       decryptCmd.setMaskDTO(userCheckPassWordCmd.getMaskInfo());
//        this.securityClientApi.decrypt(userCheckPassWordCmd.getMaskInfo().getValue(), token);
//        DecryptCmd decryptCmdResult = desenstizationClientUtil.decryptOne(decryptCmd);
        return null;
    }



    public Boolean execute(CorpInfoCheckCodeQry qry) {
        List<CorpInfoDO> list = new ArrayList<>();
        if (qry.getId() != null && qry.getId() > 0L) {
            list = corpInfoRepository.getCorpinfoByCodeAndId(qry.getCode(), qry.getId());
        } else {
            list = corpInfoRepository.getCorpinfoByCode(qry.getCode());
        }

        return CollUtil.isEmpty(list);
    }

    public Boolean executeCheckCorpName(CorpInfoCheckNameQry qry) {
        Map<String, Object> parmas = PageQueryHelper.toHashMap(qry);
        Long count = corpInfoRepository.checkCorpName(parmas);
        if (count > 0) {
            return false;
        } else {
            return true;
        }
    }

    public PageResponse<CorpDepartmentCO> corpDepartlist(CorpDepartmentQry corpDepartmentQry) {
        Map<String, Object> parmas = PageQueryHelper.toHashMap(corpDepartmentQry);
        PageResponse<CorpInfoDO> pageResponse = corpInfoRepository.listPage(parmas);
        if (CollUtil.isEmpty(pageResponse.getData())) {
            return PageResponse.of(Collections.EMPTY_LIST, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<CorpDepartmentE> corpInfoList = corpInfoCoConvertor.converDOsToCorpDepartCOs(pageResponse.getData());
        corpInfoList.forEach(corpInfo -> {
            Map<String, Object> departParmas = new HashMap<>();
            departParmas.put("eqCorpinfoId", corpInfo.getId());
            List<DepartmentDO> list = departmentRepository.listByParams(departParmas);
            if (CollUtil.isNotEmpty(list)) {
                List<DepartmentE> departmentES = corpInfoCoConvertor.converDOsToDepartE(list);
                corpInfo.addDepart(departmentES);
            }

        });

        List<CorpDepartmentCO> corpDepartmentCOList = corpInfoCoConvertor.converCorpInfoToCorpDepartCOs(corpInfoList);
        return PageResponse.of(corpDepartmentCOList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());

    }

    public PageResponse<CorpUserMiddleCO> corpUserMiddlePage(CorpUserMiddleQry qry) {
        Map<String, Object> parmas = PageQueryHelper.toHashMap(qry);
        PageResponse<CorpInfoDO> pageResponse = corpInfoRepository.corpUserMiddlePage(parmas);
        List<CorpUserMiddleCO> examCenterCOS = corpInfoCoConvertor.converDOsToMiddleCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        //examCenterCOS获取id集合
        List<Long> corpInfoIdList = examCenterCOS.stream().map(CorpUserMiddleCO::getId).collect(Collectors.toList());
        List<CorpFormDO> corpFormDOList = corpFormRepository.getCorpListByTypeList(corpInfoIdList, Arrays.asList(CorpFormTypeEnum.SELECTFROM.getCode()));
        //corpFormDOList 按照企业分组
        Map<Long, List<CorpFormDO>> groupedByCorpInfoId = corpFormDOList.stream()
                .collect(Collectors.groupingBy(CorpFormDO::getInfoId));

        examCenterCOS.forEach(info -> {
            info.setDepartMentCount(departmentRepository.getCountByCorpInfoId(info.getId()));
            info.setPostCount(postRepository.getCountByCorpInfoId(info.getId()));
            info.setUserCount(userRepository.getCountByCorpInfoId(info.getId()));
            List<UserQualificationInfoDO> userQualificationInfoDOList = userQualificationInfoRepository.getTypeCountByCorpInfoId(info.getId());
            if (CollUtil.isNotEmpty(userQualificationInfoDOList)) {
                long specialCount = userQualificationInfoDOList.stream()
                        .filter(Objects::nonNull)
                        .filter(infoDO -> Integer.valueOf(1).equals(infoDO.getQualificationinfoType()))
                        .count();
                info.setSpecialUserCount(specialCount);

                long safetyCount = userQualificationInfoDOList.stream()
                        .filter(Objects::nonNull)
                        .filter(infoDO -> Integer.valueOf(2).equals(infoDO.getQualificationinfoType()))
                        .count();
                info.setSafetyUserCount(safetyCount);
            } else {
                info.setSpecialUserCount(0L);
                info.setSafetyUserCount(0L);
            }

            if (CollUtil.isNotEmpty(groupedByCorpInfoId) && CollUtil.isNotEmpty(groupedByCorpInfoId.get(info.getId()))) {
                //infoByTypeList name按照逗号分隔
                info.setSelectfromString(groupedByCorpInfoId.get(info.getId()).stream()
                        .map(CorpFormDO::getItemName)
                        .collect(Collectors.joining(",")));
            }
        });

        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());

    }

    public List<CorpInfoCO> getCorpList() {
        List<CorpInfoDO> list = corpInfoRepository.list();
        return corpInfoCoConvertor.converDOsToCOs(list);
    }

    public List<CorpInfoCO> listByCorpIds(Collection<Long> collection) {
        QueryWrapper<CorpInfoDO> dOQueryWrapper = new QueryWrapper<>();
        dOQueryWrapper.in("id", collection);
        List<CorpInfoDO> list = corpInfoRepository.list(dOQueryWrapper);
        return corpInfoCoConvertor.converDOsToCOs(list);
    }

    public Boolean verifyCorpInfo() {
        CorpInfoDO corpInfoDO = corpInfoRepository.getById(AuthContext.getCurrentUser().getTenantId());
        if (corpInfoDO == null) {
            throw new BizException("企业不存在");
        }
        //是相关方才会校验
        List<Integer> enterpriseType = CorpTypeEnum.getCodesByEnterpriseType(UserTypeEnum.XGF.getCode());

        if (!enterpriseType.contains(corpInfoDO.getType())) {
            return true;
        }
        //corpName，单位经营地址，法定代表人姓名，主要负责人电话，职工人数，只要有一个不为空
        if (StringUtils.isEmpty(corpInfoDO.getCorpName())
                || StringUtils.isEmpty(corpInfoDO.getAddressBusiness())
                || StringUtils.isEmpty(corpInfoDO.getLrName())
                || StringUtils.isEmpty(corpInfoDO.getContactsPhone())
                || corpInfoDO.getEmployees()==null) {
            return false;
        }
        return true;
    }


}

