package cn.superdesk.uniorder.service.organisation.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.app.supercloud.dto.receive.organisation.VirtualarchitectureReceiveParam;
import cn.superdesk.data.extract.enums.opCenter.OpCenterBizPlatformEnum;
import cn.superdesk.data.extract.enums.opCenter.OpCenterOrderBizTypeEnum;
import cn.superdesk.uniorder.common.chinese.ChinesePingYinFirstLetterUtil;
import cn.superdesk.uniorder.common.enums.common.CommonEnabledEnum;
import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSourceFromEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.qchjc.QchjcOrgEnum;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.exception.utils.AssertUtils;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.numerical.AnLongUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterpriseExample;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcEnterpriseEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcEnterpriseEntityExample;
import cn.superdesk.uniorder.dao.entity.unified.TempDaide;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapper;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapperEx;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.organisation.QchjcEnterpriseEntityMapper;
import cn.superdesk.uniorder.dao.mapper.unified.TempDaideMapper;
import cn.superdesk.uniorder.dto.param.organisation.SysEnterpriseExtInvoiceQueryCriteria;
import cn.superdesk.uniorder.dto.param.organisation.SysEnterpriseQueryCriteria;
import cn.superdesk.uniorder.dto.param.organisation.SysVirtQueryParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.SlaveVirtualarchitectureReceiveParam;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionVirt;
import cn.superdesk.uniorder.dto.vo.organisation.SysEnterpriseExtInvoiceExtPathVo;
import cn.superdesk.uniorder.dto.vo.sys.SysOrganizationXEnterpriseVo;
import cn.superdesk.uniorder.dto.vo.sys.SysSelectVo;
import cn.superdesk.uniorder.dto.vo.sys.SysVirtVo;
import cn.superdesk.uniorder.dto.vo.sys.sysPlatformVo;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseExtInvoiceService;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import cn.superdesk.uniorder.service.organisation.SysOrganizationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 7/7/20 3:44 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 7/7/20 3:44 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class SysEnterpriseServiceImpl implements SysEnterpriseService {

    @Autowired
    private SysEnterpriseMapper   sysEnterpriseMapper;
    @Autowired
    private SysEnterpriseMapperEx sysEnterpriseMapperEx;

    @Autowired
    private SysEnterpriseExtInvoiceService sysEnterpriseExtInvoiceService;

    @Autowired
    private TempDaideMapper tempDaideMapper;

    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Autowired
    private CommonEventPublisher commonEventPublisher;

    @Resource
    private Snowflake snowflake;

    @Autowired
    private QchjcEnterpriseEntityMapper qchjcEnterpriseEntityMapper;


    /****************************************** extends BaseService 部分 start ******************************************/

    @Override
    public int insertSelective(SysEnterprise entity) {
        return sysEnterpriseMapper.insertSelective(entity);
    }

    @Override
    public int updateByPrimaryKeySelective(SysEnterprise entity) {
        return sysEnterpriseMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void deleteObj(Long id) {
        sysEnterpriseMapper.deleteByPrimaryKey(id);
    }

    @Override
    public SysEnterprise findById(Long id) {
        return sysEnterpriseMapper.selectByPrimaryKey(id);
    }


    @Override
    public PageInfo<SysEnterprise> findByPaging(Map<String, Object> conditions, Integer pageNun, Integer pageSize) {
        return null;
    }

    @Override
    public List<SysEnterprise> findAll(Map<String, Object> queryMap) {
//		return sysEnterpriseMapperEx.findAll(queryMap);
        return null;
    }

    @Override
    public List<SysOrganizationXEnterpriseVo> findSysOrganizationXEnterprise(Map<String, Object> queryMap) {
        return sysEnterpriseMapperEx.findSysOrganizationXEnterprise(queryMap);
    }

    /****************************************** extends BaseService 部分   end ******************************************/


    public int addSysEnterprise(SysEnterprise entity) {
        return sysEnterpriseMapper.insertSelective(entity);
    }

    public int updateSysEnterprise(SysEnterprise entity) {
        SysEnterprise originEntity = sysEnterpriseMapper.selectByPrimaryKey(entity.getId());
        AssertUtils.notNull(originEntity);
        AnBeanUtils.copy(entity, originEntity);
        return sysEnterpriseMapper.updateByPrimaryKey(originEntity);
    }

    public int updateByPrimaryKeySelectiveWithRet(SysEnterprise entity) {

        return sysEnterpriseMapper.updateByPrimaryKeySelective(entity);
    }

    public int deleteSysEnterprise(Long id) {
        return sysEnterpriseMapper.deleteByPrimaryKey(id);
    }

    public SysEnterprise findSysEnterpriseById(Long id) {
        SysEnterprise entity = sysEnterpriseMapper.selectByPrimaryKey(id);
//		AssertUtil.notNull(entity);
        return entity;
    }

    public R<List<SysEnterprise>> pageQuery(Map<String, Object> conditions, int pageNun, int pageSize) {

        // 样例 保留
//		SysEnterprise sysEnterpriseConditions = AnBeanUtils.mapToBean(conditions,SysEnterprise.class);

        SysEnterpriseExample          example  = new SysEnterpriseExample();
        SysEnterpriseExample.Criteria criteria = example.createCriteria();

        if (null != conditions.get("enterpriseId") && StringUtils.isNotBlank(conditions.get("enterpriseId").toString())) {
            criteria.andEnterpriseIdEqualTo(AnLongUtils.getLong(conditions.get("enterpriseId")));
        }

        PageHelper.startPage(pageNun, pageSize);
        List<SysEnterprise>     resultList = sysEnterpriseMapper.selectByExample(example);
        PageInfo<SysEnterprise> page       = new PageInfo<SysEnterprise>(resultList);
        PageHelper.clearPage();

        return new R<List<SysEnterprise>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }

    public R<List<SysOrganizationXEnterpriseVo>> pageQuery(SysEnterpriseQueryCriteria queryCriteria, LoginSysUser loginSysUser) {

        PageHelper.startPage(queryCriteria.getPageNumber(), queryCriteria.getPageSize());
        List<SysOrganizationXEnterpriseVo>     resultList = sysEnterpriseMapperEx.findSysOrganizationXEnterprise(queryCriteria);
        PageInfo<SysOrganizationXEnterpriseVo> page       = new PageInfo<SysOrganizationXEnterpriseVo>(resultList);
        PageHelper.clearPage();

        // 附加信息
        additionalInfoPageQuery(resultList);

        // 修正 企业是否有设置发票抬头 扩展信息
        patchReviseVirtIsHasExtInvoice(resultList);

        return new R<List<SysOrganizationXEnterpriseVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }

    private void additionalInfoPageQuery(List<SysOrganizationXEnterpriseVo> resultList) {

        if (CollUtil.isEmpty(resultList)) {
            return;
        }

        for (SysOrganizationXEnterpriseVo vo : resultList) {

            // 补 操作来源-引用enum CommonSourceFromEnum
            if (ObjectUtil.isNotNull(vo.getSourceFrom())) {
                vo.setSourceFromName(CommonSourceFromEnum.getBySourceFromCode(vo.getSourceFrom()).getSourceFromName());
            } else {
                vo.setSourceFromName(CommonSourceFromEnum.UNKNOW.getSourceFromName());
            }
        }
    }

    /**
     * 新加字段 修正初始问题
     *
     * @param resultList
     */
    public void patchReviseVirtIsHasExtInvoice(List<SysOrganizationXEnterpriseVo> resultList) {

        resultList.forEach(vo -> {

            if (ObjectUtil.isNull(vo.getVirtIsHasExtInvoice())) {
                vo.setVirtIsHasExtInvoice(0);
            }

            if (vo.getVirtIsHasExtInvoice().compareTo(0) == 0) {
                vo.setVirtIsHasExtInvoice(statisticsVirtIsHasExtInvoice(vo.getSysVirtId(), vo.getEnterpriseId()));
            }

        });

    }

    public int statisticsVirtIsHasExtInvoice(Long sysVirtId, Long outVirtId) {

        List<SysEnterpriseExtInvoiceExtPathVo> extInvoiceExtPathVoList = sysEnterpriseExtInvoiceService.query(
                SysEnterpriseExtInvoiceQueryCriteria.builder().outVirtId(outVirtId).build(), LoginSysUser.builder().build()
        );

        if (CollUtil.isNotEmpty(extInvoiceExtPathVoList)) {

            updateByPrimaryKeySelective(
                    SysEnterprise
                            .builder()
                            .id(sysVirtId)
                            .isHasExtInvoice(extInvoiceExtPathVoList.size())
                            .build()
            );

            return extInvoiceExtPathVoList.size();
        } else {
            return 0;
        }

    }


    /****************************************** 之前的 要合并 start ******************************************/


    @Override
    public SysEnterprise findByOutVirtId(Long outVirtId) {
        return sysEnterpriseMapperEx.findByVirtId(outVirtId);
    }

    @Override
    public SysEnterprise findByOutVirtName(String outVirtName) {

        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andEnterpriseNameEqualTo(outVirtName);
        List<SysEnterprise> resultList = sysEnterpriseMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(resultList)) {
            return resultList.get(0);
        }

        return null;
    }

    @Override
    public List<SysEnterprise> findByOutVirtIds(List<Long> outVirtIds) {

        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andEnterpriseIdIn(outVirtIds);
        List<SysEnterprise> resultList = sysEnterpriseMapper.selectByExample(example);
        return resultList;

    }


    @Override
    public List<String> convertOutVirtIds2VirtNames(List<Long> outVirtIds) {

        List<String> result = new ArrayList<>();

        List<SysEnterprise> sysEnterpriseList = findByOutVirtIds(outVirtIds);

        if (CollUtil.isNotEmpty(sysEnterpriseList)) {
            result = sysEnterpriseList
                    .stream()
                    .filter(AnLamdaUtils.distinctByKey(o -> o.getEnterpriseId()))
                    .map(SysEnterprise::getEnterpriseName)
                    .collect(Collectors.toList());
        }

        return result;

    }

    @Override
    public List<SysEnterprise> findByVirtName(Long orgId, String enterpriseName) {

        if (orgId == null) {
            throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "项目Id不能为空");
        }

//		Map<String, Object> params = new HashMap<>();
//		params.put("enterpriseName", enterpriseName);
//		return sysEnterpriseMapperEx.findAll(params);

        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andEnterpriseNameLike("%" + enterpriseName + "%");

        return sysEnterpriseMapper.selectByExample(example);
    }

    /***
     * 企业下拉列表 daizhi 19-0808
     */
    @Override
    public R<List<SelectOptionVirt>> getVirtSelect(Map<String, Object> params, int pageNo, int pageSize) {

        PageHelper.startPage(pageNo, pageSize);
        List<SelectOptionVirt>     resultList = sysEnterpriseMapperEx.getVirtSelect(params);
        PageInfo<SelectOptionVirt> page       = new PageInfo<SelectOptionVirt>(resultList);
        PageHelper.clearPage();

        return new R<List<SelectOptionVirt>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }

    @Override
    public List<SelectOptionVirt> getVirtSelectByOutOrgId(Long outOrgId) {

        List<SelectOptionVirt> result = new ArrayList<>();

        Map<String, Object> params = new HashMap<>();
        params.put("projectId", outOrgId);

        result = sysEnterpriseMapperEx.getVirtSelect(params);

        return result;
    }


    @Override
    public R<List<SelectOptionVirt>> getVirtSelectByOutOrgId(Long outOrgId, int pageNum, int pageSize) {

        Map<String, Object> params = new HashMap<>();
        params.put("projectId", outOrgId);

        return getVirtSelect(params, pageNum, pageSize);
    }

    @Override
    public List<Long> getOutVirtIdsByOutOrgId(Long outOrgId) {

        List<Long> result = new ArrayList<>();

        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andOrganizationIdEqualTo(outOrgId);

        List<SysEnterprise> sysEnterpriseList = sysEnterpriseMapper.selectByExample(example);

        result = sysEnterpriseList
                .stream()
                .filter(AnLamdaUtils.distinctByKey(o -> o.getEnterpriseId()))
                .map(SysEnterprise::getEnterpriseId)
                .collect(Collectors.toList());

        log.info("\n\n\n\ngetOutVirtIdsByOutOrgId \nparams outOrgId : {}\nresult : {}\n\n\n\n", outOrgId, JSONUtil.toJsonStr(result));

        return result;
    }

    @Override
    public void addSpecDaiDeLiangHang(Long id) {

        TempDaide daide = new TempDaide();
        daide.setId(id);
        tempDaideMapper.insert(daide);
    }

    @Override
    public void deleteDaiDeLiangHang(Long id) {

        tempDaideMapper.deleteByPrimaryKey(id);
    }


    /****************************************** 之前的 要合并   end ******************************************/


    /****************************************** 来源于 商城的 kafka 同步 start start ******************************************/

    private void convertReceiveVirtualarchitectureParam2Entity4SuperdeskMall(
            SlaveVirtualarchitectureReceiveParam params,
            SysEnterprise entity) {

        entity.setEnterpriseId(params.getId());
        entity.setEnterpriseName(params.getEnterpriseName());
        entity.setEnterpriseNo(params.getEnterpriseNo());
        entity.setOrganizationId(params.getOrganizationId());
        entity.setSyncTime(DateUtil.date());

        // 为什么不用switch,别问，问就是你不懂

        if (ObjectUtil.isNotNull(params.getEnabled())) {

            if (params.getEnabled().compareTo(CommonEnabledEnum.启用.getKey()) == 0) {
                entity.setEnabled(CommonEnabledEnum.启用.getKey());
            } else if (params.getEnabled().compareTo(CommonEnabledEnum.禁用.getKey()) == 0) {
                entity.setEnabled(CommonEnabledEnum.禁用.getKey());
            } else {
                entity.setEnabled(CommonEnabledEnum.启用.getKey());
            }
        }

        if (ObjectUtil.isNotNull(params.getDeleted())) {

            if (params.getDeleted().compareTo(CommonSoftDeleteEnum.正常.getKey()) == 0) {
                entity.setDeleted(CommonSoftDeleteEnum.正常.getKey());
            } else if (params.getDeleted().compareTo(CommonSoftDeleteEnum.删除.getKey()) == 0) {
                entity.setDeleted(CommonSoftDeleteEnum.删除.getKey());
            } else {
                entity.setDeleted(CommonSoftDeleteEnum.正常.getKey());
            }
        }

//        【【结算中心-测试环境】积分结算&供应商结算-筛选查询-企业名称-福利商城的企业没有显示其“服务编号”】
//        https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001005585
        // TODO mark by linjinyu at 2022-07-20 09:36:32 - 看了一下引用，好像只有侨城汇在用，先写死吧
//        entity.setServiceNo(params.getServiceNo());
        entity.setServiceNo(CommonServiceNoEnum.企业福利_侨城汇.getServiceNo());
        entity.setSourceFrom(CommonSourceFromEnum.企业福利_侨城汇.getSourceFromCode());

        entity.setOtherField3("来源^_^侨城汇^_^企业福利");
        /****************************************** 添加业务平台、运营商 at 20230412 start ******************************************/
        entity.setBizOperatorId(params.getBizOperatorId());
        entity.setBizPlatformCode(OpCenterBizPlatformEnum.福利商城.getCode());
        entity.setBizPlatformName(OpCenterBizPlatformEnum.福利商城.getName());
        /****************************************** 添加业务平台、运营商 at 20230412 end ******************************************/
    }

    @Override
    public void mergeReceiveVirtualarchitecture4SuperdeskMall(String message) {

        try {

            SysEnterprise sysEnterprise = null;

            SlaveVirtualarchitectureReceiveParam params = AnJsonUtils.toObject(message, SlaveVirtualarchitectureReceiveParam.class);

            // TODO 先让他 覆盖吧
            SysEnterpriseExample example = new SysEnterpriseExample();
            example.createCriteria()
                    .andEnterpriseIdEqualTo(params.getId());
//					.andEnterpriseNameEqualTo(params.getEnterpriseName())
//					.andEnterpriseNoEqualTo(params.getEnterpriseNo())
//					.andOrganizationIdEqualTo(params.getOrganizationId());

            List<SysEnterprise> checkExists = sysEnterpriseMapper.selectByExample(example);

            if (CollUtil.isEmpty(checkExists)) {

                sysEnterprise = new SysEnterprise();
                convertReceiveVirtualarchitectureParam2Entity4SuperdeskMall(params, sysEnterprise);
                sysEnterprise.setIsHasExtInvoice(0);
                sysEnterprise.setIsHasOrder(0);
                sysEnterpriseMapper.insert(sysEnterprise);

            } else {

                sysEnterprise = checkExists.get(0);
                convertReceiveVirtualarchitectureParam2Entity4SuperdeskMall(params, sysEnterprise);
                sysEnterpriseMapper.updateByPrimaryKey(sysEnterprise);
            }

            // 更新订单
            commonEventPublisher.triggerEnterpriseEvent(sysEnterprise);

        } catch (Exception e) {

            e.printStackTrace();
            log.error("商城 同步 统一订单 (侨城汇)-mergeReceiveVirtualarchitecture 失败:{}", ExceptionUtils.getMessage(e));
        }


    }

    @Override
    @Deprecated
    public void deleteReceiveVirtualarchitecture4SuperdeskMall(String message) {

    }


    /****************************************** 来源于 商城的 kafka 同步   end start ******************************************/


    /****************************************** 来源于 服务之窗 kafka 同步 start start ******************************************/


    private void convertVirtualarchitectureReceiveParam2Entity(
            VirtualarchitectureReceiveParam virtualarchitectureReceiveParam,
            SysEnterprise sysEnterprise) {

        sysEnterprise.setEnterpriseId(virtualarchitectureReceiveParam.getId().longValue());
        sysEnterprise.setEnterpriseNo(virtualarchitectureReceiveParam.getCodeNumber());
        sysEnterprise.setEnterpriseName(virtualarchitectureReceiveParam.getName());

        sysEnterprise.setOrganizationId(virtualarchitectureReceiveParam.getOrgId().longValue());
        sysEnterprise.setSyncTime(DateUtil.date());
        sysEnterprise.setEnabled(virtualarchitectureReceiveParam.getEnabled());

        // TODO mark by linjinyu at 2022-07-20 09:34:18 - 这里本来就是没有serviceNo // 这东西又混用了
//        sysEnterprise.setServiceNo(virtualarchitectureReceiveParam.getServiceNo());
        sysEnterprise.setServiceNo(CommonServiceNoEnum.服务之窗.getServiceNo());

        /****************************************** 添加软删除 at 20201130 start ******************************************/
        if (null != virtualarchitectureReceiveParam.getEnabled()) {
            sysEnterprise.setDeleted(virtualarchitectureReceiveParam.getEnabled().equals(1) ? 0 : 1);
        } else {
            // 默认为未删除
            sysEnterprise.setDeleted(CommonSoftDeleteEnum.正常.getKey());
        }

        /****************************************** 添加软删除 at 20201130 start ******************************************/
        /****************************************** 添加业务平台、运营商 at 20230412 start ******************************************/
        sysEnterprise.setBizPlatformCode(OpCenterBizPlatformEnum.服务之窗.getCode());
        sysEnterprise.setBizPlatformName(OpCenterBizPlatformEnum.服务之窗.getName());
        sysEnterprise.setBizOperatorId(virtualarchitectureReceiveParam.getCompId());
        /****************************************** 添加业务平台、运营商 at 20230412 end ******************************************/

    }

    @Override
    public void mergeReceiveVirtualarchitecture4SuperdeskTransfer(String message) {

        try {

            VirtualarchitectureReceiveParam virtualarchitectureReceiveParam = AnJsonUtils.toObject(message, VirtualarchitectureReceiveParam.class);

            log.info(JSONUtil.toJsonStr(virtualarchitectureReceiveParam));

            SysEnterprise sysEnterprise = sysEnterpriseMapperEx.findByVirtId(virtualarchitectureReceiveParam.getId().longValue());

            if (null == sysEnterprise) {

                sysEnterprise = new SysEnterprise();

                convertVirtualarchitectureReceiveParam2Entity(virtualarchitectureReceiveParam, sysEnterprise);

                sysEnterprise.setIsHasExtInvoice(0);
                sysEnterprise.setIsHasOrder(0);
                sysEnterpriseMapper.insertSelective(sysEnterprise);

            } else {

                convertVirtualarchitectureReceiveParam2Entity(virtualarchitectureReceiveParam, sysEnterprise);

                sysEnterpriseMapper.updateByPrimaryKeySelective(sysEnterprise);
            }

            // 更新订单
            commonEventPublisher.triggerEnterpriseEvent(sysEnterprise);


        } catch (Exception e) {

            e.printStackTrace();
            log.error("服务之窗 同步 统一订单-Virtualarchitecture 失败:{}", ExceptionUtils.getMessage(e));

        }
    }

    @Override
    public void deleteReceiveVirtualarchitecture4SuperdeskTransfer(String message) {

        VirtualarchitectureReceiveParam virtualarchitectureReceiveParam = AnJsonUtils.toObject(message, VirtualarchitectureReceiveParam.class);


        // TODO 先让他 覆盖吧
        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andEnterpriseIdEqualTo(virtualarchitectureReceiveParam.getId().longValue());
//					.andEnterpriseNameEqualTo(params.getEnterpriseName())
//					.andEnterpriseNoEqualTo(params.getEnterpriseNo())
//					.andOrganizationIdEqualTo(params.getOrganizationId());

        List<SysEnterprise> checkExists = sysEnterpriseMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(checkExists)) {
            for (SysEnterprise item : checkExists) {
                item.setEnabled(CommonEnabledEnum.禁用.getKey());
                item.setDeleted(CommonSoftDeleteEnum.删除.getKey());
                sysEnterpriseMapper.updateByPrimaryKey(item);
            }
        }
    }


    /****************************************** 来源于 服务之窗 kafka 同步  end start ******************************************/


    /****************************************** 关于游客问题 start ******************************************/

    public SysEnterprise touchByOutOrgId(Long outOrgId) {

        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andSourceFromEqualTo(CommonSourceFromEnum.结算中心.getSourceFromCode())
                .andOrganizationIdEqualTo(outOrgId);

        List<SysEnterprise> checkExists = sysEnterpriseMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(checkExists)) {
            return checkExists.get(0);
        } else {
            // TODO 创建一个
            return createByBizVisitorLogic(outOrgId);
        }
    }

    /**
     * 先是要已知项目是更名
     *
     * @param sysOrganization
     * @return
     */
    public SysEnterprise renameByOutOrgId(SysOrganization sysOrganization) {

        SysEnterpriseExample example = new SysEnterpriseExample();
        example.createCriteria()
                .andSourceFromEqualTo(CommonSourceFromEnum.结算中心.getSourceFromCode())
                .andOrganizationIdEqualTo(sysOrganization.getOrganizationId());

        List<SysEnterprise> checkExists = sysEnterpriseMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(checkExists)) {

            SysEnterprise existSysEnterprise = checkExists.get(0);

            SysEnterprise visitorVirt = new SysEnterprise();

            visitorVirt.setId(existSysEnterprise.getId());
            String knownObjectName = StrUtil.format("{}{}", sysOrganization.getOrganizationName(), "@游客企业");

            visitorVirt.setEnterpriseNo(ChinesePingYinFirstLetterUtil.getPinYinHeadChar(knownObjectName));
            visitorVirt.setEnterpriseName(knownObjectName);

            sysEnterpriseMapper.updateByPrimaryKeySelective(visitorVirt);

            return visitorVirt;
        }

        return null;
    }

    /**
     * 项目名称+游客企业
     * 编码为企业名称首先字母,地址、联系人、联系电话均为企业名称。
     *
     * @param outOrgId
     * @return
     */
    public SysEnterprise createByBizVisitorLogic(Long outOrgId) {

        Long   snowflakeId    = snowflake.nextId();
        String snowflakeIdStr = AnStringUtils.getString(snowflakeId);
//		截取
        String snowflakeStrSub = snowflakeIdStr.substring(snowflakeIdStr.length() - 16);

        SysOrganization sysOrganization = sysOrganizationService.getByOutOrgId(outOrgId);

        SysEnterprise visitorVirt = new SysEnterprise();
        visitorVirt.setSourceFrom(CommonSourceFromEnum.结算中心.getSourceFromCode());
        visitorVirt.setOrganizationId(outOrgId);
        visitorVirt.setEnterpriseId(AnLongUtils.getLong(snowflakeStrSub));


        visitorVirt.setEnabled(CommonEnabledEnum.启用.getKey());
        visitorVirt.setDeleted(CommonSoftDeleteEnum.正常.getKey());
        // 是否有订单:0-默认;1-有的;2-没有;
        visitorVirt.setIsHasOrder(0);

        if (null == sysOrganization) {

            log.error("哪里?outOrgId查不到数据? {}", outOrgId);

            String unknownObjectName = StrUtil.format("未知项目[{}]", outOrgId);

            visitorVirt.setEnterpriseNo(ChinesePingYinFirstLetterUtil.getPinYinHeadChar(unknownObjectName));
            visitorVirt.setEnterpriseName(unknownObjectName);

        } else {

            String knownObjectName = StrUtil.format("{}{}", sysOrganization.getOrganizationName(), "@游客企业");

            visitorVirt.setEnterpriseNo(ChinesePingYinFirstLetterUtil.getPinYinHeadChar(knownObjectName));
            visitorVirt.setEnterpriseName(knownObjectName);
        }

        sysEnterpriseMapper.insertSelective(visitorVirt);

        return visitorVirt;

    }

    /****************************************** 关于游客问题   end ******************************************/

    /****************************************** 工具方法  start ******************************************/

    public Map<Long, SysEnterprise> convertOutVirtIds2MapOutVirtId2Entity(List<Long> outVirtIds) {

        Map<Long, SysEnterprise> result = new HashMap<>();

        if (CollUtil.isNotEmpty(outVirtIds)) {

            List<SysEnterprise> resultList = findByOutVirtIds(outVirtIds);

            if (CollUtil.isNotEmpty(resultList)) {

                result = resultList
                        .stream()
                        .collect(Collectors.toMap(SysEnterprise::getEnterpriseId, v -> v, (k, v) -> v));
            }
        }

        return result;
    }

    @Override
    public Map<Long, SysEnterprise> findByOutVirtIdsConvertKV(List<Long> outVirtIds) {

        Map<Long, SysEnterprise> result = new HashMap<>();

        if (CollUtil.isNotEmpty(outVirtIds)) {

            List<SysEnterprise> resultList = findByOutVirtIds(outVirtIds);

            if (CollUtil.isNotEmpty(resultList)) {

                result = resultList
                        .stream()
                        .filter(AnLamdaUtils.distinctByKey(o -> o.getEnterpriseId())) // <-------
                        .collect(Collectors.toMap(SysEnterprise::getEnterpriseId, v -> v, (k, v) -> v));
            }
        }

        return result;

    }

    /****************************************** 工具方法    end ******************************************/

    @Override
    public Long countOutVirt() {
        SysEnterpriseExample example = new SysEnterpriseExample();
        return sysEnterpriseMapper.countByExample(example);
    }

    /**
     * 同步集采企业数据
     *
     * @param message
     */
    @Override
    public void mergeReceiveVirtualarchitecture4Qchjc(String message) {

        try {

            log.info("同步集采企业数据，param ：{}", message);
            QchjcEnterpriseEntity qchjcEnterpriseEntity = AnJsonUtils.toObject(message, QchjcEnterpriseEntity.class);

            QchjcEnterpriseEntityExample qchjcEnterpriseEntityExample = new QchjcEnterpriseEntityExample();
            qchjcEnterpriseEntityExample.createCriteria()
                    .andVirtIdEqualTo(qchjcEnterpriseEntity.getVirtId());
            List<QchjcEnterpriseEntity> res = qchjcEnterpriseEntityMapper.selectByExample(qchjcEnterpriseEntityExample);

            SysEnterprise sysEnterprise = null;

            if (CollectionUtils.isEmpty(res)) {
                //如果同步过则进行修改，否则新增一条企业数据
                qchjcEnterpriseEntityMapper.insertSelective(qchjcEnterpriseEntity);

                sysEnterprise = new SysEnterprise();
                convertQchjcParam2Entity(qchjcEnterpriseEntity, sysEnterprise);
                sysEnterpriseMapper.insertSelective(sysEnterprise);

                qchjcEnterpriseEntity.setUnifiedId(sysEnterprise.getId());
                //统一订单企业id保存回中间表
                qchjcEnterpriseEntityMapper.updateByPrimaryKeySelective(qchjcEnterpriseEntity);

            } else {
                QchjcEnterpriseEntity qchEntity = res.get(0);//原来的数据

                AnBeanUtils.copy(qchjcEnterpriseEntity, qchEntity);
                qchjcEnterpriseEntityMapper.updateByPrimaryKeySelective(qchEntity);//更新中间表数据

                sysEnterprise = sysEnterpriseMapper.selectByPrimaryKey(qchEntity.getUnifiedId());
                convertQchjcParam2Entity(qchEntity, sysEnterprise);

                sysEnterpriseMapper.updateByPrimaryKeySelective(sysEnterprise);//更新统一订单企业数据
            }

            // 更新订单
            commonEventPublisher.triggerEnterpriseEvent(sysEnterprise);
        } catch (Exception e) {
            log.error("同步集采企业数据异常 =====  msg : {}", ExceptionUtils.getMessage(e));
            throw e;
        }

    }

    @Override
    public List<SysVirtVo> getVirtList(SysVirtQueryParam param) {
        return sysEnterpriseMapper.getVirtList(param);
    }

    @Override
    public List<SysSelectVo> selectList(Map<String, Object> params) {
        return sysEnterpriseMapper.selectList(params);
    }

    /**
     * 集采企业转换为统一订单企业entity
     *
     * @param qchjcEnterpriseEntity
     * @param sysEnterprise
     */
    private void convertQchjcParam2Entity(QchjcEnterpriseEntity qchjcEnterpriseEntity, SysEnterprise sysEnterprise) {

        sysEnterprise.setEnterpriseId(qchjcEnterpriseEntity.getId());//中间表id,这里集采的id统一从10万开始自增

        sysEnterprise.setSourceFrom(CommonSourceFromEnum.企业商城_侨城汇.getSourceFromCode());//来源
        sysEnterprise.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());//服务编号

        sysEnterprise.setEnterpriseName(qchjcEnterpriseEntity.getVirtName());//企业名称
        sysEnterprise.setOrganizationId(QchjcOrgEnum.CUSTOMER.getOrgId());//项目id，集采默认100001

        sysEnterprise.setSyncTime(DateUtil.date());//同步时间

        sysEnterprise.setEnabled(qchjcEnterpriseEntity.getEnabled());//是否启用
        sysEnterprise.setDeleted(qchjcEnterpriseEntity.getDeleted());//是否软删除
    }


    @Override
    public List<sysPlatformVo> getvirtBizIdById(String enterpriseIds) {
        return sysEnterpriseMapper.getvirtBizIdById(enterpriseIds);
    }

}
