package com.sckw.manage.dubbo;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.CooperateStatusEnum;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.manage.api.RemoteManageService;
import com.sckw.manage.api.model.dto.res.EntAddressResDto;
import com.sckw.manage.api.model.dto.res.FindEntCooperateResVo;
import com.sckw.manage.api.model.dto.res.LineFreightAddressRes;
import com.sckw.manage.dao.KwmAddressMapper;
import com.sckw.manage.dao.KwmCooperateMapper;
import com.sckw.manage.dao.KwmCooperateTypeMapper;
import com.sckw.manage.dao.KwmLineFreightRateMapper;
import com.sckw.manage.model.entity.KwmAddress;
import com.sckw.manage.model.entity.KwmCooperate;
import com.sckw.manage.model.entity.KwmCooperateType;
import com.sckw.manage.model.entity.KwmLineFreightRate;
import com.sckw.manage.model.vo.req.FindCooperateByEntReqVo;
import com.sckw.manage.model.vo.req.FindEntCooperateReqVo;
import com.sckw.manage.model.vo.res.FindCooperateByEntResVo;
import com.sckw.manage.service.CommonBusinessService;
import com.sckw.manage.service.KwmCooperateManageService;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author czh
 * @desc 基础信息+合作管理远程接口实现
 * @date 2023/7/31
 */
@DubboService(group = "design", version = "1.0.0")
public class RemoteManageServiceImpl implements RemoteManageService {

    @Autowired
    private KwmAddressMapper kwmAddressMapper;

    @Autowired
    private KwmCooperateManageService kwmCooperateManageService;

    @Autowired
    private CommonBusinessService commonBusinessService;

    @Autowired
    private KwmCooperateMapper kwmCooperateMapper;

    @Autowired
    private KwmLineFreightRateMapper lineFreightRateMapper;

    @Autowired
    private KwmCooperateTypeMapper kwmCooperateTypeMapper;

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

    /**
     * @param idList 企业id集合
     * @return Map<Long, List < EntAddressResDto>>
     * @desc: 根据企业id查下面的地址
     * @author: czh
     * @date: 2023/7/31
     */
    @Override
    public Map<Long, List<EntAddressResDto>> queryEntAddressByEntIdList(List<Long> idList) {
        Map<Long, List<EntAddressResDto>> map = new HashMap<>(4);
        LambdaQueryWrapper<KwmAddress> kwmAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        kwmAddressLambdaQueryWrapper.in(KwmAddress::getEntId, idList).
                eq(KwmAddress::getDelFlag, Global.NO);
        List<KwmAddress> kwmAddressList = kwmAddressMapper.selectList(kwmAddressLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(kwmAddressList)) {
            return map;
        }

        List<EntAddressResDto> entAddressResDtoList = BeanUtils.copyToList(kwmAddressList, EntAddressResDto.class);
        return entAddressResDtoList.stream().collect(Collectors.groupingBy(EntAddressResDto::getEntId));
    }

    @Override
    public List<FindEntCooperateResVo> findEntCooperate(Long entId, Long targetEntId, Integer cooperateType) {
        FindEntCooperateReqVo findEntCooperateReqVo = new FindEntCooperateReqVo();
        findEntCooperateReqVo.setId(entId);
        findEntCooperateReqVo.setCooperateType(cooperateType);
        findEntCooperateReqVo.setTargetEntId(targetEntId);
        List<com.sckw.manage.model.vo.res.FindEntCooperateResVo> entCooperate = kwmCooperateManageService.findEntCooperate(findEntCooperateReqVo);
        if (CollectionUtils.isEmpty(entCooperate)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(entCooperate, FindEntCooperateResVo.class);
    }

    /**
     * @param entId 集团企业id
     * @return FindEntCooperateResVo
     * @desc: 查询集团企业包括其主体单位下的合作单位所属的集团企业
     * @author: czh
     * @date: 2023/9/1
     */
    @Override
    public List<FindEntCooperateResVo> findAllCooperateEnt(Long entId) {
        if (Objects.isNull(entId)) {
            return Collections.emptyList();
        }
        List<Long> ourEntIds = new ArrayList<>();
        ourEntIds.add(entId);
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntTreeById(entId);
        if (Objects.nonNull(entCacheResDto)) {
            List<EntCacheResDto> child = entCacheResDto.getChild();
            if (CollectionUtils.isNotEmpty(child)) {
                ourEntIds.addAll(child.stream().map(EntCacheResDto::getId).toList());
            }
        }

        //获取当前集团下所有的企业id，遍历，找到合作单位
        List<Long> list = new ArrayList<>();
        List<FindEntCooperateResVo> findEntCooperateResVoList = new ArrayList<>();
        for (Long ourEntId : ourEntIds) {
            FindCooperateByEntReqVo findCooperateByEntReqVo = new FindCooperateByEntReqVo();
            findCooperateByEntReqVo.setEntId(ourEntId);
            List<FindCooperateByEntResVo> cooperateByEnt = kwmCooperateManageService.findCooperateByEnt(findCooperateByEntReqVo);
            if (CollectionUtils.isNotEmpty(cooperateByEnt)) {
                List<Long> targetEntIds = cooperateByEnt.stream().map(FindCooperateByEntResVo::getTargetEntId).toList();
                Map<Long, EntCacheResDto> longEntCacheResDtoMap = remoteSystemService.queryEntTreeByIds(targetEntIds);
                for (Long targetEntId : targetEntIds) {
                    EntCacheResDto entCacheResDto1 = longEntCacheResDtoMap.get(targetEntId);
                    if (Objects.nonNull(entCacheResDto1)) {
                        Long id = entCacheResDto1.getId();
                        if (list.contains(id)) {
                            continue;
                        }
                        list.add(id);
                        FindEntCooperateResVo findEntCooperateResVo = new FindEntCooperateResVo();
                        findEntCooperateResVo.setEntId(id);
                        findEntCooperateResVo.setEntName(entCacheResDto1.getFirmName());
                        findEntCooperateResVoList.add(findEntCooperateResVo);
                    }
                }
            }
        }

        return findEntCooperateResVoList;
    }

    @Override
    public List<com.sckw.manage.api.model.dto.res.FindCooperateByEntResVo> findCooperateByEnt(com.sckw.manage.api.model.dto.res.FindCooperateByEntReqVo reqVo) {
        FindCooperateByEntReqVo byEntReqVo=new FindCooperateByEntReqVo();
        org.springframework.beans.BeanUtils.copyProperties(reqVo,byEntReqVo);
        List<KwmCooperate> kwmCooperates = kwmCooperateMapper.findCooperateByEnt(byEntReqVo);
        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<com.sckw.manage.api.model.dto.res.FindCooperateByEntResVo> list = new ArrayList<>();
        List<Integer> cooperateTypeList = new ArrayList<>();
        for (KwmCooperate kwmCooperate : kwmCooperates) {
            com.sckw.manage.api.model.dto.res.FindCooperateByEntResVo findCooperateByEntResVo = new com.sckw.manage.api.model.dto.res.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;
    }

    @Override
    public Map<Long, LineFreightAddressRes> findLineFreightAddress(List<Long> lineFreightId) {
        List<KwmLineFreightRate> list = lineFreightRateMapper.selectList(new LambdaQueryWrapper<KwmLineFreightRate>()
                .in(KwmLineFreightRate::getId, lineFreightId).eq(KwmLineFreightRate::getDelFlag, 0));
        Map<Long, LineFreightAddressRes> rateMap = new HashMap<>(NumberConstant.SIXTEEN);
        List<LineFreightAddressRes> lineFre = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (KwmLineFreightRate kwmLineFreightRate : list) {
                LineFreightAddressRes lineFreightRate = new LineFreightAddressRes();
                BeanUtil.copyProperties(kwmLineFreightRate, lineFreightRate);
                lineFre.add(lineFreightRate);
            }
        }
        if (!CollectionUtils.isEmpty(lineFre)) {
            rateMap = lineFre.stream().collect(Collectors.toMap(LineFreightAddressRes::getId, Function.identity()));
        }
        return rateMap;
    }

    /**
     * 通过ids获取地址信息
     * @param addressIds
     */
    @Override
    public Map<Long, EntAddressResDto> queryAddressListByAddressIdList(List<String> addressIds) {
        Map<Long, EntAddressResDto> map = new HashMap<>(4);
        LambdaQueryWrapper<KwmAddress> kwmAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        kwmAddressLambdaQueryWrapper.in(KwmAddress::getId, addressIds).
                eq(KwmAddress::getDelFlag, Global.NO);
        List<KwmAddress> kwmAddressList = kwmAddressMapper.selectList(kwmAddressLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(kwmAddressList)) {
            return map;
        }

        List<EntAddressResDto> entAddressResDtoList = BeanUtils.copyToList(kwmAddressList, EntAddressResDto.class);
        return entAddressResDtoList.stream().collect(Collectors.toMap(EntAddressResDto::getId,Function.identity()));
    }
}
