package com.sckw.system.service;

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.system.api.model.dto.req.RegisterReqDto;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.RegisterResDto;
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.vo.req.*;
import com.sckw.system.model.vo.res.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
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 RemoteSystemServiceImpl remoteSystemService;

    /**
     * @param params 入库
     * @desc: 单表入库
     * @author: czh
     * @date: 2023/6/19
     */
    public void add(KwsEnterprise params) throws SystemException {
        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) throws SystemException {
        //校验，有员工还在企业下则不能删除
        List<Long> list = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();
        List<KwsEnterprise> kwsEnterprises = kwsEnterpriseDao.selectByKeys(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 (kwsEnterpriseDao.update(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) throws SystemException {
        /*1、更新企业信息表*/
        KwsEnterprise kwsEnterprise = checkKwsEnterpriseById(LoginUserHolder.getEntId());


        BeanUtils.copyProperties(reqVo, kwsEnterprise);
        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) throws SystemException {
        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) throws SystemException {
        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.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);

        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) throws SystemException {
        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());
        kwsEnterprise.setCityName(reqVo.getCityName());
        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(ApprovalEnum.PROCESS.getCode());
        if (kwsEnterpriseDao.update(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }

        /*2、存企业类型,一个企业可以有多个类型*/
        List<KwsEntType> kwsEntTypes = new ArrayList<>();
        Arrays.stream(reqVo.getEntTypes().split(",")).toList().forEach(item -> {
            KwsEntType kwsEntType = new KwsEntType();
            kwsEntType.setEntId(entId);
            kwsEntType.setType(Integer.parseInt(item));
            kwsEntType.setId(new IdWorker(1).nextId());
            kwsEntType.setStatus(Global.NO);
            kwsEntType.setCreateBy(userId);
            kwsEntType.setCreateTime(date);
            kwsEntType.setUpdateBy(userId);
            kwsEntType.setUpdateTime(date);
            kwsEntType.setDelFlag(Global.NO);
            kwsEntTypes.add(kwsEntType);
        });
        if (kwsEntTypeDao.saveBatch(kwsEntTypes) != kwsEntTypes.size()) {
            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());
            kwsEntCertificates.add(kwsEntCertificate);
        }
        if (kwsEntCertificateDao.saveBatch(kwsEntCertificates) != kwsEntCertificates.size()) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }

        //子公司不用新建机构、角色等，直接返回
        if (!Objects.isNull(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);
            }
        }

    }

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

    /**
     * 企业审批
     */
    @Transactional(rollbackFor = Exception.class)
    public void approval(ApprovalReqVo reqVo) throws SystemException {
        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) {
            //先把旧的作废
            List<KwsEntCertificate> previous = kwsEntCertificateDao.findByEntType(kwsEntCertificate.getEntId(), kwsEntCertificate.getType());
            previous = previous.stream().filter(item -> item.getId().compareTo(kwsEntCertificate.getId()) != 0).toList();
            if (!CollectionUtils.isEmpty(previous)) {
                for (KwsEntCertificate kwsEntCertificate1 : previous) {
                    kwsEntCertificate1.setDelFlag(Global.YES);
                    kwsEntCertificateDao.update(kwsEntCertificate1);
                }
            }


            kwsEntCertificate.setStatus(ApprovalEnum.OK.getCode() == status ? Global.NO : Global.YES);
            kwsEntCertificateDao.update(kwsEntCertificate);

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

        /*更新企业信息主表审批状态*/
        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);
        if (kwsEntCheckTrackDao.insert(kwsEntCheckTrack) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }

        /*第一次审批通过（非更新资质审批通过），构建机构角色等*/
        if (ApprovalEnum.OK.getCode() == status) {
            commonService.updateEntCertificate(entId, BeanUtils.copyToList(kwsEntCertificates, EntCertificateInfo.class));
            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());
            }
        }
    }

    /**
     * @param id 主键id
     * @return KwsEnterprise
     * @desc: 查企业
     * @author: czh
     * @date: 2023/7/26
     */
    private KwsEnterprise checkKwsEnterpriseById(long id) throws SystemException {
        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) throws SystemException {
        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) throws SystemException {
        /*查企业资质*/
        List<KwsEntCertificate> kwsEntCertificates = kwsEntCertificateDao.selectByEntId(entId);
        if (CollectionUtils.isEmpty(kwsEntCertificates)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENTCERTIFICATES_NOT_EXISTS);
        }

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

    /**
     * 企业证件信息
     */
    public List<CertificateResVo> queryCertificate(Long entId) throws SystemException {
        /*查企业资质*/
        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) throws SystemException {

        checkAddEntSettleParam(reqVo);

//        /*1、存用户信息*/
//        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);

        KwsEnterprise kwsEnterprise = new KwsEnterprise();
        long entId = new IdWorker(1L).nextId();
        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());
        if (kwsEnterpriseDao.insert(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }


        /*2、认证*/
        EntRegisterReqVo entRegisterReqVo = new EntRegisterReqVo();
        BeanUtils.copyProperties(reqVo, entRegisterReqVo);
        entRegisterReqVo.setEntId(entId);
        register(entRegisterReqVo);


        //运营端新增企业入驻，直接通过
        if (Objects.isNull(reqVo.getEntPid())) {
            ApprovalReqVo approvalReqVo = new ApprovalReqVo();
            approvalReqVo.setEntId(entRegisterReqVo.getEntId());
            approvalReqVo.setStatus(ApprovalEnum.OK.getCode());
            approval(approvalReqVo);
        }

    }

    /**
     * @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 entName 企业名
     * @return KwsEnterprise
     * @desc: 模糊匹配企业名
     * @author: czh
     * @date: 2023/7/10
     */
    public List<KwsEnterprise> queryEntByName(String entName) {
        return kwsEnterpriseDao.queryEntByName(entName);
    }


    /**
     * @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).getName());
        return findListGroupResVo;
    }

    /**
     * @param id 企业id
     * @return EntDetailResVo
     * @desc: 查详情
     * @author: czh
     * @date: 2023/7/26
     */
    public EntDetailResVo detail(Long id) {
        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);
        List<KwsEntType> listByEntIds = kwsEntTypeDao.findListByEntIds(Collections.singletonList(kwsEnterprise.getId()));
        if (CollectionUtils.isNotEmpty(listByEntIds)) {
            entDetailResVo.setEntTypes(String.join(Global.COMMA, listByEntIds.stream().map(KwsEntType::getType).map(String::valueOf).toList()));
        }
        return entDetailResVo;
    }

    /**
     * @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());
        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());
                    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<>();
        List<KwsEntType> kwsEntTypeList = kwsEntTypeDao.findListByEntIds(kwsEnterprises.stream().map(KwsEnterprise::getId).toList());
        if (CollectionUtils.isNotEmpty(kwsEntTypeList)) {
            collect = kwsEntTypeList.stream().collect(Collectors.groupingBy(KwsEntType::getEntId));
        }

        List<Long> managers = kwsEnterprises.stream().map(KwsEnterprise::getManager).toList();
        Map<Long, KwsUser> userCollect = new HashMap<>();
        if (CollectionUtils.isNotEmpty(managers)) {
            List<KwsUser> kwsUsers = kwsUserService.selectByKeys(managers);
            if (CollectionUtils.isNotEmpty(kwsUsers)) {
                userCollect = kwsUsers.stream().collect(Collectors.toMap(KwsUser::getId, e -> e, (n, o) -> n));
            }
        }


        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()));
            Long manager = kwsEnterprise.getManager();
            if (Objects.nonNull(manager)) {
                queryCurrentOrganizationResVo.setContactsId(manager);
                KwsUser kwsUser = userCollect.get(manager);
                if (Objects.nonNull(kwsUser)) {
                    queryCurrentOrganizationResVo.setContacts(kwsUser.getName());
                    queryCurrentOrganizationResVo.setPhone(kwsUser.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.CARRIAGE.getCode());
            }

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

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