
package com.sckw.system.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.base.BaseModel;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.*;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.*;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.model.EntCertificateInfo;
import com.sckw.core.web.model.LoginEntInfo;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.UserInfo;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.req.RegisterReqDto;
import com.sckw.system.api.model.dto.res.*;
import com.sckw.system.dao.*;
import com.sckw.system.dubbo.RemoteBaseService;
import com.sckw.system.dubbo.RemoteSystemServiceImpl;
import com.sckw.system.model.*;
import com.sckw.system.model.pojo.FindEntListPojo;
import com.sckw.system.model.pojo.FindEntUserPojo;
import com.sckw.system.model.pojo.FindManagePojo;
import com.sckw.system.model.pojo.FindPojoParam;
import com.sckw.system.model.report.EntCustomerExcel;
import com.sckw.system.model.report.EntSettleExcel;
import com.sckw.system.model.vo.req.*;
import com.sckw.system.model.vo.res.*;
import com.sckw.system.repository.KwsEntTypeRepository;
import com.sckw.system.repository.KwsEnterpriseRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.redisson.api.RSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 企业service接口
 *
 * @author zk
 * @date 2023-05-31
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class KwsEnterpriseService {

    @Autowired
    private KwsEnterpriseDao kwsEnterpriseDao;

    @Autowired
    private KwsEntCertificateDao kwsEntCertificateDao;

    @Autowired
    private KwsEntCheckTrackDao kwsEntCheckTrackDao;

    @Autowired
    private KwsSpecialService kwsSpecialService;

    @Autowired
    private KwsEntTypeDao kwsEntTypeDao;

    @Autowired
    private KwsEntDeptDao kwsEntDeptDao;

    @Autowired
    private KwsUserService kwsUserService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private KwsRoleService kwsRoleService;

    @Autowired
    private KwsMenuRightsDao kwsMenuRightsDao;

    @Autowired
    private KwsMenuDao kwsMenuDao;

    @Autowired
    private KwsUserDao userDao;

    @Autowired
    private RemoteSystemServiceImpl remoteSystemService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysAreaDao sysAreaDao;

    @Autowired
    private KwsEntSpecialDao entSpecialDao;

    @Autowired
    private KwsSpecialDao specialDao;
    @Autowired
    private RemoteBaseService remoteBaseService;
    private final KwsEntTypeRepository kwsEntTypeRepository;
    private final KwsEnterpriseRepository kwsEnterpriseRepository;

    @Value(value = "${jumpUrl.entCertificate}")
    private String entCertificateUrl;

    @Value(value = "${jumpUrl.appEntCertificate}")
    private String appEntCertificateUrl;

    @Value(value = "${jumpUrl.entDept}")
    private String entDeptUrl;


    /**
     * @param params 入库
     * @desc: 单表入库
     * @author: czh
     * @date: 2023/6/19
     */
    public void add(KwsEnterprise params) {
        if (kwsEnterpriseDao.insert(params) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }
    }

    /**
     * 删除记录-根据主键
     *
     * @param ids 主键
     * @desc: 批量删除
     * @author: czh
     * @date: 2023/6/19
     */
    @Transactional(rollbackFor = {})
    public void deleteByKey(String ids) {
        //校验，有员工还在企业下则不能删除
        List<Long> list = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseDao.selectAllByKeys(list);
        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
        }

        List<FindEntUserPojo> findEntUserPojos = kwsEnterpriseDao.findUserByEntIds(list);
        if (!CollectionUtils.isEmpty(findEntUserPojos)) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_011);
        }

        /*1、删除企业*/
        for (KwsEnterprise kwsEnterprise : kwsEnterprises) {
            kwsEnterprise.setDelFlag(Global.YES);
            if (kwsEnterprise.getApproval().equals(ApprovalEnum.PROCESS.getCode())) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_033);
            }
            if (kwsEnterpriseDao.updateById(kwsEnterprise) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
            }
        }

        /*2、删除机构*/
//        kwsDeptService.deleteDept(kwsDeptDao.selectByEntIdList(list));

        /*2、删除角色*/
        kwsRoleService.deleteByDeptIds(list);
    }

    /**
     * @param reqVo 更新记录入参
     * @desc: 更新记录, 有的是更新有的是新增, 两种情况
     * @author: czh
     * @date: 2023/6/19
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(UpdateEntInfoReqVo reqVo) {
        /*1、更新企业信息表*/
        KwsEnterprise kwsEnterprise = checkKwsEnterpriseById(LoginUserHolder.getEntId());
        List<KwsEnterprise> list = kwsEnterpriseDao.checkEntRepeat(reqVo.getFirmName(), "");
        if (CollectionUtils.isNotEmpty(list)) {
            if (!list.get(0).getId().equals(kwsEnterprise.getId())) {
                throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_EXISTS);
            }
        }
        BeanUtils.copyProperties(reqVo, kwsEnterprise);
        SysArea sysArea = sysAreaDao.selectById(reqVo.getCityCode());
        if (Objects.nonNull(sysArea)) {
            kwsEnterprise.setCityName(sysArea.getMergerName());
        }
        if (kwsEnterpriseDao.updateById(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }

    }

    /**
     * @param id 主键id
     * @return KwsEntCertificate
     * @desc: 查资质
     * @author: czh
     * @date: 2023/7/26
     */
    public KwsEntCertificate checkEntCertificate(long id) {
        KwsEntCertificate kwsEntCertificate = kwsEntCertificateDao.selectByKey(id);
        if (Objects.isNull(kwsEntCertificate) || kwsEntCertificate.getDelFlag() == Global.YES) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENTCERTIFICATES_NOT_EXISTS);
        }
        return kwsEntCertificate;
    }

    private void validateRegisterParentEnterprise(Long targetParentId, Long currentEntId) {
        if (Objects.isNull(targetParentId) || targetParentId <= 0) {
            return;
        }
        if (Objects.equals(targetParentId, currentEntId)) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, "上级企业不能为当前企业");
        }

        long childCount = kwsEnterpriseDao.selectCount(Wrappers.<KwsEnterprise>lambdaQuery()
                .eq(BaseModel::getDelFlag, Global.NO)
                .eq(KwsEnterprise::getPid, currentEntId));
        if (childCount > 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, "当前企业存在下级企业，不能设置为其他企业的子级");
        }

        KwsEnterprise targetParent = kwsEnterpriseDao.selectByKey(targetParentId);
        if (Objects.isNull(targetParent) || Objects.equals(targetParent.getDelFlag(), Global.YES)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
        }

        int parentLevel = getEnterpriseLevel(targetParent);
        if (parentLevel + 1 > 2) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, "企业层级不能超过两级");
        }
    }

    private int getEnterpriseLevel(KwsEnterprise enterprise) {
        if (Objects.isNull(enterprise) || Objects.isNull(enterprise.getPid()) || enterprise.getPid() <= 0) {
            return 1;
        }
        return 2;
    }

    /**
     * @param key 企业id
     * @return KwsEnterprise
     * @desc: 根据主键查询
     * @author: czh
     * @date: 2023/6/9
     */
    public KwsEnterprise selectByKey(Long key) {
        return checkKwsEnterpriseById(key);
    }

    public List<EntInfo> queryEntInfoByKeys(List<Long> keys) {
        if(CollectionUtils.isEmpty(keys)){
            return Collections.emptyList();
        }
        return kwsEnterpriseDao.queryEntInfoByKeys(keys);
    }


    /**
     * @param reqVo 分页入参
     * @return HttpResult
     * @desc: 分页查询
     * @author: czh
     * @date: 2023/6/9
     */
    public PageResult findPage(EntFindPageReqVo reqVo) {
        List<EntFindPageResVo> result = new ArrayList<>();
        List<Long> authEntIdList = Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? new ArrayList<>() : LoginUserHolder.getAuthEntIdList();


        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());
        List<FindEntListPojo> list = findPojoManager(reqVo, authEntIdList);
        if (CollectionUtils.isEmpty(list)) {
            return PageHelperUtil.getPageResult(new PageInfo<>(result));
        }

        for (FindEntListPojo item : list) {
            EntFindPageResVo entFindPageResVo = new EntFindPageResVo();
            BeanUtils.copyProperties(item, entFindPageResVo);
            entFindPageResVo.setApprovalName(ApprovalEnum.getName(entFindPageResVo.getApproval()));
            entFindPageResVo.setApprovalTime(item.getApprovalTime());
            entFindPageResVo.setEntTypes(item.getType());
            entFindPageResVo.setEntryType(item.getSystemType().equals(SystemTypeEnum.MANAGE.getCode()) ? EntryTypeEnum.PLATFORM.getCode() : EntryTypeEnum.SELF.getCode());
            entFindPageResVo.setEntryTypeStr(EntryTypeEnum.getName(entFindPageResVo.getEntryType()).getName());
            if (entFindPageResVo.getManager() != null) {
                KwsUser kwsUser = userDao.selectByKey(entFindPageResVo.getManager());
                entFindPageResVo.setManagerName(kwsUser == null ? null : kwsUser.getName());
            }

            result.add(entFindPageResVo);
        }
        return PageHelperUtil.getPageResult(new PageInfo<>(result), list, reqVo.getPageSize());
    }

    private List<FindEntListPojo> findPojoManager(EntFindPageReqVo reqVo, List<Long> authEntIdList) {
        FindPojoParam findPojoParam = new FindPojoParam();
        BeanUtils.copyProperties(reqVo, findPojoParam);
        findPojoParam.setIdList(StringUtils.splitStrToList(reqVo.getIds(), Long.class));
        if (StringUtils.isNotBlank(reqVo.getEntTypes())) {
            findPojoParam.setTypeList(Arrays.stream(reqVo.getEntTypes().split(Global.COMMA)).map(Integer::parseInt).toList());
        }
        if (StrUtil.isNotEmpty(findPojoParam.getStartTime()) && StrUtil.isNotEmpty(findPojoParam.getEndTime())) {
            findPojoParam.setStartTime(findPojoParam.getStartTime() + " 00:00:00");
            findPojoParam.setEndTime(findPojoParam.getEndTime() + " 23:59:59");
        }
        return kwsEnterpriseDao.findPojoAndManager(findPojoParam, authEntIdList);
    }

    /**
     * @param reqVo 查所有企业
     * @return List<KwsEnterprise>
     * @desc: 全量查询
     * @author: czh
     * @date: 2023/6/9
     */
    public List<FindEntListResVo> findList(FindListReqVo reqVo) {
        List<FindEntListResVo> list = kwsEnterpriseDao.findList(reqVo);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        List<Long> idList = list.stream().map(FindEntListResVo::getId).toList();
        List<KwsEntType> kwsEntTypeList = kwsEntTypeDao.findListByEntIds(idList);
        if (CollectionUtils.isNotEmpty(kwsEntTypeList)) {
            Map<Long, List<KwsEntType>> collect = kwsEntTypeList.stream().collect(Collectors.groupingBy(KwsEntType::getEntId));
            for (FindEntListResVo findEntListResVo : list) {
                List<KwsEntType> kwsEntTypes = collect.get(findEntListResVo.getId());
                if (CollectionUtils.isNotEmpty(kwsEntTypes)) {
                    findEntListResVo.setEntTypes(String.join(Global.COMMA, kwsEntTypes.stream().map(KwsEntType::getType).map(String::valueOf).distinct().toList()));
                }
            }
        }
        return list;
    }

    /**
     * @param reqVo 分页入参
     * @return FindEntListPojo
     * @desc: 分页查企业信息
     * @author: czh
     * @date: 2023/7/26
     */
    public List<FindEntListPojo> findPojo(EntFindPageReqVo reqVo) {
        FindPojoParam findPojoParam = new FindPojoParam();
        BeanUtils.copyProperties(reqVo, findPojoParam);
        findPojoParam.setIdList(StringUtils.splitStrToList(reqVo.getIds(), Long.class));
        if (StringUtils.isNotBlank(reqVo.getEntTypes())) {
            findPojoParam.setTypeList(Arrays.stream(reqVo.getEntTypes().split(Global.COMMA)).map(Integer::parseInt).toList());
        }

        return kwsEnterpriseDao.findPojo(findPojoParam);
    }


    /**
     * 新增企业（注册），修改企业信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void register(EntRegisterReqVo reqVo) {

        /*1、存企业信息表*/
        KwsEnterprise kwsEnterprise = kwsEnterpriseDao.selectByKey(reqVo.getEntId());
        if (Objects.isNull(kwsEnterprise)) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }

        Integer approval = kwsEnterprise.getApproval();
        if (approval.equals(ApprovalEnum.PROCESS.getCode()) || approval.equals(ApprovalEnum.REFRESH.getCode())) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_026);
        }
        //校验统一社会信用代码
        KwsEnterprise kwsEnterprise1 = kwsEnterpriseDao.selectOne(new LambdaQueryWrapper<KwsEnterprise>().eq(KwsEnterprise::getCreditCode, reqVo.getOrgCode()).eq(KwsEnterprise::getStatus, 0).eq(KwsEnterprise::getDelFlag, Global.UN_DELETED));
        if (Objects.nonNull(kwsEnterprise1) && !Objects.equals(kwsEnterprise1.getId(), reqVo.getEntId())) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.ENT_CODE);
        }
        Long entId = kwsEnterprise.getId();
        Date date = new Date();
        Long userId = LoginUserHolder.getUserId();
        validateRegisterParentEnterprise(reqVo.getEntPid(), entId);
        kwsEnterprise.setCreditCode(reqVo.getOrgCode());//统一社会信用代码
        kwsEnterprise.setCode(reqVo.getCode());
        kwsEnterprise.setLegalName(reqVo.getLegalName());
        kwsEnterprise.setLegalPhone(reqVo.getLegalPhone());
        kwsEnterprise.setHead(reqVo.getHead());
        kwsEnterprise.setRegSource(LoginUserHolder.getClientType());
        kwsEnterprise.setCityCode(reqVo.getCityCode());
        if (Objects.nonNull(reqVo.getEntPid())) {
            kwsEnterprise.setPid(reqVo.getEntPid());
        }
        SysArea sysArea = sysAreaDao.selectById(reqVo.getCityCode());
        if (Objects.nonNull(sysArea)) {
            kwsEnterprise.setCityName(sysArea.getMergerName());
        }
        kwsEnterprise.setDetailAddress(reqVo.getDetailAddress());
        kwsEnterprise.setLat(reqVo.getLat());
        kwsEnterprise.setLng(reqVo.getLng());

        //一些待确认的字段
        kwsEnterprise.setIntegral(0);
        kwsEnterprise.setBalance(0L);
        kwsEnterprise.setExperience(0);
        kwsEnterprise.setMemberLevel(0);
        kwsEnterprise.setOrgCode("");
        kwsEnterprise.setRegTime(date);
        kwsEnterprise.setUpdateBy(LoginUserHolder.getUserId());

        //客户经理
//        Integer systemType = LoginUserHolder.getSystemType();
//        if (Objects.equals(SystemTypeEnum.MANAGE.getCode(), systemType)) {
//            kwsEnterprise.setManager(LoginUserHolder.getUserId());
//        } else {
//            //默认给一个客户经理(admin账号)-公共平台
//            List<KwsUserSystemTypeVo> userSystemTypeVos = userDao.selectUserBySystemType(SystemTypeEnum.MANAGE.getCode());
//            if (CollectionUtils.isNotEmpty(userSystemTypeVos)) {
//                KwsUserSystemTypeVo kwsUserSystemTypeVo = userSystemTypeVos.get(0);
//                kwsEnterprise.setManager(kwsUserSystemTypeVo.getId());
//            }
//        }

        //更新缓存
        List<Long> enterpriseIds = new ArrayList<>();
        if (Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode())) {
            if (Objects.equals(LoginUserHolder.getIsMain(), Global.YES)) {
                //获取所有企业id
                List<Long> enterpriseIdList = remoteUserService.findAllEnterprise();
                if (Objects.nonNull(enterpriseIdList) && enterpriseIdList.size() > 0) {
                    enterpriseIds.addAll(enterpriseIdList);
                }
                //获取所有运营端账号关联的企业(客户经理关联的企业)
                List<Long> userIds = remoteUserService.selectUserBySystemType(SystemTypeEnum.MANAGE.getCode());
                /**带有数据权限*/
                List<Long> enterpriseListByIds = remoteUserService.findEnterpriseListByIds(userIds);
                if (Objects.nonNull(enterpriseListByIds) && enterpriseListByIds.size() > 0) {
                    enterpriseIds.addAll(enterpriseListByIds);
                }
                //无数据权限，运营账号(客户经理关联)关联的企业即可
//                    enterpriseIds = remoteUserService.findEnterpriseListByUserIds(userIds);
            } else {
                List<Long> serviceEnterpriseIds = remoteUserService.findEnterpriseIds(LoginUserHolder.getUserId());
                if (Objects.nonNull(serviceEnterpriseIds) && serviceEnterpriseIds.size() > 0) {
                    enterpriseIds.addAll(serviceEnterpriseIds);
                }
            }
        }
        if (enterpriseIds.size() > 0) {
            enterpriseIds.add(kwsEnterprise.getId());
            enterpriseIds = enterpriseIds.stream().distinct().collect(Collectors.toList());
            String key = Global.getCustomerManagerUserLoginKey(LoginUserHolder.getSystemType(), LoginUserHolder.getUserId());
            RSet<Object> set = RedissonUtils.getSet(key);
            if (CollectionUtils.isNotEmpty(set)) {
                RedissonUtils.delete(key);
            }
            RedissonUtils.putSet(key, enterpriseIds);
        }

        List<KwsEntCheckTrack> list = kwsEntCheckTrackDao.findList(entId);
        kwsEnterprise.setApproval(list.stream().anyMatch(item -> item.getStatus().equals(Global.NO)) ? ApprovalEnum.REFRESH.getCode() : ApprovalEnum.PROCESS.getCode());
        if (kwsEnterpriseDao.updateById(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }

        /*2、存企业类型,一个企业可以有多个类型*/
        List<KwsEntType> listByEntId = kwsEntTypeDao.findListByEntId(entId);
        if (CollectionUtils.isNotEmpty(listByEntId)) {
            kwsEntTypeDao.deleteBatchIds(listByEntId.stream().map(KwsEntType::getId).collect(Collectors.toList()));
        }

        Integer type = Integer.parseInt(reqVo.getEntTypes());//只能单选
        KwsEntType kwsEntType = new KwsEntType();
        kwsEntType.setEntId(entId);
        kwsEntType.setType(type);
        kwsEntType.setId(new IdWorker(1).nextId());
        kwsEntType.setStatus(ApprovalEnum.PROCESS.getCode());
        kwsEntType.setCreateBy(userId);
        kwsEntType.setCreateTime(date);
        kwsEntType.setUpdateBy(userId);
        kwsEntType.setUpdateTime(date);
        kwsEntType.setDelFlag(Global.NO);
        if (kwsEntTypeDao.insert(kwsEntType) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }

        /*3、存企业证书*/
        List<KwsEntCertificate> kwsEntCertificates = new ArrayList<>();
        for (BusinessLicense businessLicense : reqVo.getBusinessLicense()) {
            KwsEntCertificate kwsEntCertificate = new KwsEntCertificate();
            kwsEntCertificate.setEntId(entId);
            kwsEntCertificate.setCreateBy(userId);
            kwsEntCertificate.setCreateTime(date);
            kwsEntCertificate.setUpdateBy(userId);
            kwsEntCertificate.setUpdateTime(date);
            kwsEntCertificate.setDelFlag(Global.NO);
            kwsEntCertificate.setStatus(ApprovalEnum.PROCESS.getCode());
            BeanUtils.copyProperties(businessLicense, kwsEntCertificate);
            kwsEntCertificate.setId(new IdWorker(1).nextId());
            kwsEntCertificate.setCertificateMain(FileUtils.replaceAll(businessLicense.getCertificateMain()));
            kwsEntCertificate.setCertificateRevolt(FileUtils.replaceAll(businessLicense.getCertificateRevolt()));
            kwsEntCertificates.add(kwsEntCertificate);
        }
        if (kwsEntCertificateDao.saveBatch(kwsEntCertificates) != kwsEntCertificates.size()) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }

        if (SystemTypeEnum.MANAGE.getCode().equals(LoginUserHolder.getSystemType())) {
            ApprovalReqVo approvalReqVo = new ApprovalReqVo();
            approvalReqVo.setEntId(entId);
            approvalReqVo.setStatus(ApprovalEnum.OK.getCode());
            approvalReqVo.setRemark("");
            approval(approvalReqVo);
        }
    }


    /**
     * 企业审批
     */
    @Transactional(rollbackFor = Exception.class)
    public void approval(ApprovalReqVo reqVo) {
        Integer status = reqVo.getStatus();
        Long entId = reqVo.getEntId();
        List<KwsEntCertificate> kwsEntCertificateList = kwsEntCertificateDao.selectByEntId(entId);
        if (CollectionUtils.isEmpty(kwsEntCertificateList)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENTCERTIFICATES_NOT_EXISTS);
        }
        List<KwsEntCertificate> kwsEntCertificates = new ArrayList<>();
        for (KwsEntCertificate kwsEntCertificate : kwsEntCertificateList) {
            //先把旧的作废
            if (status.equals(ApprovalEnum.OK.getCode())) {
                List<KwsEntCertificate> previous = kwsEntCertificateDao.findPrevious(kwsEntCertificate.getEntId(), kwsEntCertificate.getType());
                if (CollectionUtils.isNotEmpty(previous)) {
                    for (KwsEntCertificate kwsEntCertificate1 : previous) {
                        kwsEntCertificate1.setDelFlag(Global.YES);
                        kwsEntCertificateDao.update(kwsEntCertificate1);
                    }
                }
            }

            if (kwsEntCertificate.getStatus().equals(ApprovalEnum.PROCESS.getCode())) {
                kwsEntCertificate.setStatus(status.equals(ApprovalEnum.OK.getCode()) ? Global.NO : Global.YES);
                kwsEntCertificateDao.update(kwsEntCertificate);
            }

            entId = kwsEntCertificate.getEntId();
            kwsEntCertificates.add(kwsEntCertificate);
        }

        List<KwsEntType> kwsEntTypeList = kwsEntTypeDao.findApprovalByEntId(entId);
        if (CollectionUtils.isNotEmpty(kwsEntTypeList)) {
            for (KwsEntType kwsEntType : kwsEntTypeList) {
                kwsEntType.setStatus(status.equals(ApprovalEnum.OK.getCode()) ? Global.NO : Global.YES);
                kwsEntTypeDao.update(kwsEntType);
            }
        }

        /*更新企业信息主表审批状态*/
        KwsEnterprise kwsEnterprise = checkKwsEnterpriseById(entId);
        Integer currentApproval = kwsEnterprise.getApproval();
        kwsEnterprise.setApproval(reqVo.getStatus());
        kwsEnterprise.setRemark(reqVo.getRemark());
        if (Objects.equals(reqVo.getStatus(), ApprovalEnum.OK.getCode())) {
            String loginEntStr = RedissonUtils.getString(Global.getFullUserEntKey(entId));
            LoginEntInfo loginEntInfo = StringUtils.isNotBlank(loginEntStr) ? JSON.parseObject(loginEntStr, LoginEntInfo.class) : null;
            if (Objects.nonNull(loginEntInfo)) {
                loginEntInfo.setStatus(Global.NO);
                RedissonUtils.putString(Global.getFullUserEntKey(entId), JSONObject.toJSONString(loginEntInfo), Global.PC_TOKEN_EXPIRE);
            }
        }
        if (kwsEnterpriseDao.approval(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }

        /*新增审批记录*/
        KwsEntCheckTrack kwsEntCheckTrack = new KwsEntCheckTrack();
        kwsEntCheckTrack.setEntId(entId);
        kwsEntCheckTrack.setRemark(reqVo.getRemark());
        kwsEntCheckTrack.setStatus(status.equals(ApprovalEnum.OK.getCode()) ? Global.NO : Global.YES);
        if (kwsEntCheckTrackDao.insert(kwsEntCheckTrack) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }

        /*第一次审批通过（非更新资质审批通过），构建机构角色等*/
        if (ApprovalEnum.OK.getCode() == status) {
            List<Long> roleList = kwsEnterpriseDao.findManageInfoByEntIdBeforeApproval(entId);
            if (ApprovalEnum.PROCESS.getCode() == currentApproval) {
                /*审批通过，绑定角色*/
                if (CollUtil.isEmpty(roleList)) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
                }
                KwsUser userByAccount = kwsUserService.queryUserInfo(kwsEnterprise.getPhone(), SystemTypeEnum.COMPANY.getCode());
                if (Objects.isNull(userByAccount)) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
                }
                kwsUserService.fillUserRole(StrUtil.join(",", roleList), userByAccount.getId(), SystemTypeEnum.COMPANY.getCode());
            }

            List<KwsMenuRights> kwsMenuRightsList = kwsMenuRightsDao.selectEntMenus(entId);
            if (CollectionUtils.isNotEmpty(kwsMenuRightsList)) {
                kwsMenuRightsDao.deleteByIds(kwsMenuRightsList.stream().map(KwsMenuRights::getId).collect(Collectors.toList()));
            }

            List<KwsEntType> listByEntId = kwsEntTypeDao.findListByEntId(entId);
            List<Integer> typeList = listByEntId.stream().map(KwsEntType::getType).toList();
            List<KwsMenu> kwsMenus = kwsMenuDao.selectAll();
            List<KwsMenuRights> kwsMenuRightsList2 = new ArrayList<>();
            Date date = new Date();
            for (Integer entType : typeList) {
                List<KwsMenu> collect = kwsMenus.stream().filter(item -> item.getUsingRoles().contains(String.valueOf(entType))).toList();
                for (Long role : roleList) {
                    for (KwsMenu kwsMenu : collect) {
                        KwsMenuRights kwsMenuRights = new KwsMenuRights();
                        kwsMenuRights.setEntId(entId);
                        kwsMenuRights.setMenuId(kwsMenu.getId());
                        kwsMenuRights.setId(new IdWorker(1L).nextId());
                        kwsMenuRights.setRoleId(role);
                        kwsMenuRights.setCreateBy(LoginUserHolder.getUserId());
                        kwsMenuRights.setUpdateBy(LoginUserHolder.getUserId());
                        kwsMenuRights.setCreateTime(date);
                        kwsMenuRights.setUpdateTime(date);
                        kwsMenuRights.setDelFlag(Global.NO);
                        kwsMenuRights.setStatus(Global.NO);
                        kwsMenuRightsList2.add(kwsMenuRights);
                    }
                }
            }
            kwsMenuRightsDao.saveBatch(kwsMenuRightsList2);
        }
        commonService.updateEntCertificate(entId, BeanUtils.copyToList(kwsEntCertificates, EntCertificateInfo.class));

        Map<String, Object> map = CollectionUtils.createHashMap();
        map.put("entName", kwsEnterprise.getFirmName());
        map.put("createByName", LoginUserHolder.getUserName());
        MessageEnum messageEnum;
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(entId);
        if (Objects.isNull(entCacheResDto)) {
            return;
        }

        if (reqVo.getStatus().equals(ApprovalEnum.OK.getCode())) {
            if (Objects.equals(kwsEnterprise.getPid(), 0L)) {//母公司
                messageEnum = MessageEnum.ENT_CERTIFICATE_PASS;
            } else {
                messageEnum = MessageEnum.ENT_DEPT_CERTIFICATE_PASS;
            }
        } else {
            if (Objects.equals(kwsEnterprise.getPid(), 0L)) {
                messageEnum = MessageEnum.ENT_CERTIFICATE_REFUSED;
            } else {
                messageEnum = MessageEnum.ENT_DEPT_CERTIFICATE_REFUSED;
            }
        }

        if (Objects.equals(kwsEnterprise.getPid(), 0L)) {
            commonService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto.getContactsId()).setEntId(entCacheResDto.getId())),
                    messageEnum,
                    map,
                    entCertificateUrl, appEntCertificateUrl);
        } else {
            commonService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto.getContactsId()).setEntId(entCacheResDto.getId())),
                    messageEnum,
                    map,
                    entDeptUrl, "");
        }

    }

    /**
     * @param id 主键id
     * @return KwsEnterprise
     * @desc: 查企业
     * @author: czh
     * @date: 2023/7/26
     */
    private KwsEnterprise checkKwsEnterpriseById(long id) {
        KwsEnterprise kwsEnterprise = queryKwsEnterpriseById(id);
        if (Objects.isNull(kwsEnterprise) || kwsEnterprise.getDelFlag() == Global.YES) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
        }
        return kwsEnterprise;
    }

    /**
     * @param id 主键
     * @return KwsEnterprise
     * @desc: 放开接口
     * @author: czh
     * @date: 2023/7/26
     */
    public KwsEnterprise queryKwsEnterpriseById(long id) {
        return kwsEnterpriseDao.selectByKey(id);
    }

    /**
     * 企业冻结/解冻
     */
    public void freeze(FreezeReqVo reqVo) {
        KwsEnterprise kwsEnterprise = checkKwsEnterpriseById(reqVo.getId());
        kwsEnterprise.setStatus(reqVo.getStatus());
        if (kwsEnterpriseDao.updateById(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
    }

    /**
     * 企业证件信息
     */
    public List<CertificateResVo> certificate(Long entId) {
        /*查企业资质*/
        List<KwsEntCertificate> kwsEntCertificates = kwsEntCertificateDao.selectByEntId(entId);
        if (CollectionUtils.isEmpty(kwsEntCertificates)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENTCERTIFICATES_NOT_EXISTS);
        }

        KwsEnterprise kwsEnterprise = kwsEnterpriseDao.selectByKey(entId);
        List<KwsEntCertificate> finalList = new ArrayList<>();
        if (kwsEnterprise.getApproval().equals(ApprovalEnum.PROCESS.getCode()) || kwsEnterprise.getApproval().equals(ApprovalEnum.REFRESH.getCode())) {
            finalList = kwsEntCertificates.stream().filter(item -> item.getStatus().equals(ApprovalEnum.PROCESS.getCode())).toList();
        }


        if (kwsEnterprise.getApproval().equals(ApprovalEnum.OK.getCode())) {
            finalList = kwsEntCertificates.stream().filter(item -> item.getStatus().equals(Global.NO)).toList();
        }

        if (kwsEnterprise.getApproval().equals(ApprovalEnum.PASS.getCode())) {
            List<KwsEntCheckTrack> list = kwsEntCheckTrackDao.findList(entId);
            if (list.stream().anyMatch(item -> item.getStatus().equals(Global.NO))) {
                //通过了一次
                finalList = kwsEntCertificates.stream().filter(item -> item.getStatus().equals(Global.NO)).toList();
            } else {
                //未通过过，按时间倒序取最后一次驳回
                finalList = kwsEntCertificates.stream().filter(item -> item.getStatus().equals(Global.YES)).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(finalList)) {
                    Map<Integer, List<KwsEntCertificate>> collect = finalList.stream().collect(Collectors.groupingBy(KwsEntCertificate::getType));
                    for (Integer type : collect.keySet()) {
                        List<KwsEntCertificate> kwsEntCertificates1 = collect.get(type);
                        if (CollectionUtils.isNotEmpty(kwsEntCertificates1)) {
                            List<KwsEntCertificate> collect1 = kwsEntCertificates1.stream().sorted(Comparator.comparing(KwsEntCertificate::getUpdateTime).reversed()).toList();
                            finalList.add(collect1.get(0));
                        }
                    }
                }
            }
        }

        if (CollectionUtils.isEmpty(finalList)) {
            return Collections.emptyList();
        }

        /*拼装返参*/
        List<CertificateResVo> list = new ArrayList<>();
        finalList.forEach(item -> {
            CertificateResVo certificateResVo = new CertificateResVo();
            certificateResVo.setTypeName(Objects.requireNonNull(CertificateTypeEnum.getName(item.getType())).getName());
            BeanUtils.copyProperties(item, certificateResVo);
            certificateResVo.setCertificateMain(FileUtils.splice(certificateResVo.getCertificateMain()));
            certificateResVo.setCertificateRevolt(FileUtils.splice(certificateResVo.getCertificateRevolt()));
            list.add(certificateResVo);
        });
        return list;
    }

    /**
     * 企业证件信息
     */
    public List<CertificateResVo> queryCertificate(Long entId) {
        /*查企业资质*/
        List<KwsEntCertificate> kwsEntCertificates = kwsEntCertificateDao.selectByEntId(entId);
        if (CollectionUtils.isEmpty(kwsEntCertificates)) {
            return Collections.emptyList();
        }
        /*拼装返参*/
        List<CertificateResVo> list = new ArrayList<>();
        kwsEntCertificates.forEach(item -> {
            CertificateResVo certificateResVo = new CertificateResVo();
            certificateResVo.setTypeName(Objects.requireNonNull(EntTypeEnum.getName(item.getType())).getName());
            BeanUtils.copyProperties(item, certificateResVo);
            list.add(certificateResVo);
        });
        return list;
    }


    /**
     * @param userId 用户id
     * @return KwsEnterprise
     * @desc: 根据用户id查企业
     * @author: czh
     * @date: 2023/6/13
     */
    public KwsEnterprise findByUserId(long userId) {
        return kwsEnterpriseDao.findByUserId(userId);
    }

    /**
     * @param reqVo 新增企业入驻入参
     * @desc: 新增企业入驻
     * @author: czh
     * @date: 2023/6/19
     */
    @Transactional(rollbackFor = {})
    public void addEntSettle(AddEntSettleReqVo reqVo) {
        checkAddEntSettleParam(reqVo);
        //运营端新增企业入驻，直接通过
        if (LoginUserHolder.isManager()) {
            RegisterReqDto registerReqDto = new RegisterReqDto();
            registerReqDto.setEntName(reqVo.getFirmName());
            registerReqDto.setName(reqVo.getContacts());
            registerReqDto.setPhone(reqVo.getPhone());
            registerReqDto.setIsMain(Global.YES);
            registerReqDto.setSystemType(SystemTypeEnum.COMPANY.getCode());
            registerReqDto.setEntTypes(reqVo.getEntTypes());
            RegisterResDto register = kwsUserService.register(registerReqDto);

            EntRegisterReqVo entRegisterReqVo = new EntRegisterReqVo();
            BeanUtils.copyProperties(reqVo, entRegisterReqVo);
            entRegisterReqVo.setEntId(register.getEntId());
            register(entRegisterReqVo);
        } else { //平台端，新增子公司
            if (Objects.isNull(reqVo.getEntPid())) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.ENT_FAILED);
            }
            Long entId = new IdWorker(1L).nextId();
            KwsEnterprise kwsEnterprise = new KwsEnterprise();
            kwsEnterprise.setId(entId);
            kwsEnterprise.setCode("");
            kwsEnterprise.setPid(reqVo.getEntPid());
            kwsEnterprise.setCreditCode(reqVo.getOrgCode());
            kwsEnterprise.setOrgCode(reqVo.getOrgCode());
            kwsEnterprise.setFirmName(reqVo.getFirmName());
            kwsEnterprise.setApproval(ApprovalEnum.NO.getCode());
            kwsEnterprise.setContacts(reqVo.getContacts());
            kwsEnterprise.setPhone(reqVo.getPhone());
            kwsEnterprise.setCreateBy(LoginUserHolder.getUserId());
            kwsEnterprise.setUpdateBy(LoginUserHolder.getUserId());
            kwsEnterprise.setCityCode(reqVo.getCityCode());
            if (kwsEnterpriseDao.insert(kwsEnterprise) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
            }

            EntRegisterReqVo entRegisterReqVo = new EntRegisterReqVo();
            BeanUtils.copyProperties(reqVo, entRegisterReqVo);
            entRegisterReqVo.setEntId(entId);
            register(entRegisterReqVo);
        }
    }


    /**
     * @param reqVo 入参
     * @desc: 新增企业入驻入参校验
     * @author: czh
     * @date: 2023/7/25
     */
    private void checkAddEntSettleParam(AddEntSettleReqVo reqVo) {
        List<BusinessLicense> businessLicenseList = reqVo.getBusinessLicense();
        for (BusinessLicense businessLicense : businessLicenseList) {
            Integer type = businessLicense.getType();
            if (type.equals(CertificateTypeEnum.BUSINESSLICENSE.getCode())) {
                if (!RegularUtils.matchWithFix(RegularUtils.NUMBER_AND_UPPERCASE_LATTER, businessLicense.getCode(), 18)) {
                    throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.ENT_CODE_ERROR);
                }
            }

//            if (type.equals(CertificateTypeEnum.CORPORATION_IDCARD.getCode())) {
//                throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.LEGAL_ID_CARD_ERROR);
//            }
        }

        if (StringUtils.isNotBlank(reqVo.getContacts()) && !RegularUtils.matchs(RegularUtils.NAME, reqVo.getContacts())) {
            throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.CONTACTS_ERROR);
        }

        if (StringUtils.isNotBlank(reqVo.getLegalName()) && !RegularUtils.matchs(RegularUtils.NAME, reqVo.getLegalName())) {
            throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.LEGAL_NAME_ERROR);
        }

        if (StringUtils.isNotBlank(reqVo.getPhone()) && !RegularUtils.matchs(RegularUtils.PHONE_REG, reqVo.getPhone())) {
            throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.CONTACTS_PHONE_ERROR);
        }

        if (StringUtils.isNotBlank(reqVo.getLegalPhone()) && !RegularUtils.matchs(RegularUtils.PHONE_REG, reqVo.getLegalPhone())) {
            throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.LEGAL_PHONE_ERROR);
        }
    }


    public List<KwsEntCheckTrack> entCheck(Long entId) {
        return kwsEntCheckTrackDao.findList(entId);
    }

    /**
     * @param reqVo 入参
     * @desc: 更新企业资质
     * @author: czh
     * @date: 2023/6/29
     */
    public void updateCertificate(UpdateCertificateReqVo reqVo) {
        for (BusinessLicense businessLicense : reqVo.getCertificateInfo()) {
            long id = businessLicense.getId();
            KwsEntCertificate kwsEntCertificate = kwsEntCertificateDao.selectByKey(id);
            if (Objects.isNull(kwsEntCertificate)) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }

            kwsEntCertificate.setCode(businessLicense.getCode());
            kwsEntCertificate.setCertificateMain(businessLicense.getCertificateMain());
            kwsEntCertificate.setCertificateRevolt(businessLicense.getCertificateRevolt());
            kwsEntCertificate.setExpireTime(businessLicense.getExpireTime());
            kwsEntCertificate.setRemark(businessLicense.getRemark());
            kwsEntCertificate.setStatus(Global.YES);
            kwsEntCertificate.setUpdateBy(LoginUserHolder.getUserId());
            kwsEntCertificate.setUpdateTime(new Date());
            kwsEntCertificate.setDelFlag(Global.NO);
            if (kwsEntCertificateDao.update(kwsEntCertificate) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }

            KwsEnterprise kwsEnterprise = new KwsEnterprise();
            kwsEnterprise.setId(kwsEntCertificate.getEntId());
            kwsEnterprise.setApproval(ApprovalEnum.REFRESH.getCode());
            kwsEnterpriseDao.updateById(kwsEnterprise);
        }
    }

    /**
     * @param params 查询参数
     * @return KwsEnterprise
     * @desc: 查询企业
     * @author: czh
     * @date: 2023/7/10
     */
    public List<KwsEnterprise> findEnts(Map<String, Object> params) {
        return kwsEnterpriseDao.findEnts(params);
    }

    /**
     * @param reqVo 查询入参
     * @return FindListGroupResVo
     * @desc: 查分组
     * @author: czh
     * @date: 2023/7/13
     */
    public List<FindListGroupResVo> findListGroup(EntFindPageReqVo reqVo) {
        List<FindListGroupResVo> result = new ArrayList<>();
        List<Long> authEntIdList = Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? new ArrayList<>() : LoginUserHolder.getAuthEntIdList();

        List<FindEntListPojo> list = findPojoManager(reqVo, authEntIdList);
        Map<Integer, List<FindEntListPojo>> collect = list.stream().collect(Collectors.groupingBy(FindEntListPojo::getApproval));
        FindListGroupResVo findListGroupResVo = new FindListGroupResVo();
        findListGroupResVo.setCount(list.size());
        result.add(findListGroupResVo);
        result.add(getGroup(ApprovalEnum.NO.getCode(), collect));

        FindListGroupResVo process = getGroup(ApprovalEnum.PROCESS.getCode(), collect);
        FindListGroupResVo refresh = getGroup(ApprovalEnum.REFRESH.getCode(), collect);
        process.setCount(process.getCount() + refresh.getCount());
        result.add(process);
        result.add(getGroup(ApprovalEnum.OK.getCode(), collect));
        result.add(getGroup(ApprovalEnum.PASS.getCode(), collect));
        return result;
    }

    private static FindListGroupResVo getGroup(Integer code, Map<Integer, List<FindEntListPojo>> collect) {
        FindListGroupResVo findListGroupResVo = new FindListGroupResVo();
        findListGroupResVo.setApproval(code);
        List<FindEntListPojo> findEntListPojos = collect.get(code);
        findListGroupResVo.setCount(CollectionUtils.isEmpty(findEntListPojos) ? Global.NO : findEntListPojos.size());
        findListGroupResVo.setApprovalName(ApprovalEnum.getName(code));
        return findListGroupResVo;
    }

    /**
     * @param id 企业id
     * @return EntDetailResVo
     * @desc: 查详情
     * @author: czh
     * @date: 2023/7/26
     */
    public EntDetailResVo detail(Long id, Boolean isAll) {
        KwsEnterprise kwsEnterprise = selectByKey(id);
        if (Objects.isNull(kwsEnterprise)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
        }
        EntDetailResVo entDetailResVo = new EntDetailResVo();
        BeanUtils.copyProperties(kwsEnterprise, entDetailResVo);

        KwsEnterprise kwsEnterprise1 = queryKwsEnterpriseById(kwsEnterprise.getPid());
        if (Objects.nonNull(kwsEnterprise1)) {
            entDetailResVo.setPEntName(kwsEnterprise1.getFirmName());
        }
        FindManagePojo manageInfoByEntId = kwsEnterpriseDao.findManageInfoByEntId(kwsEnterprise.getId());
        if (Objects.nonNull(manageInfoByEntId)) {
            entDetailResVo.setContactsId(manageInfoByEntId.getUserId());
        }

        List<KwsEntType> listByEntIds = kwsEntTypeDao.findListByEntIds(Collections.singletonList(kwsEnterprise.getId()));
        List<Integer> types = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(listByEntIds)) {
            types.addAll(listByEntIds.stream().map(KwsEntType::getType).toList());
        }

        if (Objects.isNull(isAll) || isAll) {
            List<KwsEntType> approvalByEntId = kwsEntTypeDao.findApprovalByEntId(kwsEnterprise.getId());
            if (CollectionUtils.isNotEmpty(approvalByEntId)) {
                types.addAll(approvalByEntId.stream().map(KwsEntType::getType).toList());
            }
        }

        if (CollectionUtils.isNotEmpty(types)) {
            entDetailResVo.setEntTypes(String.join(Global.COMMA, types.stream().map(String::valueOf).distinct().toList()));
        }


        List<KwsEntCheckTrack> list = kwsEntCheckTrackDao.findList(id);
        boolean isValid = false;
        if (CollectionUtils.isNotEmpty(list)) {
            isValid = list.stream()
                    .filter(item -> item.getStatus() != null)
                    .anyMatch(item -> item.getStatus().equals(Global.NO));
        }
        entDetailResVo.setValid(isValid);
        return entDetailResVo;
    }

    /**
     * @param id 企业信息
     * @desc 企业联系人信息
     * @author zk
     * @date 2023/9/1
     **/
    public Map<String, Object> detailOpen(Long id) {
        KwsEnterprise kwsEnterprise = selectByKey(id);
        if (Objects.isNull(kwsEnterprise)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
        }

        Map<String, Object> ent = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        ent.put("contacts", kwsEnterprise.getContacts());
        ent.put("phone", kwsEnterprise.getPhone());
        return ent;
    }

    /**
     * @param reqVo 入参
     * @return FindEntUserPojo
     * @desc: 查企业用户
     * @author: czh
     * @date: 2023/7/26
     */
    public List<FindEntUserPojo> findEntUser(FindListReqVo reqVo) {
        List<FindEntUserPojo> list = kwsEnterpriseDao.findUserByEntIds(Collections.singletonList(reqVo.getId()));
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        if (StringUtils.isNotBlank(reqVo.getName())) {
            list = list.stream().filter(item -> item.getName().contains(reqVo.getName())).toList();
        }

        return list;
    }


    /**
     * @param entId id
     * @return QueryCurrentOrganization
     * @desc: 查询企业的信息+主体机构信息
     * @author: czh
     * @date: 2023/7/22
     */
    public List<QueryCurrentOrganizationResVo> queryCurrentOrganization(Long entId) {
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(entId);
        if (Objects.isNull(entCacheResDto)) {
            return Collections.emptyList();
        }

        List<QueryCurrentOrganizationResVo> list = new ArrayList<>();
        QueryCurrentOrganizationResVo queryCurrentOrganizationResVo = new QueryCurrentOrganizationResVo();
        queryCurrentOrganizationResVo.setEntId(entCacheResDto.getId());
        queryCurrentOrganizationResVo.setEntName(entCacheResDto.getFirmName());
        queryCurrentOrganizationResVo.setContactsId(entCacheResDto.getContactsId());
        queryCurrentOrganizationResVo.setContacts(entCacheResDto.getContacts());
        queryCurrentOrganizationResVo.setPhone(entCacheResDto.getPhone());
        list.add(queryCurrentOrganizationResVo);

        //todo-xcq 应该需要查询下级企业
//        List<KwsEntDept> kwsEntDepts = kwsEntDeptDao.selectByEntPid(entId);
//        if (CollectionUtils.isNotEmpty(kwsEntDepts)) {
//            List<Long> entIdList = kwsEntDepts.stream().map(KwsEntDept::getEntId).toList();
//            Map<Long, EntCacheResDto> entCacheResDtoMap = remoteSystemService.queryEntCacheMapByIds(entIdList);
//            for (KwsEntDept kwsEntDept : kwsEntDepts) {
//                EntCacheResDto entCacheResDto1 = entCacheResDtoMap.get(kwsEntDept.getEntId());
//                if (Objects.nonNull(entCacheResDto1)) {
//                    QueryCurrentOrganizationResVo queryCurrentOrganizationResVo1 = new QueryCurrentOrganizationResVo();
//                    queryCurrentOrganizationResVo1.setEntId(entCacheResDto1.getId());
//                    queryCurrentOrganizationResVo1.setEntName(entCacheResDto1.getFirmName());
//                    queryCurrentOrganizationResVo1.setPid(kwsEntDept.getEntPid());
//                    queryCurrentOrganizationResVo1.setContactsId(entCacheResDto1.getContactsId());
//                    queryCurrentOrganizationResVo1.setContacts(entCacheResDto1.getContacts());
//                    queryCurrentOrganizationResVo1.setPhone(entCacheResDto1.getPhone());
//                    list.add(queryCurrentOrganizationResVo1);
//                }
//            }
//        }

        //填充企业属性
        List<Long> entIds = list.stream().map(QueryCurrentOrganizationResVo::getEntId).toList();
        List<KwsEntType> listByEntIds = kwsEntTypeDao.findListByEntIds(entIds);
        if (CollectionUtils.isNotEmpty(listByEntIds)) {
            Map<Long, List<KwsEntType>> collect = listByEntIds.stream().collect(Collectors.groupingBy(KwsEntType::getEntId));
            for (QueryCurrentOrganizationResVo queryCurrentOrganizationResVo1 : list) {
                List<KwsEntType> kwsEntTypes = collect.get(queryCurrentOrganizationResVo1.getEntId());
                if (CollectionUtils.isNotEmpty(kwsEntTypes)) {
                    queryCurrentOrganizationResVo1.setEntTypes(String.join(Global.COMMA, kwsEntTypes.stream().map(KwsEntType::getType).map(String::valueOf).distinct().toList()));
                }
            }
        }

        return list;
    }

    /**
     * @param entId id
     * @return QueryCurrentOrganization
     * @desc: 查询其他入驻企
     * @author: czh
     * @date: 2023/7/22
     */
    public List<QueryCurrentOrganizationResVo> queryOtherEnt(Long entId, HttpServletRequest request) {
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseDao.selectByKeys(null);
        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            return Collections.emptyList();
        }

        //专场逻辑
        String accessSpecial = request.getHeader("Access-Special");
        //是否主平台
        boolean mainPlatform = remoteSystemService.queryMainPlatform(accessSpecial);
        if (!mainPlatform) {
            List<Long> entIds = remoteSystemService.queryEntIdsByCode(accessSpecial, null);
            if (CollectionUtils.isEmpty(entIds)) {
                return Collections.emptyList();
            }
//            kwsEnterprises = kwsEnterprises.stream().filter(item -> !entIds.contains(item.getId())).collect(Collectors.toList());
            List<Long> longList = kwsEnterprises.stream().map(KwsEnterprise::getId).distinct().collect(Collectors.toList());
            List<Long> intersection = longList.stream().filter(entIds::contains).collect(Collectors.toList());
            kwsEnterprises = kwsEnterpriseDao.selectByKeys(intersection);
        } else {
            //求交集数据
            List<Long> entIds = remoteSystemService.queryEntIdsByCode(accessSpecial, null);
            List<Long> longList = kwsEnterprises.stream().map(KwsEnterprise::getId).distinct().collect(Collectors.toList());
            List<Long> intersection = longList.stream().filter(entIds::contains).collect(Collectors.toList());
            kwsEnterprises = kwsEnterpriseDao.selectByKeys(intersection);
        }
        if (kwsEnterprises.size() < 1) {
            return Collections.emptyList();
        }
        //过滤除了当前企业的其他企业
        kwsEnterprises = kwsEnterprises.stream().filter(item -> !item.getId().equals(entId)).toList();
        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            return Collections.emptyList();
        }

        //过滤当前企业的主体机构
        List<KwsEntDept> kwsEntDepts = kwsEntDeptDao.selectByEntPid(entId);
        if (CollectionUtils.isNotEmpty(kwsEntDepts)) {
            List<Long> entIdList = kwsEntDepts.stream().map(KwsEntDept::getEntId).toList();
            kwsEnterprises = kwsEnterprises.stream().filter(item -> !entIdList.contains(item.getId())).toList();
        }

        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            return Collections.emptyList();
        }

        Map<Long, List<KwsEntType>> collect = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        List<KwsEntType> kwsEntTypeList = kwsEntTypeDao.findListByEntIds(kwsEnterprises.stream().map(KwsEnterprise::getId).toList());
        if (CollectionUtils.isNotEmpty(kwsEntTypeList)) {
            collect = kwsEntTypeList.stream().collect(Collectors.groupingBy(KwsEntType::getEntId));
        }

        List<FindManagePojo> manageInfoByEntIds = kwsEnterpriseDao.findManageInfoByEntIds(kwsEnterprises.stream().map(KwsEnterprise::getId).toList());
        Map<Long, KwsUser> userCollect = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        Map<Long, FindManagePojo> manageInfoCollect = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(manageInfoByEntIds)) {
            List<KwsUser> kwsUsers = kwsUserService.selectByKeys(manageInfoByEntIds.stream().map(FindManagePojo::getUserId).toList());
            if (CollectionUtils.isNotEmpty(kwsUsers)) {
                userCollect = kwsUsers.stream().collect(Collectors.toMap(KwsUser::getId, e -> e, (n, o) -> n));
            }

            manageInfoCollect = manageInfoByEntIds.stream().collect(Collectors.toMap(FindManagePojo::getEntId, Function.identity()));
        }

        List<QueryCurrentOrganizationResVo> list = new ArrayList<>();
        for (KwsEnterprise kwsEnterprise : kwsEnterprises) {
            QueryCurrentOrganizationResVo queryCurrentOrganizationResVo = new QueryCurrentOrganizationResVo();
            List<KwsEntType> kwsEntTypeList1 = collect.get(kwsEnterprise.getId());
            queryCurrentOrganizationResVo.setEntTypes(CollectionUtils.isEmpty(kwsEntTypeList1) ? null : String.join(Global.COMMA, kwsEntTypeList1.stream().map(KwsEntType::getType).map(String::valueOf).toList()));
            FindManagePojo findManagePojo = manageInfoCollect.get(kwsEnterprise.getId());
            if (Objects.nonNull(findManagePojo)) {
                queryCurrentOrganizationResVo.setContactsId(findManagePojo.getUserId());
                KwsUser kwsUser = userCollect.get(findManagePojo.getUserId());
                if (Objects.nonNull(kwsUser)) {
                    queryCurrentOrganizationResVo.setContacts(kwsUser.getName());
                    queryCurrentOrganizationResVo.setPhone(kwsUser.getPhone());
                }
            } else {
                queryCurrentOrganizationResVo.setContacts(kwsEnterprise.getContacts());
                queryCurrentOrganizationResVo.setPhone(kwsEnterprise.getPhone());
            }
            queryCurrentOrganizationResVo.setCityName(kwsEnterprise.getCityName());
            queryCurrentOrganizationResVo.setBusiness(kwsEnterprise.getBusiness());
            queryCurrentOrganizationResVo.setEntId(kwsEnterprise.getId());
            queryCurrentOrganizationResVo.setEntName(kwsEnterprise.getFirmName());
            queryCurrentOrganizationResVo.setCooperateTypes(getCooperateType(kwsEntTypeList1));
            list.add(queryCurrentOrganizationResVo);
        }
        return list;
    }


    /**
     * @param kwsEntTypeList 企业类型集合
     * @return String
     * @desc: 根据企业属性返回可供合作的属性
     * @author: czh
     * @date: 2023/8/1
     */
    private String getCooperateType(List<KwsEntType> kwsEntTypeList) {
        if (CollectionUtils.isEmpty(kwsEntTypeList)) {
            return null;
        }

        List<Integer> cooperateTypeList = new ArrayList<>();
        for (KwsEntType kwsEntType : kwsEntTypeList) {
            if (EntTypeEnum.SUPPLIER.getCode() == kwsEntType.getType()) {
                cooperateTypeList.add(CooperateTypeEnum.SUPPLIER.getCode());
                cooperateTypeList.add(CooperateTypeEnum.CONSIGN.getCode());
            }

            if (EntTypeEnum.PURCHASER.getCode() == kwsEntType.getType()) {
                cooperateTypeList.add(CooperateTypeEnum.PURCHASER.getCode());
                cooperateTypeList.add(CooperateTypeEnum.CONSIGN.getCode());
            }

            if (EntTypeEnum.LOGISTICS3.getCode() == kwsEntType.getType()) {
                cooperateTypeList.add(CooperateTypeEnum.CONSIGN.getCode());
                cooperateTypeList.add(CooperateTypeEnum.CARRIAGE.getCode());
            }

            if (EntTypeEnum.LOGISTICS4.getCode() == kwsEntType.getType()) {
                cooperateTypeList.add(CooperateTypeEnum.CARRIAGE.getCode());
            }
        }

        return String.join(Global.COMMA, cooperateTypeList.stream().distinct().map(String::valueOf).toList());
    }

    /**
     * @param entId 企业ID
     * @desc 企业详情(企业登录 / 司机登录)
     * @author zk
     * @date 2023/8/10
     **/
    public EntCacheResDto queryEntDetails(Long entId) {
        //企业信息
        KwsEnterprise enterprise = kwsEnterpriseDao.selectByKey(entId);
        if (enterprise == null) {
            return null;
        }
        EntCacheResDto entCacheResDto = new EntCacheResDto();
        BeanUtils.copyProperties(enterprise, entCacheResDto);
        entCacheResDto.setId(enterprise.getId());
        entCacheResDto.setFirmName(enterprise.getFirmName());
        entCacheResDto.setApproval(enterprise.getApproval());
        entCacheResDto.setRegTime(enterprise.getRegTime());
        entCacheResDto.setContacts(enterprise.getContacts());
        entCacheResDto.setPhone(enterprise.getPhone());
        entCacheResDto.setBusiness(enterprise.getBusiness());
        entCacheResDto.setCityName(enterprise.getCityName());
        entCacheResDto.setCityCode(enterprise.getCityCode());
        entCacheResDto.setStatus(enterprise.getStatus());
        //企业类型
        List<KwsEntType> entTypes = kwsEntTypeDao.findListByEntId(entId);
        if (CollectionUtils.isNotEmpty(entTypes)) {
            entCacheResDto.setEntTypes(String.join(Global.COMMA, entTypes.stream().map(KwsEntType::getType).map(String::valueOf).distinct().toList()));
            entCacheResDto.setEntTypeNames(EntTypeEnum.getNames(entCacheResDto.getEntTypes()));
        }

        Map<String, Object> queryParams = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("isMain", Global.YES);
            put("entId", entId);
            put("systemType", SystemTypeEnum.COMPANY.getCode());
        }};
        List<KwsUserResVo> users = kwsUserService.findPage(queryParams);
        if (CollectionUtils.isNotEmpty(users)) {
            KwsUserResVo kwsUserResVo = users.get(0);
            entCacheResDto.setContactsId(kwsUserResVo.getId());
            entCacheResDto.setContacts(kwsUserResVo.getName());
            entCacheResDto.setPhone(kwsUserResVo.getPhone());
        }

        //企业资质有效性判断  1、当前资质没过期，且状态是已认证  2、只要有认证过一次就算有效  参数判断
        String checkType = String.valueOf(Global.NUMERICAL_TWO);
        entCacheResDto.setValid(false); // 设置默认值
        if (checkType.equals(Global.NUMERICAL_ONE)) {
            List<CertificateResVo> certificates = queryCertificate(entId);
            if (CollectionUtils.isNotEmpty(certificates)) {
                // 只要有一个证书有效，则企业有效
                boolean hasValidCertificate = certificates.stream()
                        .filter(cert -> cert.getExpireTime() != null)
                        .anyMatch(certificate -> DateUtil.compare(new Date(), certificate.getExpireTime()) <= 0);
                entCacheResDto.setValid(hasValidCertificate);
            }
        } else {
            List<KwsEntCheckTrack> entCheckTrackResDtoList = entCheck(entId);
            if (CollectionUtils.isNotEmpty(entCheckTrackResDtoList)) {
                boolean hasApprovedRecord = entCheckTrackResDtoList.stream()
                        .filter(item -> item.getStatus() != null)
                        .anyMatch(item -> item.getStatus() == Global.NO);
                entCacheResDto.setValid(hasApprovedRecord);
            }
        }

        return entCacheResDto;
    }

    /**
     * @param cityCode 区域code  entTypeList 企业类型 entIdList 企业id
     * @return PageResult
     * @desc: 根据区域code和企业类型分页查询企业信息
     * @author: czh
     * @date: 2023/9/1
     */
    public List<KwsEnterprise> queryEntInfoByCityCodeAndEntTypesWithPage(Integer cityCode, List<Integer> entTypeList, List<Long> entIdList, String entName) {
        return kwsEnterpriseDao.queryEntInfoByCityCodeAndEntTypesWithPage(cityCode, entTypeList, entIdList, entName);
    }

    /**
     * @param reqVo 查询
     * @return QueryCustomerResVo
     * @desc: 客户列表分组个数
     * @author: czh
     * @date: 2023/9/14
     */
    public List<QueryCustomerResVo> queryCustomerGroup(EntFindPageReqVo reqVo) {
        List<QueryCustomerResVo> result = new ArrayList<>();
        List<Long> authEntIdList = Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? new ArrayList<>() : LoginUserHolder.getAuthEntIdList();

        List<FindEntListPojo> list = findPojoManager(reqVo, authEntIdList);
        Map<Integer, List<FindEntListPojo>> collect = list.stream().collect(Collectors.groupingBy(FindEntListPojo::getStatus));

        List<FindEntListPojo> findEntListPojos1 = collect.get(Global.NO);
        QueryCustomerResVo queryCustomerResVo1 = new QueryCustomerResVo();
        queryCustomerResVo1.setStatus(Global.NO);
        queryCustomerResVo1.setStatusName("正常");
        queryCustomerResVo1.setCnt(CollectionUtils.isEmpty(findEntListPojos1) ? 0 : findEntListPojos1.size());

        List<FindEntListPojo> findEntListPojos2 = collect.get(Global.YES);
        QueryCustomerResVo queryCustomerResVo2 = new QueryCustomerResVo();
        queryCustomerResVo2.setStatus(Global.YES);
        queryCustomerResVo2.setStatusName("冻结");
        queryCustomerResVo2.setCnt(CollectionUtils.isEmpty(findEntListPojos2) ? 0 : findEntListPojos2.size());

        QueryCustomerResVo queryCustomerResVo = new QueryCustomerResVo();
        queryCustomerResVo.setStatusName("全部");
        queryCustomerResVo.setCnt(queryCustomerResVo1.getCnt() + queryCustomerResVo2.getCnt());
        result.add(queryCustomerResVo);
        result.add(queryCustomerResVo1);
        result.add(queryCustomerResVo2);
        return result;
    }

    private void getDefaultReturn(List<QueryCustomerResVo> result) {
        QueryCustomerResVo queryCustomerResVo1 = new QueryCustomerResVo();
        queryCustomerResVo1.setStatus(Global.NO);
        queryCustomerResVo1.setStatusName("正常");
        queryCustomerResVo1.setCnt(0);

        QueryCustomerResVo queryCustomerResVo2 = new QueryCustomerResVo();
        queryCustomerResVo2.setStatus(Global.YES);
        queryCustomerResVo2.setStatusName("冻结");
        queryCustomerResVo2.setCnt(0);

        QueryCustomerResVo queryCustomerResVo = new QueryCustomerResVo();
        queryCustomerResVo.setStatusName("全部");
        queryCustomerResVo.setCnt(0);
        result.add(queryCustomerResVo);
        result.add(queryCustomerResVo1);
        result.add(queryCustomerResVo2);
    }


    /**
     * @desc: 入驻认证导出
     * @author: czh
     * @date: 2023/9/21
     */
    public void exportEntSettle(EntFindPageReqVo reqVo, HttpServletResponse response) {
        List<Long> authEntIdList = Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? new ArrayList<>() : LoginUserHolder.getAuthEntIdList();

        if (CollectionUtils.isEmpty(authEntIdList)) {
            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
            if (ids.size() < 1) {
                throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
            }
        }
//        List<FindEntListPojo> list = findPojo(reqVo);
        List<FindEntListPojo> list = findPojoManager(reqVo, authEntIdList);
        List<EntFindPageResVo> result = new ArrayList<>();

        if (CollectionUtils.isEmpty(list)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        for (FindEntListPojo item : list) {
            EntFindPageResVo entFindPageResVo = new EntFindPageResVo();
            BeanUtils.copyProperties(item, entFindPageResVo);
            entFindPageResVo.setApprovalName(ApprovalEnum.getName(item.getApproval()));
            entFindPageResVo.setApprovalTime(item.getApprovalTime());
            entFindPageResVo.setEntTypes(item.getType());
            entFindPageResVo.setEntryType(item.getSystemType().equals(SystemTypeEnum.MANAGE.getCode()) ? EntryTypeEnum.PLATFORM.getCode() : EntryTypeEnum.SELF.getCode());
            entFindPageResVo.setEntryTypeStr(EntryTypeEnum.getName(entFindPageResVo.getEntryType()).getName());

            if (item.getType().contains(String.valueOf(EntTypeEnum.SUPPLIER.getCode()))) {
                entFindPageResVo.setEnt1("是");
            }
            if (item.getType().contains(String.valueOf(EntTypeEnum.PURCHASER.getCode()))) {
                entFindPageResVo.setEnt2("是");
            }
            if (item.getType().contains(String.valueOf(EntTypeEnum.LOGISTIC.getCode()))) {
                entFindPageResVo.setEnt3("是");
            }
//            if (item.getType().contains(String.valueOf(EntTypeEnum.LOGISTICS4.getCode()))) {
//                entFindPageResVo.setEnt4("是");
//            }
            if (entFindPageResVo.getManager() != null) {
                KwsUser kwsUser = userDao.selectByKey(entFindPageResVo.getManager());
                entFindPageResVo.setManagerName(kwsUser == null ? null : kwsUser.getName());
            }
            result.add(entFindPageResVo);
        }

        if (Objects.isNull(reqVo.getCustomer())) {
            ExcelUtil.downData(response, EntSettleExcel.class, BeanUtils.copyToList(result, EntSettleExcel.class));
        } else {
            ExcelUtil.downData(response, EntCustomerExcel.class, BeanUtils.copyToList(result, EntCustomerExcel.class));
        }
    }

    /**
     * 企业用户绑定客户经理
     *
     * @param vo
     */
    @Transactional
    public void enterpriseBindManage(EnterpriseBindManagerVo vo) {
        long managerId = Long.parseLong(vo.getManagerId());
        String enterpriseIds = vo.getEnterpriseIds();
        List<Long> enterpriseList = StringUtils.splitStrToList(enterpriseIds, Long.class);
        enterpriseList.forEach(id -> {
            KwsEnterprise enterprise = kwsEnterpriseDao.selectByKey(id);
            enterprise.setManager(managerId);
            kwsEnterpriseDao.updateById(enterprise);
        });
        //清除缓存  新增缓存
        String key = Global.getCustomerManagerUserLoginKey(SystemTypeEnum.MANAGE.getCode(), managerId);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(key)) {
            RedissonUtils.delete(key);
        }
        RedissonUtils.putSet(key, enterpriseIds);
    }

    public List<KwsUserSystemTypeVo> getManagerAll() {
//        List<KwsUser> list = userDao.selectManager();
        List<KwsUserSystemTypeVo> list = userDao.selectUserBySystemTypeAndMain(SystemTypeEnum.MANAGE.getCode(), NumberConstant.ZERO);
        return list;
    }

    public HttpResult findAllEnterprise() {
        List<KwsEnterprise> enterprises = kwsEnterpriseDao.findAllEnterprise();
        return HttpResult.ok(enterprises);
    }

    public List<PlatformEnterpriseResVo> findPlatformEnterprise() {
        List<KwsEnterprise> enterprises = kwsEnterpriseRepository.list(Wrappers.<KwsEnterprise>lambdaQuery()
                .eq(BaseModel::getDelFlag, Global.UN_DELETED)
                .eq(BaseModel::getStatus, Global.NO)
                .orderByDesc(BaseModel::getCreateTime));
        if (CollectionUtils.isEmpty(enterprises)) {
            return List.of();
        }

//        Set<Long> parentIds = enterprises.stream()
//                .map(KwsEnterprise::getPid)
//                .filter(Objects::nonNull)
//                .filter(pid -> pid > 0)
//                .collect(Collectors.toSet());
//        Map<Long, String> parentNameMap = CollectionUtils.isEmpty(parentIds) ? Collections.emptyMap()
//                : kwsEnterpriseRepository.list(Wrappers.<KwsEnterprise>lambdaQuery()
//                        .in(KwsEnterprise::getId, parentIds)
//                        .eq(BaseModel::getDelFlag, Global.UN_DELETED)
//                        .eq(BaseModel::getStatus, Global.NO))
//                .stream()
//                .collect(Collectors.toMap(KwsEnterprise::getId, KwsEnterprise::getFirmName, (v1, v2) -> v1));

        return enterprises.stream().map(item -> {
            PlatformEnterpriseResVo vo = new PlatformEnterpriseResVo();
            vo.setId(item.getId());
            vo.setFirmName(item.getFirmName());
            return vo;
        }).collect(Collectors.toList());
    }

    public EntInfoResp queryEntInfo(EntInfoReq req) {
        //如果是发起方是采购方，采购方只能是自己和下级，供应方可以选所有入住的供应企业
        // 如果发起方是供应方，则供应方是能自己和下级，采购方可以是所有入住企业
        if (org.apache.commons.lang3.StringUtils.isBlank(req.getEntId())) {
            throw new BusinessException("企业id不能为空");
        }
        KwsEntType kwsEntType = kwsEntTypeRepository.queryByEntId(req.getEntId());
        if (Objects.nonNull(kwsEntType)) {
            req.setLoginEntType(String.valueOf(kwsEntType.getType()));
        }
        if (req.getEntType().contains(req.getLoginEntType())) {
            //登录客户的企业类型和查询的类型是一直的说明只能查询自己和自己的下级
            //发起方的公司信息
            return getEntInfoResp(req);
        }
        //被邀请方的企业信息
        //根据类型查询企业id
        return getInfoResp(req);
    }

    @NotNull
    private EntInfoResp getInfoResp(EntInfoReq req) {
        EntInfoResp entInfoResp = buildEntInfoResp(req);
        List<KwsEntType> kwsEntTypes = kwsEntTypeRepository.queryByType(req.getEntType());
        if (CollectionUtils.isEmpty(kwsEntTypes)) {
            return entInfoResp;
        }
        Set<Long> entIds = kwsEntTypes.stream().map(KwsEntType::getEntId).collect(Collectors.toSet());
        //根据企业id查询企业信息
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseRepository.queryByEntIds(entIds, req.getEntName());
        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            return entInfoResp;
        }
        //组装返回对象
        List<EntInfoResp.EntInfo> entInfos = kwsEnterprises.stream().map(k -> {
            EntInfoResp.EntInfo info = new EntInfoResp.EntInfo();
            info.setEntId(String.valueOf(k.getId()));
            info.setEntName(k.getFirmName());
            return info;
        }).collect(Collectors.toList());
        entInfoResp.setEntInfos(entInfos);
        return entInfoResp;
    }

    @NotNull
    private EntInfoResp getEntInfoResp(EntInfoReq req) {
        EntInfoResp entInfoResp = buildEntInfoResp(req);
        if (org.apache.commons.lang3.StringUtils.isBlank(req.getEntId())) {
            throw new BusinessException("企业id不能为空");
        }
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseRepository.queryByEntIdAndName(req.getEntId(), req.getEntName());
        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            return entInfoResp;
        }
        Set<Long> entIds = kwsEnterprises.stream().map(BaseModel::getId).collect(Collectors.toSet());

        //查询父企业
        List<KwsEnterprise> parentEnts = kwsEnterpriseRepository.queryByParentEntIds(entIds);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(parentEnts)) {
            kwsEnterprises.addAll(parentEnts);
        }
        //根据类型进行过滤
        List<KwsEntType> kwsEntTypes = kwsEntTypeRepository.queryByEntIdsAndType(entIds, req.getEntType());
        if (CollectionUtils.isEmpty(kwsEntTypes)) {
            return entInfoResp;
        }
        Set<Long> entIdList = kwsEntTypes.stream().map(KwsEntType::getEntId).collect(Collectors.toSet());
        //过滤类型表中包含的数据
        List<EntInfoResp.EntInfo> entInfos = kwsEnterprises.stream().filter(x -> entIdList.contains(x.getId())).map(k -> {
            EntInfoResp.EntInfo info = new EntInfoResp.EntInfo();
            info.setEntId(String.valueOf(k.getId()));
            info.setEntName(k.getFirmName());
            return info;
        }).collect(Collectors.toList());
        entInfoResp.setEntInfos(entInfos);
        return entInfoResp;
    }

    private EntInfoResp buildEntInfoResp(EntInfoReq req) {
        EntInfoResp entInfoResp = new EntInfoResp();
        entInfoResp.setBuyer(Objects.equals(req.getLoginEntType(), String.valueOf(EntTypeEnum.PURCHASER.getCode())));
        return entInfoResp;
    }

    /**
     * @return
     */
    public EntFindInfoResp querySupOrProEnt() {
        EntFindInfoResp entFindInfoResp = new EntFindInfoResp();
        //查询当前登录企业
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId());
        if (entCacheResDto == null) {
            throw new RuntimeException("entId:" + LoginUserHolder.getEntId() + ", 企业信息不存在！");
        }
        //校验
        int entType = Integer.parseInt(entCacheResDto.getEntTypes());
        if (entType != EntTypeEnum.SUPPLIER.getCode()) {
            throw new RuntimeException("entId:" + LoginUserHolder.getEntId() + ", 只有供应商企业可以创建钱包！");
        }

        //查询当前供应商的子级企业
        List<KwsEntDeptDto> subEntList = remoteSystemService.queryEntDeptByPid(entCacheResDto.getParentId());
        if (CollectionUtils.isEmpty(subEntList)) {
            EntFindInfoVO entFindInfoVO = EntFindInfoVO.toPageResp(entCacheResDto);
            //子级为空，只返回父级供应商
            entFindInfoResp.setSupEntInfo(Lists.newArrayList(entFindInfoVO));
        } else {
            List<Long> parentId = subEntList.stream().map(KwsEntDeptDto::getEntId).collect(Collectors.toList());
            List<EntCacheResDto> entDtoList = remoteSystemService.queryEntCacheByIds(parentId);
            entDtoList.add(0, entCacheResDto);
            List<EntFindInfoVO> entFindInfoVOList = entDtoList.stream().map(EntFindInfoVO::toPageResp).collect(Collectors.toList());
            entFindInfoResp.setSupEntInfo(entFindInfoVOList);
        }
        //查询采购商企业信息
        List<EntCacheResDto> proEntList = queryKwsEnterpriseById();
        List<EntFindInfoVO> proEntVOList = proEntList.stream().map(EntFindInfoVO::toPageResp).collect(Collectors.toList());
        entFindInfoResp.setProEntInfo(proEntVOList);

        return entFindInfoResp;
    }

    /**
     * @return KwsEnterprise
     * @desc: 放开接口
     * @author: czh
     * @date: 2023/7/26
     */
    public List<EntCacheResDto> queryKwsEnterpriseById() {
        //查询采购商企业信息
        LambdaQueryWrapper<KwsEntType> queryWrapper = Wrappers.<KwsEntType>lambdaQuery().eq(KwsEntType::getType, 2).eq(KwsEntType::getDelFlag, 0);
        List<KwsEntType> kwsEntTypes = kwsEntTypeDao.selectList(queryWrapper);
        if (kwsEntTypes.isEmpty()) {
            return new ArrayList<>();
        }
        List<Long> entId = kwsEntTypes.stream().map(KwsEntType::getEntId).distinct().collect(Collectors.toList());
        return remoteSystemService.queryEntCacheByIds(entId);

    }

    public EntInfoResp queryKwsEnterprise(EntInfoReq req) {
        log.info("查询企业信息请求参数：{}", JSON.toJSONString(req));
        return getInfoResp(req);

    }

    public List<EntInfo> queryEnterpriseByPageType(EnterprisePageQueryReqVo req) {
        log.info("查询企业信息请求参数：{}", JSON.toJSONString(req));

        Long loginEntId = LoginUserHolder.getEntId();
        if (Objects.isNull(loginEntId)) {
            return Collections.emptyList();
        }

        List<KwsEntType> entTypes = kwsEntTypeDao.findListByEntId(loginEntId);
        boolean matchEnterpriseType = CollectionUtils.isNotEmpty(entTypes)
                && entTypes.stream().anyMatch(item -> Objects.equals(item.getType(), req.getEnterpriseType()));
        if (!matchEnterpriseType) {
            return Collections.emptyList();
        }

        List<KwsEnterprise> enterprises = kwsEnterpriseRepository.list(Wrappers.<KwsEnterprise>lambdaQuery()
                .eq(BaseModel::getDelFlag, Global.UN_DELETED)
                .eq(BaseModel::getStatus, Global.NO)
                .eq(KwsEnterprise::getApproval, ApprovalEnum.OK.getCode())
                .eq(KwsEnterprise::getId, loginEntId)
                .like(StringUtils.isNotBlank(req.getEntName()), KwsEnterprise::getFirmName, req.getEntName())
                .orderByAsc(KwsEnterprise::getFirmName));
        if (CollectionUtils.isEmpty(enterprises)) {
            return Collections.emptyList();
        }

        return enterprises.stream().map(item -> {
            EntInfo info = new EntInfo();
            info.setEntId(String.valueOf(item.getId()));
            info.setEntName(item.getFirmName());
            return info;
        }).collect(Collectors.toList());
    }

    public EntInfo queryEnt(String entName) {
        return kwsEnterpriseDao.query(entName);
    }

    public List<EntBaseInfo> childEnt() {
        return kwsEnterpriseDao.queryCte(LoginUserHolder.getEntId());
    }

    public List<EntBaseInfo> list() {
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseDao.selectList(new LambdaQueryWrapper<KwsEnterprise>().eq(KwsEnterprise::getPid, 0).eq(KwsEnterprise::getApproval, 1).eq(KwsEnterprise::getStatus, 0));
        return kwsEnterprises.stream().map(d -> BeanUtils.toBean(d, EntBaseInfo.class)).collect(Collectors.toList());
    }
    @Nullable
    private EntCacheResDto getEntCacheResDto(Long entId) {
        KwsEnterpriseResDto kwsEnterpriseResDto = remoteBaseService.queryEnterpriseById(entId);
        if (Objects.isNull(kwsEnterpriseResDto)) {
            return null;
        }

        EntCacheResDto entCacheResDto = new EntCacheResDto();
        BeanUtils.copyProperties(kwsEnterpriseResDto, entCacheResDto);
//        entCacheResDto.setDeptInfo(remoteBaseService.queryDeftInfoByEntId(entId));
        entCacheResDto.setCertificateInfo(remoteBaseService.queryCertificateByEntId(entId));
        KwsUser kwsUser = remoteBaseService.queryManageByEntId(entId);
        if (Objects.nonNull(kwsUser)) {
            entCacheResDto.setContactsId(kwsUser.getId());
            entCacheResDto.setContacts(kwsUser.getName());
            entCacheResDto.setPhone(kwsUser.getPhone());
        }
        List<EntTypeResDto> entTypeResDtos = remoteBaseService.queryEntTypeById(entId);
        if (CollectionUtils.isNotEmpty(entTypeResDtos)) {
            entCacheResDto.setEntTypes(String.join(Global.COMMA, entTypeResDtos.stream().map(EntTypeResDto::getType).map(String::valueOf).distinct().toList()));
            entCacheResDto.setEntTypeNames(EntTypeEnum.getNames(entCacheResDto.getEntTypes()));
        }
        return entCacheResDto;
    }
    public EntCacheResDto queryEntCacheById(Long entId) {
        if (Objects.isNull(entId)) {
            return null;
        }
        EntCacheResDto entCacheResDto = getEntCacheResDto(entId);
        if (Objects.isNull(entCacheResDto)) {
            return null;
        }
        return entCacheResDto;
    }
}
