package com.sckw.manage.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.CooperateStatusEnum;
import com.sckw.core.model.enums.CooperateTypeEnum;
import com.sckw.core.model.enums.SystemTypeEnum;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.manage.dao.KwmCooperateMapper;
import com.sckw.manage.dao.KwmCooperateTypeMapper;
import com.sckw.manage.model.dto.req.CooperateManageQueryReqDto;
import com.sckw.manage.model.dto.res.CooperateManageQueryResDto;
import com.sckw.manage.model.entity.KwmCooperate;
import com.sckw.manage.model.entity.KwmCooperateType;
import com.sckw.manage.model.report.CooperateManageExport;
import com.sckw.manage.model.report.QueryAllCooperateInfoExcel;
import com.sckw.manage.model.vo.req.*;
import com.sckw.manage.model.vo.res.*;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.payment.api.dubbo.PaymentDubboService;
import com.sckw.payment.api.model.constant.OrderEnum;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.UserInfo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.FindEntUserResDto;
import com.sckw.system.api.model.dto.res.KwsEnterpriseResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import com.sckw.transport.api.dubbo.TransportRemoteService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
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.stream.Collectors;

/**
 * @author czh
 * @desc 合作管理service
 * @date 2023/7/10
 */
@Slf4j
@Service
public class KwmCooperateManageService {

    @Autowired
    private KwmCooperateMapper kwmCooperateMapper;

    @Autowired
    private KwmCooperateTypeMapper kwmCooperateTypeMapper;

    @Autowired
    private CommonBusinessService commonBusinessService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteUserService remoteUserService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private TradeOrderInfoService tradeOrderInfoService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private TransportRemoteService transportRemoteService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private PaymentDubboService paymentDubboService;

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

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

    /**
     * @param reqVo 分页入参
     * @return PageResult
     * @desc: 查询合作企业列表
     * @author: czh
     * @date: 2023/7/10
     */
    public PageResult queryByPage(CooperateManageQueryReqVo reqVo) {
        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());
        CooperateManageQueryReqDto reqDto = buildQueryParam(reqVo);
        List<CooperateManageQueryResDto> list = kwmCooperateMapper.findManageList(reqDto);
        if (CollectionUtils.isEmpty(list)) {
            return PageHelperUtil.getPageResult(new PageInfo<>());
        }
        List<CooperateManageQueryResVo> cooperateManageQueryResVos = commonBusinessService.getCooperateManageQueryResVos(list);
        return PageHelperUtil.getPageResult(new PageInfo<>(cooperateManageQueryResVos), list, reqVo.getPageSize());
    }


    /**
     * @param reqVo 查询入参
     * @return CooperateManageQueryReqDto
     * @desc: 构建查全量入参
     * @author: czh
     * @date: 2023/7/11
     */
    private CooperateManageQueryReqDto buildQueryParam(CooperateManageQueryReqVo reqVo) {
        CooperateManageQueryReqDto cooperateManageQueryReqDto = new CooperateManageQueryReqDto();
        BeanUtils.copyProperties(reqVo, cooperateManageQueryReqDto);
        String cooperateTypes = reqVo.getCooperateTypes();
        if (StringUtils.isNotBlank(cooperateTypes)) {
            cooperateManageQueryReqDto.setCooperateTypes(Arrays.asList(cooperateTypes.split(Global.COMMA)));
        }


        //只允许查出申请中、已拒绝、已撤销的记录
        List<Integer> status = new ArrayList<>();
        if (Objects.isNull(reqVo.getStatus())) {
            status.add(CooperateStatusEnum.OK.getCode());
            status.add(CooperateStatusEnum.PASS.getCode());
        }

        if (Objects.nonNull(reqVo.getStatus()) && reqVo.getStatus().equals(CooperateStatusEnum.OK.getCode())) {
            status.add(CooperateStatusEnum.OK.getCode());
        }
        if (Objects.nonNull(reqVo.getStatus()) && reqVo.getStatus().equals(CooperateStatusEnum.PASS.getCode())) {
            status.add(CooperateStatusEnum.PASS.getCode());
        }
        cooperateManageQueryReqDto.setStatus(status);

        if (StringUtils.isNotBlank(reqVo.getIds())) {
            cooperateManageQueryReqDto.setIds(StringUtils.splitStrToList(reqVo.getIds(), Long.class));
        }


        Long entId = LoginUserHolder.getEntId();
        cooperateManageQueryReqDto.setCurrentEntId(entId);
        List<Long> currentEntIdList = new ArrayList<>();
        currentEntIdList.add(entId);
        Map<Long, List<EntCacheResDto>> longListMap = remoteSystemService.queryEntDeptCacheByIds(Collections.singletonList(entId));
        if (!longListMap.isEmpty()) {
            List<EntCacheResDto> entCacheResDtos = longListMap.get(entId);
            if (CollectionUtils.isNotEmpty(entCacheResDtos)) {
                currentEntIdList.addAll(entCacheResDtos.stream().map(EntCacheResDto::getId).toList());
            }
        }
        cooperateManageQueryReqDto.setCurrentEntIdList(currentEntIdList);

        if (StringUtils.isNotBlank(reqVo.getKeywords())) {
            List<EntCacheResDto> entCacheResDtos = remoteSystemService.queryEntCacheByName(reqVo.getKeywords());
            if (CollectionUtils.isNotEmpty(entCacheResDtos)) {
                cooperateManageQueryReqDto.setTargetEntIdList(entCacheResDtos.stream().map(EntCacheResDto::getId).toList());
            }
        }

        List<FindEntUserResDto> entUser = remoteUserService.findEntUser(entId);
        if (CollectionUtils.isEmpty(entUser)) {
            cooperateManageQueryReqDto.setCurrentUserIdList(Collections.singletonList(LoginUserHolder.getUserId()));
        } else {
            cooperateManageQueryReqDto.setCurrentUserIdList(entUser.stream().map(FindEntUserResDto::getUserId).toList());
        }
        return cooperateManageQueryReqDto;
    }


    /**
     * @param entId 企业id
     * @return QueryDetailResVo
     * @desc: 查询详情
     * @author: czh
     * @date: 2023/7/10
     */
    public QueryDetailResVo queryDetail(Long entId) {
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(entId);
        if (Objects.isNull(entCacheResDto)) {
            return null;
        }
        QueryDetailResVo queryDetailResVo = new QueryDetailResVo();
        BeanUtils.copyProperties(entCacheResDto, queryDetailResVo);
        return queryDetailResVo;
    }

    /**
     * @param reqVo 用户id
     * @desc: 设置客户经理
     * @author: czh
     * @date: 2023/7/10
     */
    public void bindManager(BindManagerReqVo reqVo) {
        commonBusinessService.bingManager(reqVo.getUserId(), reqVo.getId());
    }

    /**
     * @param ids 主键id
     * @desc: 解除合同
     * @author: czh
     * @date: 2023/7/11
     */
    @Transactional(rollbackFor = {})
    public void dissolve(String ids, Integer type) {
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.selectBatchIds(Arrays.asList(ids.split(Global.COMMA)));
        if (CollectionUtils.isEmpty(kwmCooperates)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COOPERATE_NOT_EXISTS);
        }
        Long userId = LoginUserHolder.getUserId();
        Date date = new Date();
        //校验解除限制
        checkLimit(kwmCooperates);
        kwmCooperates.forEach(item -> {
            //运营端可以操作任意状态，企业端只能操作合作中的数据
            if (SystemTypeEnum.MANAGE.getCode().equals(LoginUserHolder.getSystemType())) {
                if (!item.getStatus().equals(CooperateStatusEnum.OK.getCode()) && type.equals(CooperateStatusEnum.PASS.getCode())) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_012);
                }

                if (!item.getStatus().equals(CooperateStatusEnum.PASS.getCode()) && type.equals(CooperateStatusEnum.OK.getCode())) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_012);
                }
            }
            item.setStatus(type);
            item.setUpdateBy(userId);
            item.setUpdateTime(date);
            if (kwmCooperateMapper.updateById(item) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }
        });

        try {
            Map<String, Object> map = new HashMap<>(Global.NUMERICAL_FOUR);
            for (KwmCooperate kwmCooperate : kwmCooperates) {
                Long targetEntId = kwmCooperate.getEntId().equals(LoginUserHolder.getEntId()) ? kwmCooperate.getInviteeEntId() : kwmCooperate.getInviterEntId();
                Long entId = kwmCooperate.getEntId().equals(LoginUserHolder.getEntId()) ? kwmCooperate.getInviterEntId() : kwmCooperate.getInviteeEntId();
                EntCacheResDto targetEntCacheResDto = remoteSystemService.queryEntCacheById(targetEntId);
                EntCacheResDto targetEntTreeCacheResDto = remoteSystemService.queryEntTreeById(targetEntId);
                EntCacheResDto ourEntCacheResDto = remoteSystemService.queryEntCacheById(entId);
                EntCacheResDto ourEntTopCacheResDto = remoteSystemService.queryEntCacheById(kwmCooperate.getEntId());
                if (type.equals(CooperateStatusEnum.PASS.getCode())) {
                    map.put("entName", targetEntCacheResDto.getFirmName());
                    map.put("createByName", LoginUserHolder.getUserName());
                    commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(ourEntTopCacheResDto.getContactsId()).setEntId(ourEntTopCacheResDto.getId())),
                            MessageEnum.COOPERATE_DISSOLVE,
                            map,
                            cooperateManageUrl,
                            appCooperateApplyUrl);

                    map.put("entName", ourEntCacheResDto.getFirmName());
                    commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(targetEntTreeCacheResDto.getContactsId()).setEntId(targetEntTreeCacheResDto.getId())),
                            MessageEnum.COOPERATE_DISSOLVED,
                            map,
                            cooperateManageUrl,
                            appCooperateApplyUrl);
                } else {
                    map.put("entName", targetEntCacheResDto.getFirmName());
                    map.put("createByName", LoginUserHolder.getUserName());
                    commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(ourEntTopCacheResDto.getContactsId()).setEntId(ourEntTopCacheResDto.getId())),
                            MessageEnum.COOPERATE_RESTORE,
                            map,
                            cooperateManageUrl,
                            appCooperateApplyUrl);

                    map.put("entName", ourEntCacheResDto.getFirmName());
                    commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(targetEntTreeCacheResDto.getContactsId()).setEntId(targetEntTreeCacheResDto.getId())),
                            MessageEnum.COOPERATE_RESTORED,
                            map,
                            cooperateManageUrl,
                            appCooperateApplyUrl);
                }
            }
        } catch (Exception e) {
            log.error("合作关系恢复/解除消息出错:", e);
        }

    }


    /**
     * @param kwmCooperates 实体
     * @desc: 解除的校验限制
     * @author: czh
     * @date: 2023/9/7
     */
    private void checkLimit(List<KwmCooperate> kwmCooperates) {
        //判断是否可以解除-销售订单
        KwmCooperate kwmCooperate = kwmCooperates.get(0);
        if (tradeOrderInfoService.associateEnt(kwmCooperate.getInviteeEntId(), kwmCooperate.getInviterEntId())) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_031);
        }
        //判断是否可以解除-托运和承运
        HttpResult response = transportRemoteService.checkLogisticsOrderIsFinishByEntId(kwmCooperate.getInviteeEntId(), kwmCooperate.getInviterEntId());
        int receivedResult = response.getCode();
        if (!Integer.toString(receivedResult).equals(String.valueOf(HttpStatus.SUCCESS_CODE))) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_032);
        }
        Map<OrderEnum, List<String>> ledgerMap = paymentDubboService.checkLedger(kwmCooperate.getInviteeEntId(), kwmCooperate.getInviterEntId());
        if (!CollectionUtils.isEmpty(ledgerMap.get(OrderEnum.LOGISTICS))) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_034);
        }
        if (!CollectionUtils.isEmpty(ledgerMap.get(OrderEnum.TRADE))) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_034);
        }
        Map<OrderEnum, List<String>> settlementMap = paymentDubboService.checkSettlement(kwmCooperate.getInviteeEntId(), kwmCooperate.getInviterEntId());
        if (!CollectionUtils.isEmpty(settlementMap.get(OrderEnum.LOGISTICS))) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_034);
        }
        if (!CollectionUtils.isEmpty(settlementMap.get(OrderEnum.TRADE))) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_034);
        }
    }

    /**
     * @param status 操作状态
     * @return boolean
     * @desc: 校验用户操作状态
     * @author: czh
     * @date: 2023/7/11
     */
    private boolean checkUserPermission(int status) {
        return status != CooperateStatusEnum.OK.getCode() && !Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode());
    }

    /**
     * @param ids 主键
     * @desc: 删除合同
     * @author: czh
     * @date: 2023/7/11
     */
    public void delete(String ids) {
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.selectBatchIds(Arrays.asList(ids.split(Global.COMMA)));
        Long userId = LoginUserHolder.getUserId();
        Date date = new Date();
        kwmCooperates.forEach(item -> {
            //运营端可以操作任意状态，企业端只能操作合作中的数据
            if (item.getStatus() != CooperateStatusEnum.PASS.getCode()) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_013);
            }

            item.setDelFlag(Global.YES);
            item.setUpdateBy(userId);
            item.setUpdateTime(date);
            if (kwmCooperateMapper.updateById(item) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }
        });
    }

    /**
     * @param reqVo 查询入参
     * @desc: 导出
     * @author: czh
     * @date: 2023/7/11
     */
    public void export(CooperateManageQueryReqVo reqVo, HttpServletResponse response) {
        CooperateManageQueryReqDto reqDto = buildQueryParam(reqVo);
        List<CooperateManageQueryResDto> list = kwmCooperateMapper.findManageList(reqDto);
        if (CollectionUtils.isEmpty(list)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        List<CooperateManageQueryResVo> cooperateManageQueryResVos = commonBusinessService.getCooperateManageQueryResVos(list);
        List<CooperateManageExport> result = new ArrayList<>();
        cooperateManageQueryResVos.forEach(item -> {
            CooperateManageExport cooperateManageExport = new CooperateManageExport();
            BeanUtils.copyProperties(item, cooperateManageExport);
            cooperateManageExport.setStatus(CooperateStatusEnum.getName(item.getStatus()));
            cooperateManageExport.setApplyType(item.getApplyTypeCode().equals(1) ? "我方发起" : "对方发起");
            String cooperateTypes = item.getCooperateTypes();
            if (cooperateTypes.contains(String.valueOf(CooperateTypeEnum.SUPPLIER.getCode()))) {
                cooperateManageExport.setEnt1("是");
            }

            if (cooperateTypes.contains(String.valueOf(CooperateTypeEnum.PURCHASER.getCode()))) {
                cooperateManageExport.setEnt2("是");
            }

            if (cooperateTypes.contains(String.valueOf(CooperateTypeEnum.CONSIGN.getCode()))) {
                cooperateManageExport.setEnt3("是");
            }

            if (cooperateTypes.contains(String.valueOf(CooperateTypeEnum.CARRIAGE.getCode()))) {
                cooperateManageExport.setEnt4("是");
            }

            result.add(cooperateManageExport);
        });
        ExcelUtil.downData(response, CooperateManageExport.class, result);
    }

    /**
     * @param reqVo 查询入参
     * @return HttpResult
     * @desc: 分组查询
     * @author: czh
     * @date: 2023/7/17
     */
    public List<FindListGroupResVo> findListGroup(CooperateManageQueryReqVo reqVo) {
        //初始化分组返参
        List<FindListGroupResVo> result = commonBusinessService.init();

        CooperateManageQueryReqDto reqDto = buildQueryParam(reqVo);
        List<CooperateManageQueryResDto> list = kwmCooperateMapper.findManageList(reqDto);
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }
        List<CooperateManageQueryResVo> cooperateManageQueryResVos = commonBusinessService.getCooperateManageQueryResVos(list);
        if (CollectionUtils.isEmpty(cooperateManageQueryResVos)) {
            return result;
        }

        //填充分组数据
        commonBusinessService.fillGroup(result, cooperateManageQueryResVos);
        return result;
    }


    /**
     * @param reqVo 企业id
     * @return FindEntCooperateResVo
     * @desc: 查询企业的合作单位
     * @author: czh
     * @date: 2023/7/22
     */
    public List<FindEntCooperateResVo> findEntCooperate(FindEntCooperateReqVo reqVo) {
        Long id = reqVo.getId();
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.findEntCooperate(reqVo);
        if (CollectionUtils.isEmpty(kwmCooperates)) {
            return Collections.emptyList();
        }

        EntCacheResDto topEnt = remoteSystemService.queryEntTreeById(id);
        Long topEntId = topEnt.getId();
        List<KwmCooperateType> kwmCooperateTypeList = new ArrayList<>();
        for (KwmCooperate kwmCooperate : kwmCooperates) {
            Integer type = reqVo.getCooperateType();
            //不是我方发起
            if (!topEntId.equals(kwmCooperate.getEntId())) {
                type = commonBusinessService.changeCooperateType(type);
            }
            LambdaQueryWrapper<KwmCooperateType> kwmCooperateTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            kwmCooperateTypeLambdaQueryWrapper.eq(KwmCooperateType::getCooperateId, kwmCooperate.getId());
            kwmCooperateTypeLambdaQueryWrapper.eq(KwmCooperateType::getDelFlag, Global.NO);
            kwmCooperateTypeLambdaQueryWrapper.eq(KwmCooperateType::getStatus, CooperateStatusEnum.OK.getCode());
            kwmCooperateTypeLambdaQueryWrapper.eq(KwmCooperateType::getType, type);
            List<KwmCooperateType> kwmCooperateTypes = kwmCooperateTypeMapper.selectList(kwmCooperateTypeLambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(kwmCooperateTypes)) {
                kwmCooperateTypeList.addAll(kwmCooperateTypes);
            }
        }

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


        //装对方企业的id
        List<Long> kwmCooperateIdList = kwmCooperateTypeList.stream().map(KwmCooperateType::getCooperateId).toList();
        kwmCooperates = kwmCooperates.stream().filter(item -> kwmCooperateIdList.contains(item.getId())).toList();
        if (CollectionUtils.isEmpty(kwmCooperates)) {
            return null;
        }

        List<Long> targetEntIdList = new ArrayList<>();
        kwmCooperates.forEach(item -> targetEntIdList.add(item.getInviterEntId().equals(id) ? item.getInviteeEntId() : item.getInviterEntId()));

        Map<Long, EntCacheResDto> entCacheResDtoMap = remoteSystemService.queryEntCacheMapByIds(targetEntIdList);
        if (Objects.isNull(entCacheResDtoMap)) {
            return null;
        }

        //装对方企业信息
        List<FindEntCooperateResVo> targetEntList = new ArrayList<>();
        kwmCooperates.forEach(item -> {
            FindEntCooperateResVo findEntCooperateResVo = new FindEntCooperateResVo();
            Long entId = item.getInviterEntId().equals(id) ? item.getInviteeEntId() : item.getInviterEntId();
            EntCacheResDto entCacheResDto = entCacheResDtoMap.get(entId);
            if (Objects.isNull(entCacheResDto)) {
                return;
            }
            findEntCooperateResVo.setEntId(entId);
            findEntCooperateResVo.setEntName(entCacheResDto.getFirmName());
            findEntCooperateResVo.setContactsId(item.getInviterEntId().equals(id) ? item.getInviteeContactsId() : item.getInviterContactsId());
            findEntCooperateResVo.setContacts(item.getInviterEntId().equals(id) ? item.getInviteeContacts() : item.getInviterContacts());
            findEntCooperateResVo.setPhone(item.getInviterEntId().equals(id) ? item.getInviteePhone() : item.getInviterPhone());
            targetEntList.add(findEntCooperateResVo);
        });

        //装对方企业的主体单位
//        Map<Long, List<EntCacheResDto>> longListMap = remoteSystemService.queryEntDeptCacheByIds(targetEntIdList);
//        List<Long> longs = targetEntList.stream().map(FindEntCooperateResVo::getEntId).toList();
//        longs.forEach(item -> {
//            List<EntCacheResDto> entCacheResDtos1 = longListMap.get(item);
//            if (CollectionUtils.isEmpty(entCacheResDtos1)) {
//                return;
//            }
//            entCacheResDtos1.forEach(x -> {
//                FindEntCooperateResVo findEntCooperateResVo = new FindEntCooperateResVo();
//                findEntCooperateResVo.setEntId(x.getId());
//                findEntCooperateResVo.setEntName(x.getFirmName());
//                targetEntList.add(findEntCooperateResVo);
//            });
//        });
        return targetEntList;
    }


    /**
     * @param reqVo 企业id
     * @return FindCooperateByEntResVo
     * @desc: 根据企业查合作信息
     * @author: czh
     * @date: 2023/8/1
     */
    public List<FindCooperateByEntResVo> findCooperateByEnt(FindCooperateByEntReqVo reqVo) {
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.findCooperateByEnt(reqVo);
        if (CollectionUtils.isEmpty(kwmCooperates)) {
            return Collections.emptyList();
        }

        Long entId = reqVo.getEntId();
        Map<Long, EntCacheResDto> entCacheResDtoMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(entId));
        Long topId = entCacheResDtoMap.get(entId).getId();

        //获取合作属性
        List<Long> cooperateIdList = kwmCooperates.stream().map(KwmCooperate::getId).toList();
        LambdaQueryWrapper<KwmCooperateType> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwmCooperateType::getCooperateId, cooperateIdList);
        wrapper.eq(KwmCooperateType::getDelFlag, Global.NO);
        wrapper.eq(KwmCooperateType::getStatus, CooperateStatusEnum.OK.getCode());
        List<KwmCooperateType> kwmCooperateTypes = kwmCooperateTypeMapper.selectList(wrapper);
        Map<Long, List<KwmCooperateType>> collect = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(kwmCooperateTypes)) {
            collect = kwmCooperateTypes.stream().collect(Collectors.groupingBy(KwmCooperateType::getCooperateId));
        }

        //获取所有企业信息
        List<Long> allEntIdList = new ArrayList<>();
        kwmCooperates.forEach(item -> {
            allEntIdList.add(item.getEntId());
            allEntIdList.add(item.getInviterEntId());
            allEntIdList.add(item.getInviteeEntId());
        });
        List<EntCacheResDto> entCacheResDtos = remoteSystemService.queryEntCacheByIds(allEntIdList);
        Map<Long, EntCacheResDto> entMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(entCacheResDtos)) {
            entMap = entCacheResDtos.stream().collect(Collectors.toMap(EntCacheResDto::getId, e -> e, (n, o) -> n));
        }

        List<FindCooperateByEntResVo> list = new ArrayList<>();
        List<Integer> cooperateTypeList = new ArrayList<>();
        for (KwmCooperate kwmCooperate : kwmCooperates) {
            FindCooperateByEntResVo findCooperateByEntResVo = new FindCooperateByEntResVo();
            findCooperateByEntResVo.setId(kwmCooperate.getId());
            findCooperateByEntResVo.setRemark(kwmCooperate.getRemark());
            //设置发起企业
            EntCacheResDto entCacheResDto = entMap.get(kwmCooperate.getEntId());
            findCooperateByEntResVo.setInitiateEntId(kwmCooperate.getEntId());
            if (Objects.nonNull(entCacheResDto)) {
                findCooperateByEntResVo.setInitiateEntName(entCacheResDto.getFirmName());
            }

            EntCacheResDto inviterEntCacheResDto = entMap.get(kwmCooperate.getInviterEntId());
            EntCacheResDto inviteeEntCacheResDto = entMap.get(kwmCooperate.getInviteeEntId());
            String inviterEntName = Objects.isNull(inviterEntCacheResDto) ? null : inviterEntCacheResDto.getFirmName();
            String inviteeEntName = Objects.isNull(inviteeEntCacheResDto) ? null : inviteeEntCacheResDto.getFirmName();

            //设置合作属性
            List<KwmCooperateType> kwmCooperateTypeList = collect.get(kwmCooperate.getId());
            for (KwmCooperateType kwmCooperateType : kwmCooperateTypeList) {
                Integer type;
                if (kwmCooperate.getEntId().equals(topId)) {
                    type = kwmCooperateType.getType();
                } else {
                    type = commonBusinessService.changeCooperateType(kwmCooperateType.getType());
                }

                if (Objects.isNull(reqVo.getCooperateType())) {
                    cooperateTypeList.add(type);
                } else if (reqVo.getCooperateType().equals(type)) {
                    cooperateTypeList.add(type);
                }
            }

            if (CollectionUtils.isEmpty(cooperateTypeList)) {
                continue;
            }

            String cooperateTypes = String.join(Global.COMMA, cooperateTypeList.stream().map(String::valueOf).distinct().toList());
            findCooperateByEntResVo.setCooperateTypes(cooperateTypes);
            //设置我方和对方企业信息、联系人
            if (topId.equals(kwmCooperate.getEntId())) {
                findCooperateByEntResVo.setEntId(kwmCooperate.getInviterEntId());
                findCooperateByEntResVo.setEntName(inviterEntName);
                findCooperateByEntResVo.setContactsId(kwmCooperate.getInviterContactsId());
                findCooperateByEntResVo.setContacts(kwmCooperate.getInviterContacts());
                findCooperateByEntResVo.setPhone(kwmCooperate.getInviterPhone());
                findCooperateByEntResVo.setTargetEntId(kwmCooperate.getInviteeEntId());
                findCooperateByEntResVo.setTargetEntName(inviteeEntName);
                findCooperateByEntResVo.setTargetContactsId(kwmCooperate.getInviteeContactsId());
                findCooperateByEntResVo.setTargetContacts(kwmCooperate.getInviteeContacts());
                findCooperateByEntResVo.setTargetPhone(kwmCooperate.getInviteePhone());
            } else {
                findCooperateByEntResVo.setEntId(kwmCooperate.getInviteeEntId());
                findCooperateByEntResVo.setEntName(inviteeEntName);
                findCooperateByEntResVo.setContactsId(kwmCooperate.getInviteeContactsId());
                findCooperateByEntResVo.setContacts(kwmCooperate.getInviteeContacts());
                findCooperateByEntResVo.setPhone(kwmCooperate.getInviteePhone());
                findCooperateByEntResVo.setTargetEntId(kwmCooperate.getInviterEntId());
                findCooperateByEntResVo.setTargetEntName(inviterEntName);
                findCooperateByEntResVo.setTargetContactsId(kwmCooperate.getInviterContactsId());
                findCooperateByEntResVo.setTargetContacts(kwmCooperate.getInviterContacts());
                findCooperateByEntResVo.setTargetPhone(kwmCooperate.getInviterPhone());
            }
            list.add(findCooperateByEntResVo);
            cooperateTypeList.clear();
        }
        return list;
    }


    public void restore(String ids, Integer type) {
        dissolve(ids, type);
    }


    /**
     * @param reqVo 企业id
     * @return FindCooperateByEntResVo
     * @desc: 查询对方企业的合作单位有哪些是我方的
     * @author: czh
     * @date: 2023/7/22
     */
    public List<FindCooperateByEntResVo> findTargetEntCooperateInOur(FindCooperateByEntReqVo reqVo) {

//        Map<Long, EntCacheResDto> longEntCacheResDtoMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(reqVo.getEntId()));
//        if (longEntCacheResDtoMap.isEmpty()) {
//            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
//        }
//
//        EntCacheResDto entCacheResDto = longEntCacheResDtoMap.get(reqVo.getEntId());
//        if (Objects.isNull(entCacheResDto)) {
//            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ENT_NOT_EXISTS);
//        }
//
//        List<Long> longs = new ArrayList<>();
//        longs.add(reqVo.getEntId());
//        List<EntCacheResDto> child = entCacheResDto.getChild();
//        if (CollectionUtils.isNotEmpty(child)) {
//            longs.addAll(child.stream().map(EntCacheResDto::getId).toList());
//        }

        return Collections.emptyList();
//
//        //由于是以对方单位为第一单位查，所以这里要取反一下
//        long entIdTemp;
//        long contactsId;
//        String entIdName;
//        String contacts;
//        String phone;
//        for (FindCooperateByEntResVo findCooperateByEntResVo : findCooperateByEntResVos) {
//            entIdTemp = findCooperateByEntResVo.getEntId();
//            entIdName = findCooperateByEntResVo.getEntName();
//            contactsId = findCooperateByEntResVo.getContactsId();
//            contacts = findCooperateByEntResVo.getContacts();
//            phone = findCooperateByEntResVo.getPhone();
//
//            findCooperateByEntResVo.setEntId(findCooperateByEntResVo.getTargetEntId());
//            findCooperateByEntResVo.setEntName(findCooperateByEntResVo.getTargetEntName());
//            findCooperateByEntResVo.setContactsId(findCooperateByEntResVo.getTargetContactsId());
//            findCooperateByEntResVo.setContacts(findCooperateByEntResVo.getTargetContacts());
//            findCooperateByEntResVo.setPhone(findCooperateByEntResVo.getTargetPhone());
//            findCooperateByEntResVo.setTargetEntId(entIdTemp);
//            findCooperateByEntResVo.setTargetEntName(entIdName);
//            findCooperateByEntResVo.setTargetContactsId(contactsId);
//            findCooperateByEntResVo.setTargetContacts(contacts);
//            findCooperateByEntResVo.setTargetPhone(phone);
//            findCooperateByEntResVo.setCooperateTypes(commonBusinessService.changeCooperateType(findCooperateByEntResVo.getCooperateTypes()));
//        }
//        return findCooperateByEntResVos;
    }


    /**
     * @param entId 发起合作的企业id
     * @return KwmCooperate
     * @desc: 根据发起合作的企业查询
     * @author: czh
     * @date: 2023/9/1
     */
    public List<KwmCooperate> findCooperateByInitEnt(Long entId) {
        LambdaQueryWrapper<KwmCooperate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwmCooperate::getEntId, entId).
                eq(KwmCooperate::getDelFlag, Global.NO).
                eq(KwmCooperate::getStatus, CooperateStatusEnum.OK.getCode());
        return kwmCooperateMapper.selectList(wrapper);
    }


    /**
     * @param reqVo 分页入参
     * @return QueryAllCooperateInfoResVo
     * @desc: 运营端查合作信息
     * @author: czh
     * @date: 2023/9/15
     */
    public PageResult queryAllCooperateInfoByPage(CooperateManageQueryReqVo reqVo) {
        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());

        //新增客户经理权限过滤
        List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
        if (CollectionUtils.isEmpty(authEntIdList)) {
            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
            if (CollectionUtils.isEmpty(ids)) {
                return PageHelperUtil.getPageResult(new PageInfo<>(), new ArrayList<>(), reqVo.getPageSize());
            }
            authEntIdList.addAll(ids);
        }

        List<CooperateManageQueryResDto> list = kwmCooperateMapper.queryAllCooperateInfoList(getQueryAllCooperateInfoReqDto(reqVo), authEntIdList);
        if (CollectionUtils.isEmpty(list)) {
            return PageHelperUtil.getPageResult(new PageInfo<>());
        }

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


    /**
     * 构建入参
     */
    private QueryAllCooperateInfoReqDto getQueryAllCooperateInfoReqDto(CooperateManageQueryReqVo reqVo) {
        QueryAllCooperateInfoReqDto queryAllCooperateInfoReqDto = new QueryAllCooperateInfoReqDto();
        BeanUtils.copyProperties(reqVo, queryAllCooperateInfoReqDto);
        String cooperateTypes = reqVo.getCooperateTypes();
        if (StringUtils.isNotBlank(cooperateTypes)) {
            queryAllCooperateInfoReqDto.setCooperateTypes(Arrays.stream(cooperateTypes.split(Global.COMMA)).map(Integer::parseInt).toList());
        }

        if (StringUtils.isNotBlank(reqVo.getKeywords())) {
            List<EntCacheResDto> entCacheResDtos = remoteSystemService.queryEntCacheByName(reqVo.getKeywords());
            if (CollectionUtils.isNotEmpty(entCacheResDtos)) {
                queryAllCooperateInfoReqDto.setQueryEntIdList(entCacheResDtos.stream().map(EntCacheResDto::getId).toList());
            }
        }
        queryAllCooperateInfoReqDto.setIds(StringUtils.splitStrToList(reqVo.getIds(), Long.class));
        return queryAllCooperateInfoReqDto;
    }

    /**
     * 获取返参
     */
    private List<QueryAllCooperateInfoResVo> getAllCooperateInfoVo(List<CooperateManageQueryResDto> list) {
        List<Long> inviteeEntIds = list.stream().map(CooperateManageQueryResDto::getInviteeEntId).toList();
        List<Long> inviterEntIds = list.stream().map(CooperateManageQueryResDto::getInviterEntId).toList();
        List<Long> userIds = list.stream().map(CooperateManageQueryResDto::getCreateBy).toList();
        List<Long> allEntIds = new ArrayList<>();
        allEntIds.addAll(inviterEntIds);
        allEntIds.addAll(inviteeEntIds);
        Map<Long, EntCacheResDto> entCacheResDtoMap = remoteSystemService.queryEntCacheMapByIds(allEntIds);
        Map<Long, UserCacheResDto> userCacheResDtoMap = remoteSystemService.queryUserCacheMapByIds(userIds);

        List<QueryAllCooperateInfoResVo> result = new ArrayList<>();
        //邀请客户经理id
        List<Long> inviterEntUserIds = new ArrayList<>();
        //受邀客户经理id
        List<Long> inviteeEntUserIds = new ArrayList<>();
        Map<Long, KwsEnterpriseResDto> mapList = remoteSystemService.queryEnterpriseByEntIds(allEntIds.stream().distinct().collect(Collectors.toList()));
        list.forEach(item -> {
            QueryAllCooperateInfoResVo queryAllCooperateInfoResVo = new QueryAllCooperateInfoResVo();
            queryAllCooperateInfoResVo.setStatus(item.getStatus());
            queryAllCooperateInfoResVo.setStatusName(CooperateStatusEnum.getName(item.getStatus()));
            queryAllCooperateInfoResVo.setInviterEntId(item.getInviterEntId());
            queryAllCooperateInfoResVo.setInviteeEntId(item.getInviteeEntId());
            EntCacheResDto entCacheResDto = entCacheResDtoMap.get(item.getInviterEntId());
            queryAllCooperateInfoResVo.setInviterEntName(Objects.nonNull(entCacheResDto) ? entCacheResDto.getFirmName() : "");
            EntCacheResDto entCacheResDto1 = entCacheResDtoMap.get(item.getInviteeEntId());
            queryAllCooperateInfoResVo.setInviteeEntName(Objects.nonNull(entCacheResDto1) ? entCacheResDto1.getFirmName() : "");
            queryAllCooperateInfoResVo.setCooperateTypes(item.getTypes());
            queryAllCooperateInfoResVo.setEnt1(item.getTypes().contains(String.valueOf(CooperateTypeEnum.SUPPLIER.getCode())) ? "是" : "");
            queryAllCooperateInfoResVo.setEnt2(item.getTypes().contains(String.valueOf(CooperateTypeEnum.PURCHASER.getCode())) ? "是" : "");
            queryAllCooperateInfoResVo.setEnt3(item.getTypes().contains(String.valueOf(CooperateTypeEnum.CONSIGN.getCode())) ? "是" : "");
            queryAllCooperateInfoResVo.setEnt4(item.getTypes().contains(String.valueOf(CooperateTypeEnum.CARRIAGE.getCode())) ? "是" : "");
            queryAllCooperateInfoResVo.setInviterContacts(item.getInviterContacts());
            queryAllCooperateInfoResVo.setInviterContactsPhone(item.getInviterPhone());
            queryAllCooperateInfoResVo.setInviteeContacts(item.getInviteeContacts());
            queryAllCooperateInfoResVo.setInviteeContactsPhone(item.getInviteePhone());
            queryAllCooperateInfoResVo.setCreateTime(item.getCreateTime());
            queryAllCooperateInfoResVo.setId(item.getId());
            UserCacheResDto userCacheResDto = userCacheResDtoMap.get(item.getCreateBy());
            queryAllCooperateInfoResVo.setCreateByName(Objects.nonNull(userCacheResDto) ? userCacheResDto.getName() : "");
            queryAllCooperateInfoResVo.setPhone(Objects.nonNull(userCacheResDto) ? userCacheResDto.getPhone() : "");
            queryAllCooperateInfoResVo.setUpdateTime(item.getUpdateTime());
            queryAllCooperateInfoResVo.setRemark(item.getRemark());

            Long manager = mapList.get(item.getInviterEntId()) == null ? null : mapList.get(item.getInviterEntId()).getManager();
            if (Objects.nonNull(manager)){
                queryAllCooperateInfoResVo.setInviterEntUserId(manager);
                inviterEntUserIds.add(manager);
            }
//            Long manager1 = entCacheResDto1.getManager();
            Long manager1 = mapList.get(item.getInviterEntId()) == null ? null : mapList.get(item.getInviterEntId()).getManager();
            if (Objects.nonNull(manager1)){
                queryAllCooperateInfoResVo.setInviteeEntUserId(manager1);
                inviteeEntUserIds.add(manager1);
            }
            result.add(queryAllCooperateInfoResVo);
        });

        List<Long> managerUserIds = new ArrayList<Long>() {{
            addAll(inviterEntUserIds);
            addAll(inviteeEntUserIds);
        }}.stream().distinct().collect(Collectors.toList());
        //客户经理查询
        if (CollectionUtils.isNotEmpty(managerUserIds)){
            Map<Long, UserCacheResDto> userCacheResMap = remoteSystemService.queryUserCacheMapByIds(managerUserIds);
            result.forEach(item -> {
                Long inviterEntUserId = item.getInviterEntUserId();
                item.setInviterEntUserId(inviterEntUserId);
                item.setInviterEntUserName(userCacheResMap.get(inviterEntUserId) == null ? null : userCacheResMap.get(inviterEntUserId).getName());
                item.setInviterEntUserPhone(userCacheResMap.get(inviterEntUserId) == null ? null : userCacheResMap.get(inviterEntUserId).getPhone());

                Long inviteeEntUserId = item.getInviteeEntUserId();
                item.setInviteeEntUserId(inviteeEntUserId);
                item.setInviteeEntUserName(userCacheResMap.get(inviteeEntUserId) == null ? null : userCacheResMap.get(inviteeEntUserId).getName());
                item.setInviteeEntUserPhone(userCacheResMap.get(inviteeEntUserId) == null ? null : userCacheResMap.get(inviteeEntUserId).getPhone());
            });
        }
        return result;
    }


    /**
     * @param reqVo 查询入参
     * @desc: 导出
     * @author: czh
     * @date: 2023/7/11
     */
    public void exportAllCooperateInfo(CooperateManageQueryReqVo reqVo, HttpServletResponse response) {

        //新增客户经理权限过滤
        List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
        if (CollectionUtils.isEmpty(authEntIdList)) {
            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
            if (CollectionUtils.isEmpty(ids)) {
                throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
            }
            authEntIdList.addAll(ids);
        }

        List<CooperateManageQueryResDto> list = kwmCooperateMapper.queryAllCooperateInfoList(getQueryAllCooperateInfoReqDto(reqVo), authEntIdList);
        if (CollectionUtils.isEmpty(list)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        List<QueryAllCooperateInfoResVo> allCooperateInfoVo = getAllCooperateInfoVo(list);
        if (CollectionUtils.isEmpty(allCooperateInfoVo)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        List<QueryAllCooperateInfoExcel> queryAllCooperateInfoExcels = BeanUtils.copyToList(allCooperateInfoVo, QueryAllCooperateInfoExcel.class);
        ExcelUtil.downData(response, QueryAllCooperateInfoExcel.class, queryAllCooperateInfoExcels);
    }

}
