package com.sckw.system.service;

import java.util.Date;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
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.excel.utils.ExcelUtil;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.UserInfo;
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.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.model.vo.res.KwsUserResVo;
import jakarta.servlet.http.HttpServletResponse;
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
public class KwsEnterpriseService {

    @Autowired
    private KwsEnterpriseDao kwsEnterpriseDao;

    @Autowired
    private KwsEntTypeDao kwsEntTypeDao;

    @Autowired
    private KwsEntCertificateDao kwsEntCertificateDao;

    @Autowired
    private KwsEntCheckTrackDao kwsEntCheckTrackDao;

    @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 RemoteSystemServiceImpl remoteSystemService;

    @Autowired
    private SysAreaDao sysAreaDao;

    @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.update(kwsEnterprise) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
            }
        }

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

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

    public static void main(String[] args) {
    }

    /**
     * @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.update(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;
    }


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


    /**
     * @param reqVo 分页入参
     * @return HttpResult
     * @desc: 分页查询
     * @author: czh
     * @date: 2023/6/9
     */
    public PageResult findPage(EntFindPageReqVo reqVo) {
        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());
        List<FindEntListPojo> list = findPojo(reqVo);
        List<EntFindPageResVo> result = new ArrayList<>();

        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());
            result.add(entFindPageResVo);
        }
        return PageHelperUtil.getPageResult(new PageInfo<>(result), list, reqVo.getPageSize());
    }

    /**
     * @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) {
        checkRegisterParam(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);
        }

        Long entId = kwsEnterprise.getId();
        Date date = new Date();
        Long userId = LoginUserHolder.getUserId();
        kwsEnterprise.setCode(reqVo.getCode());
        kwsEnterprise.setLegalName(reqVo.getLegalName());
        kwsEnterprise.setLegalPhone(reqVo.getLegalPhone());
        kwsEnterprise.setHead(reqVo.getHead());
        kwsEnterprise.setRegSource(LoginUserHolder.getClientType());
        kwsEnterprise.setCityCode(reqVo.getCityCode());
        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());
        kwsEnterprise.setApproval(kwsEnterprise.getApproval().equals(ApprovalEnum.OK.getCode()) ? ApprovalEnum.REFRESH.getCode() : ApprovalEnum.PROCESS.getCode());
        if (kwsEnterpriseDao.update(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }

        /*2、存企业类型,一个企业可以有多个类型*/
        List<KwsEntType> listByEntId = kwsEntTypeDao.findListByEntId(entId);
        List<Integer> currentTypeList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(listByEntId)) {
            currentTypeList.addAll(listByEntId.stream().map(KwsEntType::getType).toList());
        }
        List<Integer> typeList = Arrays.stream(reqVo.getEntTypes().split(Global.COMMA)).map(Integer::parseInt).toList();

        if (typeList.contains(EntTypeEnum.LOGISTICS3.getCode()) && typeList.contains(EntTypeEnum.LOGISTICS4.getCode())) {
            throw new SystemException(HttpStatus.CODE_10301, HttpStatus.PL34);
        }

        if (currentTypeList.contains(EntTypeEnum.LOGISTICS3.getCode()) && typeList.contains(EntTypeEnum.LOGISTICS4.getCode())) {
            throw new SystemException(HttpStatus.CODE_10301, HttpStatus.PL34);
        }

        if (currentTypeList.contains(EntTypeEnum.LOGISTICS4.getCode()) && typeList.contains(EntTypeEnum.LOGISTICS3.getCode())) {
            throw new SystemException(HttpStatus.CODE_10301, HttpStatus.PL34);
        }

        for (Integer item : typeList) {
            if (currentTypeList.contains(item)) {
                continue;
            }
            KwsEntType kwsEntType = new KwsEntType();
            kwsEntType.setEntId(entId);
            kwsEntType.setType(item);
            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);
        }


        //子公司不用新建机构、角色等，直接返回
        Map<String, Object> map = new HashMap<>();
        map.put("entName", kwsEnterprise.getFirmName());
        map.put("createByName", kwsEnterprise.getContacts());
        if (Objects.nonNull(reqVo.getEntPid())) {
            KwsEntDept kwsEntDept = new KwsEntDept();
            kwsEntDept.setEntId(entId);
            kwsEntDept.setEntPid(reqVo.getEntPid());
            kwsEntDept.setId(new IdWorker(1L).nextId());
            if (kwsEntDeptDao.insert(kwsEntDept) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
            }

            commonService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(userId).setEntId(reqVo.getEntPid())),
                    MessageEnum.ENT_CERTIFICATE,
                    map,
                    entDeptUrl, "");
        } else {
            commonService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(userId).setEntId(entId)),
                    MessageEnum.ENT_CERTIFICATE,
                    map,
                    entCertificateUrl, appEntCertificateUrl);
        }
    }

    /**
     * @param reqVo 注册入参
     * @desc: 校验注册入参
     * @author: czh
     * @date: 2023/7/25
     */
    private void checkRegisterParam(EntRegisterReqVo reqVo) {
    }

    /**
     * 企业审批
     */
    @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 (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);
        }

        KwsEntDept kwsEntDept = kwsEntDeptDao.selectByEntId(entId);
        //主体机构不用走后面的流程
        if (Objects.isNull(kwsEntDept)) {
            /*第一次审批通过（非更新资质审批通过），构建机构角色等*/
            if (ApprovalEnum.OK.getCode() == status) {
                if (ApprovalEnum.PROCESS.getCode() == currentApproval) {
                    /*审批通过，绑定角色*/
                    FindManagePojo findManagePojo = kwsEnterpriseDao.findManageInfoByEntIdBeforeApproval(entId);
                    if (Objects.isNull(findManagePojo)) {
                        throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
                    }
                    KwsUser userByAccount = kwsUserService.getUserByAccount(kwsEnterprise.getPhone(), SystemTypeEnum.COMPANY.getCode());
                    if (Objects.isNull(userByAccount)) {
                        throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
                    }
                    kwsUserService.fillUserRole(String.valueOf(findManagePojo.getRoleId()), 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 (KwsMenu kwsMenu : collect) {
                        KwsMenuRights kwsMenuRights = new KwsMenuRights();
                        kwsMenuRights.setEntId(entId);
                        kwsMenuRights.setMenuId(kwsMenu.getId());
                        kwsMenuRights.setId(new IdWorker(1L).nextId());
                        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 = new HashMap<>();
        map.put("entName", kwsEnterprise.getFirmName());
        map.put("createByName", LoginUserHolder.getUserName());
        MessageEnum messageEnum;
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntTreeById(entId);
        if (Objects.isNull(entCacheResDto)) {
            return;
        }

        if (reqVo.getStatus().equals(ApprovalEnum.OK.getCode())) {
            if (Objects.isNull(kwsEntDept)) {
                messageEnum = MessageEnum.ENT_CERTIFICATE_PASS;
            } else {
                messageEnum = MessageEnum.ENT_DEPT_CERTIFICATE_PASS;
            }
        } else {
            if (Objects.isNull(kwsEntDept)) {
                messageEnum = MessageEnum.ENT_CERTIFICATE_REFUSED;
            } else {
                messageEnum = MessageEnum.ENT_DEPT_CERTIFICATE_REFUSED;
            }
        }

        if (Objects.isNull(kwsEntDept)) {
            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.update(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 (Objects.isNull(reqVo.getEntPid())) {
            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());
            RegisterResDto register = kwsUserService.register(registerReqDto);

            EntRegisterReqVo entRegisterReqVo = new EntRegisterReqVo();
            BeanUtils.copyProperties(reqVo, entRegisterReqVo);
            entRegisterReqVo.setEntId(register.getEntId());
            register(entRegisterReqVo);
//            ApprovalReqVo approvalReqVo = new ApprovalReqVo();
//            approvalReqVo.setEntId(register.getEntId());
//            approvalReqVo.setStatus(ApprovalEnum.OK.getCode());
//            approval(approvalReqVo);
            return;
        }

        //主体机构
        extracted(reqVo, new IdWorker(1L).nextId());
    }


    private void extracted(AddEntSettleReqVo reqVo, Long entId) {
        KwsEnterprise kwsEnterprise = new KwsEnterprise();
        kwsEnterprise.setId(entId);
        kwsEnterprise.setCode("");
        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.update(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<FindEntListPojo> list = findPojo(reqVo);
        Map<Integer, List<FindEntListPojo>> collect = list.stream().collect(Collectors.groupingBy(FindEntListPojo::getApproval));

        List<FindListGroupResVo> result = new ArrayList<>();
        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);
        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);
        if (CollectionUtils.isNotEmpty(list)) {
            entDetailResVo.setValid(list.stream().anyMatch(item -> item.getStatus().equals(Global.NO)));
        } else {
            entDetailResVo.setValid(false);
        }
        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);

        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) {
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseDao.selectByKeys(null);
        if (CollectionUtils.isEmpty(kwsEnterprises)) {
            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);
        if (checkType.equals(Global.NUMERICAL_ONE)) {
            List<CertificateResVo> certificates = queryCertificate(entId);
            for (CertificateResVo certificate : certificates) {
                Date expireTime = certificate.getExpireTime();
                entCacheResDto.setValid(DateUtil.compare(new Date(), expireTime) <= 0);
            }
        } else {
            List<KwsEntCheckTrack> entCheckTrackResDtoList = entCheck(entId);
            if (CollectionUtils.isEmpty(entCheckTrackResDtoList)) {
                entCacheResDto.setValid(false);
            }
            entCacheResDto.setValid(entCheckTrackResDtoList.stream().anyMatch(item -> item.getStatus() == Global.NO));
        }
        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<FindEntListPojo> list = findPojo(reqVo);
        List<QueryCustomerResVo> result = new ArrayList<>();
        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;
    }


    /**
     * @desc: 入驻认证导出
     * @author: czh
     * @date: 2023/9/21
     */
    public void exportEntSettle(EntFindPageReqVo reqVo, HttpServletResponse response) {
        List<FindEntListPojo> list = findPojo(reqVo);
        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.LOGISTICS3.getCode()))) {
                entFindPageResVo.setEnt3("是");
            }
            if (item.getType().contains(String.valueOf(EntTypeEnum.LOGISTICS4.getCode()))) {
                entFindPageResVo.setEnt4("是");
            }

            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));
        }
    }

}
