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.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.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
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.dto.res.CooperateQueryDto;
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.vo.req.CooperateApplyQueryReqVo;
import com.sckw.manage.model.vo.req.CooperateApproveReqVo;
import com.sckw.manage.model.vo.req.IdsReqVo;
import com.sckw.manage.model.vo.req.InitiateReqVo;
import com.sckw.manage.model.vo.res.CooperateManageQueryResVo;
import com.sckw.manage.model.vo.res.FindListGroupResVo;
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.UserCacheResDto;
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.function.Function;
import java.util.stream.Collectors;

/**
 * @author czh
 * @desc 合作申请service
 * @date 2023/7/10
 */
@Slf4j
@Service
public class KwmCooperateApplyService {

    @Autowired
    private KwmCooperateMapper kwmCooperateMapper;

    @Autowired
    private CommonBusinessService commonBusinessService;

    @Autowired
    private KwmCooperateTypeMapper kwmCooperateTypeMapper;

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

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

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

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

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

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

        List<CooperateManageQueryResVo> cooperateManageQueryResVos = getCooperateManageQueryResVos(list);
        return PageHelperUtil.getPageResult(new PageInfo<>(cooperateManageQueryResVos), list, reqVo.getPageSize());
    }


    /**
     * @param list 数据
     * @return CooperateManageQueryResVo
     * @desc: 组装返参
     * @author: czh
     * @date: 2023/8/2
     */
    public List<CooperateManageQueryResVo> getCooperateManageQueryResVos(List<CooperateManageQueryResDto> list) {
        //dubbo接口查用户和企业
        Long entId = LoginUserHolder.getEntId();
        List<Long> userIds = list.stream().map(CooperateManageQueryResDto::getCreateBy).distinct().toList();
        List<Long> allEntIds = new ArrayList<>();
        List<Long> targetEntIds = list.stream().map(CooperateManageQueryResDto::getTargetEntId).distinct().toList();
        List<Long> ourEntIds = list.stream().map(CooperateManageQueryResDto::getOurEntId).distinct().toList();
        allEntIds.addAll(ourEntIds);
        allEntIds.addAll(targetEntIds);
        Map<Long, UserCacheResDto> userCacheResDtoMap = remoteSystemService.queryUserCacheMapByIds(userIds);
        List<EntCacheResDto> entCacheResDtos = remoteSystemService.queryEntCacheByIds(allEntIds);
        Map<Long, EntCacheResDto> entMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (!CollectionUtils.isEmpty(entCacheResDtos)) {
            entMap = entCacheResDtos.stream().collect(Collectors.toMap(EntCacheResDto::getId, Function.identity()));
        }

        List<CooperateManageQueryResVo> result = new ArrayList<>();
        for (CooperateManageQueryResDto cooperateManageQueryResDto : list) {
            Long targetEntId = cooperateManageQueryResDto.getTargetEntId();
            EntCacheResDto entCacheResDto = entMap.get(targetEntId);
            EntCacheResDto entCacheResDto2 = entMap.get(cooperateManageQueryResDto.getOurEntId());

            CooperateManageQueryResVo cooperateManageQueryResVo = new CooperateManageQueryResVo();
            cooperateManageQueryResVo.setId(cooperateManageQueryResDto.getId() + "_" + cooperateManageQueryResDto.getStatus());
            cooperateManageQueryResVo.setCreateTime(cooperateManageQueryResDto.getCreateTime());
            cooperateManageQueryResVo.setRemark(cooperateManageQueryResDto.getRemark());
            cooperateManageQueryResVo.setStatus(cooperateManageQueryResDto.getStatus());

            UserCacheResDto userCacheResDto = userCacheResDtoMap.get(cooperateManageQueryResDto.getCreateBy());
            cooperateManageQueryResVo.setCreateByName(userCacheResDto.getName());
            EntCacheResDto entInfo = userCacheResDto.getEntInfo();
            boolean isOur = entId.equals(entInfo.getId());
            cooperateManageQueryResVo.setApplyTypeCode(isOur ? Global.NUMERICAL_ONE : Global.NUMERICAL_TWO);

            cooperateManageQueryResVo.setTargetEntName(Objects.nonNull(entCacheResDto) ? entCacheResDto.getFirmName() : "");
            cooperateManageQueryResVo.setTargetEntId(targetEntId);
            cooperateManageQueryResVo.setEntId(cooperateManageQueryResDto.getOurEntId());
            cooperateManageQueryResVo.setEntName(Objects.nonNull(entCacheResDto2) ? entCacheResDto2.getFirmName() : "");
            cooperateManageQueryResVo.setApprovalRemark(cooperateManageQueryResDto.getApprovalRemark());
            cooperateManageQueryResVo.setHead(Objects.nonNull(entCacheResDto) ? entCacheResDto.getHead() : "");
            //我方是发起方
            if (isOur) {
                cooperateManageQueryResVo.setContacts(cooperateManageQueryResDto.getInviteeContacts());
                cooperateManageQueryResVo.setPhone(cooperateManageQueryResDto.getInviteePhone());
                cooperateManageQueryResVo.setContactsId(cooperateManageQueryResDto.getInviteeContactsId());
                cooperateManageQueryResVo.setManager(cooperateManageQueryResDto.getInviterContacts());
                cooperateManageQueryResVo.setManagerPhone(cooperateManageQueryResDto.getInviterPhone());
                cooperateManageQueryResVo.setManagerId(cooperateManageQueryResDto.getInviterContactsId());
            } else {
                cooperateManageQueryResVo.setContacts(cooperateManageQueryResDto.getInviterContacts());
                cooperateManageQueryResVo.setPhone(cooperateManageQueryResDto.getInviterPhone());
                cooperateManageQueryResVo.setContactsId(cooperateManageQueryResDto.getInviterContactsId());
                cooperateManageQueryResVo.setManager(cooperateManageQueryResDto.getInviteeContacts());
                cooperateManageQueryResVo.setManagerPhone(cooperateManageQueryResDto.getInviteePhone());
                cooperateManageQueryResVo.setManagerId(cooperateManageQueryResDto.getInviteeContactsId());
            }

            if (entId.equals(cooperateManageQueryResDto.getEntId())) {
                cooperateManageQueryResVo.setCooperateTypes(cooperateManageQueryResDto.getTypes());
            } else {
                cooperateManageQueryResVo.setCooperateTypes(commonBusinessService.changeCooperateType(cooperateManageQueryResDto.getTypes()));
            }


            result.add(cooperateManageQueryResVo);
        }
        return result;
    }

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

        if (StringUtils.isNotBlank(reqVo.getIds())) {
            cooperateManageQueryReqDto.setIds(StringUtils.splitStrToList(reqVo.getIds(), Long.class));
        }
        //只允许查出申请中、已拒绝、已撤销的记录
        List<Integer> status = new ArrayList<>();
        if (Objects.isNull(reqVo.getStatus())) {
            status.add(CooperateStatusEnum.PROCESS.getCode());
            status.add(CooperateStatusEnum.REFUSE.getCode());
            status.add(CooperateStatusEnum.CANCEL.getCode());
        }

        if (Objects.nonNull(reqVo.getStatus()) && reqVo.getStatus().equals(CooperateStatusEnum.PROCESS.getCode())) {
            status.add(CooperateStatusEnum.PROCESS.getCode());
        }
        if (Objects.nonNull(reqVo.getStatus()) && reqVo.getStatus().equals(CooperateStatusEnum.REFUSE.getCode())) {
            status.add(CooperateStatusEnum.REFUSE.getCode());
        }
        if (Objects.nonNull(reqVo.getStatus()) && reqVo.getStatus().equals(CooperateStatusEnum.CANCEL.getCode())) {
            status.add(CooperateStatusEnum.CANCEL.getCode());
        }
        cooperateManageQueryReqDto.setStatus(status);

        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 reqVo 申请入参
     * @desc: 发起申请
     * @author: czh
     * @date: 2023/7/11
     */
    @Transactional(rollbackFor = {})
    public void initiate(InitiateReqVo reqVo) {
        Long currentEntId = reqVo.getEntId();
        List<Integer> chooseCooperateTypes = Arrays.stream(reqVo.getChooseCooperateTypes().split(Global.COMMA)).map(Integer::parseInt).toList();

        //查是否有在合作中、审核中的记录
        List<CooperateQueryDto> cooperateQueryDtoList = queryValidCooperate(reqVo.getTargetEntId(), currentEntId);
        if (!CollectionUtils.isEmpty(cooperateQueryDtoList)) {
            //有待审核的记录不允许新增申请
            for (CooperateQueryDto cooperateQueryDto : cooperateQueryDtoList) {
                List<KwmCooperateType> kwmCooperateTypeList = cooperateQueryDto.getKwmCooperateTypeList();
                if (CollectionUtils.isEmpty(kwmCooperateTypeList)) {
                    throw new SystemException(HttpStatus.CODE_10301, HttpStatus.COOPERATE_ATTRIBUTE_NOT_EXISTS);
                }

                for (KwmCooperateType kwmCooperateType : kwmCooperateTypeList) {
                    if (kwmCooperateType.getStatus().equals(CooperateStatusEnum.PROCESS.getCode())) {
                        throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.MSG_015);
                    }
                }

                //已合作的可以新增，但不能重复新增
                List<Integer> typeList = kwmCooperateTypeList.stream().map(KwmCooperateType::getType).toList();
                chooseCooperateTypes.forEach(item -> {
                    if (typeList.contains(item)) {
                        throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_016);
                    }
                });

//                //对方发起了与之相对的申请，也不能再申请
//                if (cooperateQueryDto.getKwmCooperate().getInviteeEntId().equals(currentEntId)) {
//                    chooseCooperateTypes.forEach(item -> {
//                        Integer relative = commonBusinessService.changeAttribute(item);
//                        if (typeList.contains(relative)) {
//                            throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_016);
//                        }
//                    });
//                }
            }
        }
        //保存发起申请
        saveInitiate(reqVo, currentEntId, chooseCooperateTypes);

        //发起合作申请消息
        try {
            EntCacheResDto targetEntCacheResDto = remoteSystemService.queryEntCacheById(reqVo.getTargetEntId());
            Map<String, Object> map = new HashMap<>(Global.NUMERICAL_FOUR);
            map.put("entName", targetEntCacheResDto.getFirmName());
            map.put("createByName", LoginUserHolder.getUserName());
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(LoginUserHolder.getUserId()).setEntId(LoginUserHolder.getEntId())),
                    MessageEnum.SUBMIT_COOPERATE,
                    map,
                    cooperateApplyUrl,
                    appCooperateApplyUrl);

            //合作申请待审核消息
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(reqVo.getEntId());
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntTreeById(reqVo.getTargetEntId());
            map.put("entName", entCacheResDto.getFirmName());
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto1.getContactsId()).setEntId(entCacheResDto1.getId())),
                    MessageEnum.COOPERATE_WAIT_APPROVAL,
                    map,
                    cooperateApplyUrl,
                    appCooperateApplyUrl);
        } catch (Exception e) {
           log.error("发起合作申请消息出错:", e);
        }
    }


    /**
     * @param reqVo 入参， currentEntId当前企业id，选择的企业类型
     * @desc: 保存发起申请
     * @author: czh
     * @date: 2023/7/11
     */
    public void saveInitiate(InitiateReqVo reqVo, Long currentEntId, List<Integer> chooseCooperateTypes) {
        Date date = new Date();
        Long id = reqVo.getId();
        if (Objects.isNull(reqVo.getId())) {
            KwmCooperate kwmCooperate = new KwmCooperate();
            id = new IdWorker(1L).nextId();
            kwmCooperate.setEntId(LoginUserHolder.getEntId());
            kwmCooperate.setInviterEntId(currentEntId);
            kwmCooperate.setInviteeEntId(reqVo.getTargetEntId());

            //我方联系人
            UserCacheResDto contactDto = remoteSystemService.queryUserCacheById(reqVo.getUserId());
            if (Objects.nonNull(contactDto)) {
                kwmCooperate.setInviterContactsId(contactDto.getId());
                kwmCooperate.setInviterContacts(contactDto.getName());
                kwmCooperate.setInviterPhone(contactDto.getPhone());
            }

            //对方联系人
            UserCacheResDto userCacheResDto = remoteSystemService.queryManagerInfoByEntId(reqVo.getTargetEntId());
            if (Objects.nonNull(userCacheResDto)) {
                kwmCooperate.setInviteeContactsId(userCacheResDto.getId());
                kwmCooperate.setInviteeContacts(contactDto.getName());
                kwmCooperate.setInviteePhone(contactDto.getPhone());
            }

            kwmCooperate.setId(id);
            kwmCooperate.setRemark(reqVo.getRemark());
            kwmCooperate.setStatus(CooperateStatusEnum.PROCESS.getCode());
            kwmCooperate.setCreateBy(LoginUserHolder.getUserId());
            kwmCooperate.setCreateTime(date);
            kwmCooperate.setUpdateBy(LoginUserHolder.getUserId());
            kwmCooperate.setUpdateTime(date);
            kwmCooperate.setDelFlag(Global.NO);
            if (kwmCooperateMapper.insert(kwmCooperate) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
            }
        } else {
            KwmCooperate kwmCooperate = kwmCooperateMapper.selectById(id);
            if (Objects.nonNull(kwmCooperate)) {
                kwmCooperate.setUpdateBy(LoginUserHolder.getUserId());
                kwmCooperate.setUpdateTime(date);
                kwmCooperateMapper.updateById(kwmCooperate);
            }
        }

        KwmCooperate kwmCooperate = kwmCooperateMapper.selectById(id);
        for (Integer item : chooseCooperateTypes) {
            KwmCooperateType kwmCooperateType = new KwmCooperateType();
            kwmCooperateType.setId(new IdWorker(1L).nextId());
            kwmCooperateType.setCooperateId(id);
            if (!kwmCooperate.getEntId().equals(LoginUserHolder.getEntId())) {
                item = commonBusinessService.changeCooperateType(item);
            }
            kwmCooperateType.setType(item);
            kwmCooperateType.setStatus(CooperateStatusEnum.PROCESS.getCode());
            kwmCooperateType.setCreateBy(LoginUserHolder.getUserId());
            kwmCooperateType.setCreateTime(date);
            kwmCooperateType.setUpdateBy(LoginUserHolder.getUserId());
            kwmCooperateType.setUpdateTime(date);
            kwmCooperateType.setDelFlag(Global.NO);
            if (kwmCooperateTypeMapper.insert(kwmCooperateType) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
            }
        }

    }

    /**
     * @param currentEntId 当前企业id  chooseCooperateTypes选择的合作属性  kwmCooperates已有的合作记录
     * @desc: 新增申请前判重
     * @author: czh
     * @date: 2023/7/11
     */
    private void checkTypeRepeat(Long currentEntId, List<Integer> chooseCooperateTypes, List<KwmCooperate> kwmCooperates) {
        for (KwmCooperate kwmCooperate : kwmCooperates) {
            //受邀请方
            Long inviteeEntId = kwmCooperate.getInviteeEntId();
            //发起方
            Long inviterEntId = kwmCooperate.getInviterEntId();
            LambdaQueryWrapper<KwmCooperateType> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KwmCooperateType::getCooperateId, kwmCooperate.getId());
            List<KwmCooperateType> kwmCooperateTypes = kwmCooperateTypeMapper.selectList(wrapper);
            if (CollectionUtils.isEmpty(kwmCooperateTypes)) {
                throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COOPERATE_ATTRIBUTE_NOT_EXISTS);
            }

            //判断是否有重复的合作属性
            List<Integer> typeList = kwmCooperateTypes.stream().map(KwmCooperateType::getType).toList();
            if (inviterEntId.equals(currentEntId)) {
                chooseCooperateTypes.forEach(item -> {
                    if (typeList.contains(item)) {
                        throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_016);
                    }
                });
            }

            if (inviteeEntId.equals(currentEntId)) {
                chooseCooperateTypes.forEach(item -> {
                    Integer relative = commonBusinessService.changeAttribute(item);
                    if (typeList.contains(relative)) {
                        throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_016);
                    }
                });
            }
        }
    }

    /**
     * @param entId 对方企业id  currentEntId 我方企业id
     * @return CooperateQueryDto
     * @desc: 查是否有在合作中、审核中的记录
     * @author: czh
     * @date: 2023/7/11
     */
    private List<CooperateQueryDto> queryValidCooperate(Long entId, Long currentEntId) {
        LambdaQueryWrapper<KwmCooperate> wrapper = new LambdaQueryWrapper<>();
        List<Integer> statusList = new ArrayList<>();
        statusList.add(CooperateStatusEnum.OK.getCode());
        statusList.add(CooperateStatusEnum.PROCESS.getCode());
        wrapper.eq(KwmCooperate::getDelFlag, Global.NO).
                in(KwmCooperate::getStatus, statusList).
                and(wq -> wq.eq(KwmCooperate::getInviteeEntId, entId).
                        eq(KwmCooperate::getInviterEntId, currentEntId).
                        or().
                        eq(KwmCooperate::getInviteeEntId, currentEntId).
                        eq(KwmCooperate::getInviterEntId, entId));
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(kwmCooperates)) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<KwmCooperateType> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(KwmCooperateType::getDelFlag, Global.NO).
                in(KwmCooperateType::getStatus, statusList).
                in(KwmCooperateType::getCooperateId, kwmCooperates.stream().map(KwmCooperate::getId).toList());
        List<KwmCooperateType> kwmCooperateTypes = kwmCooperateTypeMapper.selectList(wrapper2);
        Map<Long, List<KwmCooperateType>> map = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(kwmCooperateTypes)) {
            map = kwmCooperateTypes.stream().collect(Collectors.groupingBy(KwmCooperateType::getCooperateId));
        }

        List<CooperateQueryDto> list = new ArrayList<>();
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntTreeById(currentEntId);

        for (KwmCooperate kwmCooperate : kwmCooperates) {
            CooperateQueryDto cooperateQueryDto = new CooperateQueryDto();
            cooperateQueryDto.setKwmCooperate(kwmCooperate);

            List<KwmCooperateType> kwmCooperateTypeList = map.get(kwmCooperate.getId());
            if (CollectionUtils.isNotEmpty(kwmCooperateTypeList)) {
                List<Long> longs = kwmCooperateTypeList.stream().map(KwmCooperateType::getCreateBy).toList();
                Map<Long, UserCacheResDto> longUserCacheResDtoMap = remoteSystemService.queryUserCacheMapByIds(longs);
                for (KwmCooperateType kwmCooperateType : kwmCooperateTypeList) {
                    Long createBy = kwmCooperateType.getCreateBy();
                    if (!entCacheResDto.getId().equals(longUserCacheResDtoMap.get(createBy).getEntInfo().getId())) {
                        kwmCooperateType.setType(commonBusinessService.changeCooperateType(kwmCooperateType.getType()));
                    }
                }
            }

            cooperateQueryDto.setKwmCooperateTypeList(kwmCooperateTypeList);
            list.add(cooperateQueryDto);
        }

        return list;
    }


    /**
     * @param reqVo 主键
     * @desc: 撤销
     * @author: czh
     * @date: 2023/7/11
     */
    public void cancel(IdsReqVo reqVo) {
        updateCooperateInfo(reqVo.getIds(), CooperateStatusEnum.CANCEL.getCode(), reqVo.getRemark());
    }


    /**
     * @param ids 主键 type需要修改为的类型
     * @desc: 抽取公共方法
     * @author: czh
     * @date: 2023/7/11
     */
    @Transactional(rollbackFor = {})
    public void updateCooperateInfo(String ids, Integer type, String remark) {
        List<Long> idList = Arrays.stream(ids.split(Global.COMMA)).map(item -> item.contains("_") ? item.substring(0, item.indexOf("_")) : item).map(Long::parseLong).toList();
        LambdaQueryWrapper<KwmCooperate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwmCooperate::getDelFlag, Global.NO);
        wrapper.in(KwmCooperate::getId, idList);
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(kwmCooperates) || kwmCooperates.size() != idList.size()) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COOPERATE_NOT_EXISTS);
        }

        Long userId = LoginUserHolder.getUserId();
        Date date = new Date();
        List<Integer> statusList = new ArrayList<>();
        statusList.add(CooperateStatusEnum.PROCESS.getCode());
        statusList.add(CooperateStatusEnum.OK.getCode());
        kwmCooperates.forEach(item -> {
            List<KwmCooperateType> kwmCooperateTypes = kwmCooperateTypeMapper.selectList(new LambdaQueryWrapper<KwmCooperateType>().
                    eq(KwmCooperateType::getCooperateId, item.getId()).
                    in(KwmCooperateType::getStatus, statusList).
                    eq(KwmCooperateType::getDelFlag, Global.NO));
            List<KwmCooperateType> updateKwmCooperateTypes = kwmCooperateTypes.stream().filter(x -> x.getStatus().equals(CooperateStatusEnum.PROCESS.getCode())).toList();
            if (CollectionUtils.isEmpty(updateKwmCooperateTypes)) {
                throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COOPERATE_CANCEL_EXISTS);
            }

            //目前只有一条
            for (KwmCooperateType kwmCooperateType : updateKwmCooperateTypes) {
                kwmCooperateType.setStatus(type);
                kwmCooperateType.setUpdateBy(userId);
                kwmCooperateType.setUpdateTime(date);
                if (kwmCooperateTypeMapper.updateById(kwmCooperateType) <= 0) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
                }
            }

            item.setUpdateBy(userId);
            item.setUpdateTime(date);
            item.setApprovalRemark(remark);
            List<Integer> currentStatusList = kwmCooperateTypes.stream().map(KwmCooperateType::getStatus).toList();
            if (type.equals(CooperateStatusEnum.OK.getCode())) {
                item.setStatus(type);
            }

            if ((type.equals(CooperateStatusEnum.CANCEL.getCode()) || type.equals(CooperateStatusEnum.REFUSE.getCode())) && !currentStatusList.contains(CooperateStatusEnum.OK.getCode())) {
                item.setStatus(type);
            }

            if (kwmCooperateMapper.updateById(item) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }
        });
    }


    /**
     * @param reqVo 入参
     * @desc: 审核
     * @author: czh
     * @date: 2023/7/11
     */
    @Transactional(rollbackFor = {})
    public void approve(CooperateApproveReqVo reqVo) {
        updateCooperateInfo(reqVo.getIds(), reqVo.getApprove(), reqVo.getRemark());
        for (String id : reqVo.getIds().split(Global.COMMA)) {
            id = id.contains("_") ? id.substring(0, id.indexOf("_")) : id;
            if (reqVo.getApprove().equals(CooperateStatusEnum.OK.getCode())) {
                commonBusinessService.bingManager(reqVo.getManager(), Long.parseLong(id));
                passMessage(id);
            } else {
                refuseMessage(id);
            }
        }
    }

    private void refuseMessage(String id) {
        try {
            KwmCooperate kwmCooperate = kwmCooperateMapper.selectById(Long.parseLong(id));
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(kwmCooperate.getEntId());
            Map<String, Object> map = new HashMap<>(Global.NUMERICAL_TWO);
            map.put("entName", entCacheResDto.getFirmName());
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto.getContactsId()).setEntId(entCacheResDto.getId())),
                    MessageEnum.COOPERATE_REFUSED,
                    map,
                    cooperateApplyUrl,
                    appCooperateApplyUrl);
        } catch (NumberFormatException e) {
            log.error("合作申请审核驳回消息出错:", e);
        }
    }

    private void passMessage(String id) {
        try {
            KwmCooperate kwmCooperate = kwmCooperateMapper.selectById(Long.parseLong(id));
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(kwmCooperate.getEntId());
            Map<String, Object> map = new HashMap<>(Global.NUMERICAL_TWO);
            map.put("entName", entCacheResDto.getFirmName());
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto.getContactsId()).setEntId(entCacheResDto.getId())),
                    MessageEnum.COOPERATE_PASS,
                    map,
                    cooperateManageUrl,
                    appCooperateApplyUrl);
        } catch (Exception e) {
            log.error("合作申请审核通过消息出错:", e);
        }
    }


    /**
     * @param reqVo 全量入参
     * @desc: 导出
     * @author: czh
     * @date: 2023/7/11
     */
    public void export(CooperateApplyQueryReqVo reqVo, HttpServletResponse response) {
        CooperateManageQueryReqDto reqDto = buildQueryParam(reqVo);
        List<CooperateManageQueryResDto> list = kwmCooperateMapper.findList(reqDto);
        if (CollectionUtils.isEmpty(list)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }

        List<CooperateManageQueryResVo> cooperateManageQueryResVos = 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(CooperateApplyQueryReqVo reqVo) {
        //初始化分组返参
        List<FindListGroupResVo> result = commonBusinessService.init();
        List<CooperateManageQueryResDto> list = kwmCooperateMapper.findList(buildQueryParam(reqVo));
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }

        List<CooperateManageQueryResVo> cooperateManageQueryResVos = getCooperateManageQueryResVos(list);
        if (CollectionUtils.isEmpty(cooperateManageQueryResVos)) {
            return result;
        }

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


}
