package com.sckw.order.serivce;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.Global;
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.model.vo.TableBottom;
import com.sckw.core.model.vo.TableStatisticRes;
import com.sckw.core.model.vo.TableTop;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.DateUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginEntHolder;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.excel.utils.DateUtil;
import com.sckw.order.dao.KwoTransportDemandMapper;
import com.sckw.order.enums.TransportDemandStatusEnum;
import com.sckw.order.model.KwoTransportDemand;
import com.sckw.order.model.dto.TransportDemandExport;
import com.sckw.order.model.vo.req.*;
import com.sckw.order.model.vo.res.TransportDemandContactInfoRes;
import com.sckw.order.model.vo.res.TransportDemandDetailRes;
import com.sckw.order.model.vo.res.TransportDemandListRes;
import com.sckw.order.model.vo.res.TransportDemandSquaresListRes;
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.SysDictResDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

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

/**
 * @desc: 运需service
 * @author: yzc
 * @date: 2023-06-25 14:53
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class KwoTransportDemandService {

    private final KwoTransportDemandMapper kwoTransportDemandMapper;

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

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


    /**
     * @desc: 添加草稿
     * @author: yzc
     * @date: 2023-07-26 10:32
     * @Param param:
     * @return: void
     */
    public void addDraft(AddTransportDemandDraftParam param) {
        KwoTransportDemand transportDemand = BeanUtils.copyProperties(param, KwoTransportDemand.class);
        transportDemand.setDeadline(DateUtils.localDateToDateEnd(param.getDeadline()));
        transportDemand.setEntId(LoginUserHolder.getEntId()).setStatus(TransportDemandStatusEnum.SAVED.getCode());
        kwoTransportDemandMapper.insert(transportDemand);
    }

    /**
     * @desc: 添加上架
     * @author: yzc
     * @date: 2023-07-26 10:32
     * @Param param:
     * @return: void
     */
    public void addShelves(AddTransportDemandParam param) {
        KwoTransportDemand transportDemand = BeanUtils.copyProperties(param, KwoTransportDemand.class);
        transportDemand.setDeadline(DateUtils.localDateToDateEnd(param.getDeadline()));
        transportDemand.setEntId(LoginUserHolder.getEntId()).setStatus(TransportDemandStatusEnum.PUT_ON_SHELVES.getCode());
        kwoTransportDemandMapper.insert(transportDemand);
    }

    /**
     * @desc: 运需详情
     * @author: yzc
     * @date: 2023-07-26 10:32
     * @Param id:
     * @return: com.sckw.order.model.vo.res.TransportDemandDetailRes
     */
    public TransportDemandDetailRes detail(Long id) {
        KwoTransportDemand transportDemand = getById(id, Boolean.FALSE);
        if (Objects.isNull(transportDemand)) {
            throw new BusinessException("数据不存在！");
        }
        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.PRODUCT_NAME_TYPE.getType(),
                DictTypeEnum.TRADE_TYPE.getType(), DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType()));
        Map<String, String> productNameMap, tradeMap, statusMap;
        if (CollectionUtils.isEmpty(dict)) {
            productNameMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
            tradeMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
            statusMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        } else {
            productNameMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType());
            tradeMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.TRADE_TYPE.getType());
            statusMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType());
        }
        TransportDemandDetailRes res = BeanUtils.copyProperties(transportDemand, TransportDemandDetailRes.class);
        List<SysDictResDto> types = remoteSystemService.queryDictFrontAll(DictTypeEnum.PRODUCT_NAME_TYPE.getType(), res.getGoodsType());
        if (CollectionUtils.isNotEmpty(types)) {
            res.setGoodsTypes(types.stream().map(SysDictResDto::getValue).toList())
                    .setGoodsTypeLabels(String.join(Global.RIGHT_SLASH, types.stream().map(SysDictResDto::getLabel).toList()));
        }
        res.setGoodsTypeLabel(productNameMap.get(res.getGoodsType()))
                .setTradingLabel(tradeMap.get(res.getTrading()))
                .setStatusLabel(statusMap.get(String.valueOf(res.getStatus())));
        return res;
    }

    /**
     * @desc: 根据id获取
     * @author: yzc
     * @date: 2023-07-26 11:27
     * @Param id:
     * @return: com.sckw.order.model.KwoTransportDemand
     */
    private KwoTransportDemand getById(Long id, Boolean needPermissions) {
        LambdaQueryWrapper<KwoTransportDemand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwoTransportDemand::getId, id);
        if (needPermissions) {
            wrapper.eq(KwoTransportDemand::getEntId, LoginUserHolder.getEntId());
        }
        wrapper.eq(KwoTransportDemand::getDelFlag, Global.NO).last("LIMIT 1");
        return kwoTransportDemandMapper.selectOne(wrapper);
    }

    /**
     * @desc: 运需修改
     * @author: yzc
     * @date: 2023-07-26 10:33
     * @Param param:
     * @return: void
     */
    public void update(UpdateTransportDemandParam param) {
        KwoTransportDemand demand = getById(param.getId(), true);
        if (Objects.isNull(demand)) {
            throw new BusinessException("数据不存在！");
        }
        LambdaUpdateWrapper<KwoTransportDemand> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(KwoTransportDemand::getName, param.getName())
                .set(KwoTransportDemand::getGoodsType, param.getGoodsType())
                .set(KwoTransportDemand::getSpec, param.getSpec())
                .set(KwoTransportDemand::getTrading, param.getTrading())
                .set(KwoTransportDemand::getPrice, param.getPrice())
                .set(KwoTransportDemand::getAmount, param.getAmount())
                .set(KwoTransportDemand::getDeadline, DateUtils.localDateToDateEnd(param.getDeadline()))
                .set(KwoTransportDemand::getContacts, param.getContacts())
                .set(KwoTransportDemand::getPhone, param.getPhone())
                .set(KwoTransportDemand::getLoadAreaCode, param.getLoadAreaCode())
                .set(KwoTransportDemand::getLoadAreaName, param.getLoadAreaName())
                .set(KwoTransportDemand::getLoadDetailAddress, param.getLoadDetailAddress())
                .set(KwoTransportDemand::getUnloadAreaCode, param.getUnloadAreaCode())
                .set(KwoTransportDemand::getUnloadAreaName, param.getUnloadAreaName())
                .set(KwoTransportDemand::getUnloadDetailAddress, param.getUnloadDetailAddress())
                .set(KwoTransportDemand::getRemark, param.getRemark())
                .eq(KwoTransportDemand::getId, param.getId());
        kwoTransportDemandMapper.update(null, wrapper);
    }

    /**
     * @desc: 参数校验
     * @author: yzc
     * @date: 2023-07-26 11:30
     * @Param param:
     * @return: void
     */
    private void checkParams(UpdateTransportDemandParam param) {
        if (StringUtils.isBlank(param.getName())) {
            throw new BusinessException("商品名称不能为空");
        }
        if (StringUtils.isBlank(param.getPrice())) {
            throw new BusinessException("运需单价不能为空");
        }
        if (StringUtils.isBlank(param.getAmount())) {
            throw new BusinessException("运输总量不能为空");
        }
        if (StringUtils.isBlank(param.getContacts())) {
            throw new BusinessException("联系人姓名不能为空");
        }
        if (StringUtils.isBlank(param.getPhone())) {
            throw new BusinessException("联系人电话不能为空");
        }
        if (Objects.isNull(param.getLoadAreaCode())) {
            throw new BusinessException("装货区域code不能为空");
        }
        if (StringUtils.isBlank(param.getLoadAreaName())) {
            throw new BusinessException("装货区域名称不能为空");
        }
        if (Objects.isNull(param.getUnloadAreaCode())) {
            throw new BusinessException("卸货区域code不能为空");
        }
        if (StringUtils.isBlank(param.getUnloadAreaName())) {
            throw new BusinessException("卸货区域名称不能为空");
        }
    }

    /**
     * @desc: 运需分页查询
     * @author: yzc
     * @date: 2023-07-26 10:33
     * @Param param:
     * @return: com.sckw.core.model.page.PageResult
     */
    public PageResult select(SelectTransportDemandParam param) {

        //新增客户经理权限过滤
        List<Long> authEntIdList = new ArrayList<>();
        if (SystemTypeEnum.MANAGE.getCode() == LoginUserHolder.getSystemType()) {

            authEntIdList = LoginUserHolder.getAuthEntIdList();
            if (CollectionUtils.isEmpty(authEntIdList)) {
                List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                if (CollectionUtils.isEmpty(ids)) {
                    return PageHelperUtil.getPageResult(new PageInfo<>());
                }
                authEntIdList.addAll(ids);
            }
        }
//        else {
//            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
//            if (CollectionUtils.isEmpty(ids)) {
//                return PageHelperUtil.getPageResult(new PageInfo<>());
//            }
//            authEntIdList.addAll(ids);
//        }

        LambdaQueryWrapper<KwoTransportDemand> wrapper = buildWrapper(BeanUtils.copyProperties(param, ExportTransportDemandParam.class), authEntIdList);
        IPage<KwoTransportDemand> page = new Page<>(param.getPage(), param.getPageSize());
        IPage<KwoTransportDemand> demandPage = kwoTransportDemandMapper.selectPage(page, wrapper);
        List<KwoTransportDemand> list = demandPage.getRecords();
        if (CollectionUtils.isEmpty(list)) {
            return PageResult.build(param.getPage(), param.getPageSize(), demandPage.getTotal(), Collections.emptyList());
        }

        // 获取供应企业信息
        List<Long> supplyEntIds = list.stream().map(KwoTransportDemand::getEntId).collect(Collectors.toList());
        // 通过企业id查询企业信息
        List<EntCacheResDto> entList = remoteSystemService.queryEntCacheByIds(supplyEntIds);
        Map<Long, String> entMap = entList.stream().collect(Collectors.toMap(EntCacheResDto::getId, EntCacheResDto::getFirmName, (k1, k2) -> k1));

        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.PRODUCT_NAME_TYPE.getType(),
                DictTypeEnum.TRADE_TYPE.getType(), DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType()));
        Map<String, String> productNameMap, tradeMap, statusMap;
        if (CollectionUtils.isNotEmpty(dict)) {
            productNameMap = CollectionUtils.isNotEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType()) : new HashMap<>(Global.NUMERICAL_SIXTEEN);
            tradeMap = CollectionUtils.isNotEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    dict.get(DictTypeEnum.TRADE_TYPE.getType()) : new HashMap<>(Global.NUMERICAL_SIXTEEN);
            statusMap = CollectionUtils.isNotEmpty(dict.get(DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType())) ?
                    dict.get(DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType()) : new HashMap<>(Global.NUMERICAL_SIXTEEN);
        } else {
            productNameMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
            tradeMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
            statusMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        }
        List<TransportDemandListRes> result = Lists.newArrayList();
        list.forEach(e -> {
            TransportDemandListRes demand = BeanUtils.copyProperties(e, TransportDemandListRes.class);
            String loadAreaName = Objects.nonNull(e.getLoadAreaName()) ? e.getLoadAreaName() : "";
            String loadDetailAddress = Objects.nonNull(e.getLoadDetailAddress()) ? e.getLoadDetailAddress() : "";
            String unloadAreaName = Objects.nonNull(e.getUnloadAreaName()) ? e.getUnloadAreaName() : "";
            String unloadDetailAddress = Objects.nonNull(e.getUnloadDetailAddress()) ? e.getUnloadDetailAddress() : "";
            demand.setGoodsTypeLabel(productNameMap.get(e.getGoodsType()))
                    .setTradingLabel(tradeMap.get(e.getTrading()))
                    .setStatusLabel(statusMap.get(String.valueOf(e.getStatus())))
                    .setLoadAddress(loadAreaName + loadDetailAddress)
                    .setUnloadAddress(unloadAreaName + unloadDetailAddress)
                    .setEntName(entMap.get(e.getEntId()));
            result.add(demand);
        });
        return PageResult.build(param.getPage(), param.getPageSize(), demandPage.getTotal(), result);
    }

    /**
     * @desc: 构建wrapper
     * @author: yzc
     * @date: 2023-07-26 14:00
     * @Param param:
     * @return: com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.sckw.order.model.KwoTransportDemand>
     */
    private LambdaQueryWrapper<KwoTransportDemand> buildWrapper(ExportTransportDemandParam param, List<Long> authEntIdList) {
        LambdaQueryWrapper<KwoTransportDemand> wrapper = new LambdaQueryWrapper<>();

        if (authEntIdList.size() > 0) {
            authEntIdList = authEntIdList.stream().distinct().collect(Collectors.toList());
            wrapper.in(KwoTransportDemand::getEntId, authEntIdList);
        }

        wrapper.eq(KwoTransportDemand::getDelFlag, Global.NO);
        if (!Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode())) {
            wrapper.eq(KwoTransportDemand::getEntId, LoginUserHolder.getEntId());
        } else if (Objects.isNull(param.getStatus())) {
            wrapper.in(KwoTransportDemand::getStatus, 1, 2);
        }
        if (StringUtils.isNotBlank(param.getIds())) {
            List<Long> ids = StringUtils.splitStrToList(param.getIds(), ",", Long.class);
            wrapper.in(KwoTransportDemand::getId, ids).orderByDesc(KwoTransportDemand::getCreateTime);
            return wrapper;
        }
        if (Objects.nonNull(param.getEndCreateTime())) {
            wrapper.le(KwoTransportDemand::getCreateTime, param.getEndCreateTime());
        }
        wrapper.ge(Objects.nonNull(param.getStartCreateTime()), KwoTransportDemand::getCreateTime, param.getStartCreateTime())
                .eq(Objects.nonNull(param.getStatus()), KwoTransportDemand::getStatus, param.getStatus())
                .like(Objects.nonNull(param.getKeywords()), KwoTransportDemand::getName, param.getKeywords());
        Integer loadCode = param.getLoadAreaCode();
        if (Objects.nonNull(loadCode) && Objects.nonNull(param.getLoadAreaLevel())) {
            switch (param.getLoadAreaLevel()) {
                case 1 ->
                        wrapper.likeRight(KwoTransportDemand::getLoadAreaCode, Integer.valueOf(String.valueOf(loadCode).substring(0, 2)));
                case 2 ->
                        wrapper.likeRight(KwoTransportDemand::getLoadAreaCode, Integer.valueOf(String.valueOf(loadCode).substring(0, 4)));
                case 3 -> wrapper.eq(KwoTransportDemand::getLoadAreaCode, loadCode);
            }
        }
        Integer unloadCode = param.getUnloadAreaCode();
        if (Objects.nonNull(unloadCode) && Objects.nonNull(param.getLoadAreaLevel())) {
            switch (param.getUnloadAreaLevel()) {
                case 1 ->
                        wrapper.likeRight(KwoTransportDemand::getUnloadAreaCode, Integer.valueOf(String.valueOf(unloadCode).substring(0, 2)));
                case 2 ->
                        wrapper.likeRight(KwoTransportDemand::getUnloadAreaCode, Integer.valueOf(String.valueOf(unloadCode).substring(0, 4)));
                case 3 -> wrapper.eq(KwoTransportDemand::getUnloadAreaCode, unloadCode);
            }
        }
        return wrapper.orderByDesc(KwoTransportDemand::getCreateTime);
    }

    /**
     * @desc: 运需统计
     * @author: yzc
     * @date: 2023-07-26 10:33
     * @Param param:
     * @return: com.sckw.core.model.vo.TableStatisticRes
     */
    public TableStatisticRes statistic(StatisticTransportDemandParam param) {
        TableStatisticRes res = new TableStatisticRes();

        //新增客户经理权限过滤
        List<Long> authEntIdList = new ArrayList<>();
        if (SystemTypeEnum.MANAGE.getCode() == LoginUserHolder.getSystemType()) {
            authEntIdList = LoginUserHolder.getAuthEntIdList();
            if (CollectionUtils.isEmpty(authEntIdList)) {
                List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                if (CollectionUtils.isEmpty(ids)) {
                    return getDefaultStatistic(res);
                }
                authEntIdList.addAll(ids);
            }
        }
//        else {
//            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
//            if (CollectionUtils.isEmpty(ids)) {
//                return getDefaultStatistic(res);
//            }
//            authEntIdList.addAll(ids);
//        }

        LambdaQueryWrapper<KwoTransportDemand> wrapper = buildWrapper(BeanUtils.copyProperties(param, ExportTransportDemandParam.class), authEntIdList);
        List<KwoTransportDemand> demands = kwoTransportDemandMapper.selectList(wrapper);
        Map<Integer, List<KwoTransportDemand>> map = demands.stream().collect(Collectors.groupingBy(KwoTransportDemand::getStatus));

        List<TableTop> tableTops = new ArrayList<>();
        TableTop all = new TableTop();
        all.setName("全部").setTotal(CollectionUtils.isEmpty(demands) ? 0 : demands.size());
        tableTops.add(all);

        List<TransportDemandStatusEnum> enums = TransportDemandStatusEnum.getSortList();
        enums.forEach(e -> {
            Integer value = e.getCode();
            Integer systemType = LoginUserHolder.getSystemType();
            if (Objects.equals(systemType, SystemTypeEnum.MANAGE.getCode()) && Objects.equals(value, Global.NO)) {
                return;
            }
            List<KwoTransportDemand> list = map.get(value);
            int total = CollectionUtils.isEmpty(list) ? 0 : list.size();
            TableTop tableTop = new TableTop();
            tableTop.setName(e.getMsg()).setValue(value).setTotal(total);
            tableTops.add(tableTop);

        });

        TableBottom tableBottom = new TableBottom();
        tableBottom.setTotal(CollectionUtils.isEmpty(demands) ? 0 : demands.size());
        res.setTableTops(tableTops).setTableBottom(tableBottom);
        return res;
    }

    private TableStatisticRes getDefaultStatistic(TableStatisticRes res) {
        List<TableTop> tableTops = new ArrayList<>();
        TableTop all = new TableTop();
        all.setName("全部").setTotal(0);
        tableTops.add(all);
        List<TransportDemandStatusEnum> enums = TransportDemandStatusEnum.getSortList();
        enums.forEach(e -> {
            Integer value = e.getCode();
            int total = 0;
            TableTop tableTop = new TableTop();
            tableTop.setName(e.getMsg()).setValue(value).setTotal(total);
            tableTops.add(tableTop);
        });
        TableBottom tableBottom = new TableBottom();
        tableBottom.setTotal(0);
        res.setTableTops(tableTops).setTableBottom(tableBottom);
        return res;
    }

    /**
     * @desc: 运需导出
     * @author: yzc
     * @date: 2023-07-26 10:33
     * @Param param:
     * @return: java.util.List<com.sckw.order.model.dto.TransportDemandExport>
     */
    public List<TransportDemandExport> export(ExportTransportDemandParam param) {
        //新增客户经理权限过滤
        List<Long> authEntIdList = new ArrayList<>();
        if (SystemTypeEnum.MANAGE.getCode() == LoginUserHolder.getSystemType()) {

            authEntIdList = LoginUserHolder.getAuthEntIdList();
            if (CollectionUtils.isEmpty(authEntIdList)) {
                List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                if (CollectionUtils.isEmpty(ids)) {
                    return new ArrayList<>();
                }
                authEntIdList.addAll(ids);
            }
        }
//        else {
//            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
//            if (CollectionUtils.isEmpty(ids)) {
//                return new ArrayList<>();
//            }
//            authEntIdList.addAll(ids);
//        }
        LambdaQueryWrapper<KwoTransportDemand> wrapper = buildWrapper(param, authEntIdList);
        List<KwoTransportDemand> demands = kwoTransportDemandMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(demands)) {
            return Collections.emptyList();
        }

        // 获取供应企业信息
        List<Long> supplyEntIds = demands.stream().map(KwoTransportDemand::getEntId).collect(Collectors.toList());
        // 通过企业id查询企业信息
        List<EntCacheResDto> entList = remoteSystemService.queryEntCacheByIds(supplyEntIds);
        Map<Long, String> entMap = entList.stream().collect(Collectors.toMap(EntCacheResDto::getId, EntCacheResDto::getFirmName, (k1, k2) -> k1));

        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.PRODUCT_NAME_TYPE.getType(),
                DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType()));
        Map<String, String> productNameMap, statusMap;
        if (CollectionUtils.isEmpty(dict)) {
            productNameMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
            statusMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        } else {
            productNameMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType());
            statusMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.TRANSPORT_DEMAND_STATUS.getType());
        }
        List<TransportDemandExport> result = Lists.newArrayList();
        demands.forEach(e -> {
            TransportDemandExport export = BeanUtils.copyProperties(e, TransportDemandExport.class);
            String loadAreaName = Objects.nonNull(e.getLoadAreaName()) ? e.getLoadAreaName() : "";
            String loadDetailAddress = Objects.nonNull(e.getLoadDetailAddress()) ? e.getLoadDetailAddress() : "";
            String unloadAreaName = Objects.nonNull(e.getUnloadAreaName()) ? e.getUnloadAreaName() : "";
            String unloadDetailAddress = Objects.nonNull(e.getUnloadDetailAddress()) ? e.getUnloadDetailAddress() : "";
            export.setGoodsTypeLabel(productNameMap.get(e.getGoodsType()))
                    .setStatusLabel(statusMap.get(String.valueOf(e.getStatus())))
                    .setLoadAddress(loadAreaName + loadDetailAddress)
                    .setUnloadAddress(unloadAreaName + unloadDetailAddress)
                    .setDeadline(Objects.isNull(e.getDeadline()) ? null : DateUtils.format(e.getDeadline(), DateUtils.DATE_PATTERN))
                    .setCreateTime(DateUtil.getDateTime(e.getCreateTime()))
                    .setUpdateTime(DateUtil.getDateTime(e.getUpdateTime()))
                    .setEntName(entMap.get(e.getEntId()));
            result.add(export);
        });
        return result;
    }

    /**
     * @desc: 运需上架
     * @author: yzc
     * @date: 2023-07-26 10:34
     * @Param id:
     * @return: void
     */
    public void batchPutOnShelves(List<Long> ids) {
        LambdaQueryWrapper<KwoTransportDemand> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwoTransportDemand::getId, ids)
                .ne(KwoTransportDemand::getStatus, TransportDemandStatusEnum.PUT_ON_SHELVES.getCode())
                .eq(KwoTransportDemand::getEntId, LoginUserHolder.getEntId()).eq(KwoTransportDemand::getDelFlag, Global.NO);
        List<KwoTransportDemand> list = kwoTransportDemandMapper.selectList(wrapper);
        if (!Objects.equals(ids.size(), list.size())) {
            throw new BusinessException("上架操作仅针对“已下架”“草稿”状态的单据！");
        }
        LambdaUpdateWrapper<KwoTransportDemand> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwoTransportDemand::getStatus, TransportDemandStatusEnum.PUT_ON_SHELVES.getCode())
                .in(KwoTransportDemand::getId, ids);
        kwoTransportDemandMapper.update(null, updateWrapper);
    }

    /**
     * @desc: 运需批量下架
     * @author: yzc
     * @date: 2023-07-26 10:34
     * @Param id:
     * @return: void
     */
    public void batchTakeOffShelves(List<Long> ids) {
        LambdaQueryWrapper<KwoTransportDemand> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwoTransportDemand::getId, ids)
                .eq(KwoTransportDemand::getStatus, TransportDemandStatusEnum.PUT_ON_SHELVES.getCode())
                .eq(KwoTransportDemand::getEntId, LoginUserHolder.getEntId()).eq(KwoTransportDemand::getDelFlag, Global.NO);
        List<KwoTransportDemand> list = kwoTransportDemandMapper.selectList(wrapper);
        if (!Objects.equals(ids.size(), list.size())) {
            throw new BusinessException("下架操作仅针对“已上架”状态的单据");
        }
        LambdaUpdateWrapper<KwoTransportDemand> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwoTransportDemand::getStatus, TransportDemandStatusEnum.TAKE_OFF_SHELVES.getCode())
                .in(KwoTransportDemand::getId, ids);
        kwoTransportDemandMapper.update(null, updateWrapper);
    }

    /**
     * @desc: 运需批量删除
     * @author: yzc
     * @date: 2023-07-26 10:34
     * @Param id:
     * @return: void
     */
    public void batchDelete(List<Long> ids) {
        LambdaQueryWrapper<KwoTransportDemand> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwoTransportDemand::getId, ids).in(KwoTransportDemand::getStatus, 0, 2)
                .eq(KwoTransportDemand::getEntId, LoginUserHolder.getEntId()).eq(KwoTransportDemand::getDelFlag, Global.NO);
        List<KwoTransportDemand> list = kwoTransportDemandMapper.selectList(wrapper);
        if (!Objects.equals(ids.size(), list.size())) {
            throw new BusinessException("删除操作仅针对“已下架”“草稿”状态的单据");
        }
        LambdaUpdateWrapper<KwoTransportDemand> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwoTransportDemand::getDelFlag, Global.YES).in(KwoTransportDemand::getId, ids);
        kwoTransportDemandMapper.update(null, updateWrapper);
    }

    /**
     * @desc: 运需广场列表
     * @author: yzc
     * @date: 2023-07-26 10:34
     * @Param param:
     * @return: com.sckw.core.model.page.PageResult
     */
    public PageResult demandSquaresList(TransportDemandSquaresParam param, HttpServletRequest request) {
        Page<KwoTransportDemand> page = new Page<>(param.getPage(), param.getPageSize());
        LambdaQueryWrapper<KwoTransportDemand> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getGoodsType()) && StringUtils.isNotBlank(param.getGoodsTypeValue())) {
            List<SysDictResDto> goodsTypeList = remoteSystemService.queryDictBottom(param.getGoodsType(), param.getGoodsTypeValue());
            if (CollectionUtils.isNotEmpty(goodsTypeList)) {
                List<String> goodsTypes = goodsTypeList.stream().map(SysDictResDto::getValue).toList();
                wrapper.in(KwoTransportDemand::getGoodsType, goodsTypes);
            }
        }
        wrapper.eq(KwoTransportDemand::getStatus, TransportDemandStatusEnum.PUT_ON_SHELVES.getCode())
                .eq(KwoTransportDemand::getDelFlag, Global.NO);
        Integer loadCode = param.getLoadAreaCode();
        if (Objects.nonNull(loadCode) && Objects.nonNull(param.getLoadAreaLevel())) {
            switch (param.getLoadAreaLevel()) {
                case 1 ->
                        wrapper.likeRight(KwoTransportDemand::getLoadAreaCode, Integer.valueOf(String.valueOf(loadCode).substring(0, 2)));
                case 2 ->
                        wrapper.likeRight(KwoTransportDemand::getLoadAreaCode, Integer.valueOf(String.valueOf(loadCode).substring(0, 4)));
                case 3 -> wrapper.eq(KwoTransportDemand::getLoadAreaCode, loadCode);
            }
        }
        Integer unloadCode = param.getUnloadAreaCode();
        if (Objects.nonNull(unloadCode) && Objects.nonNull(param.getUnloadAreaLevel())) {
            switch (param.getUnloadAreaLevel()) {
                case 1 ->
                        wrapper.likeRight(KwoTransportDemand::getUnloadAreaCode, Integer.valueOf(String.valueOf(unloadCode).substring(0, 2)));
                case 2 ->
                        wrapper.likeRight(KwoTransportDemand::getUnloadAreaCode, Integer.valueOf(String.valueOf(unloadCode).substring(0, 4)));
                case 3 -> wrapper.eq(KwoTransportDemand::getUnloadAreaCode, unloadCode);
            }
        }
        if (StringUtils.isNotBlank(param.getKeywords())) {
            List<EntCacheResDto> entList = remoteSystemService.queryEntCacheByName(param.getKeywords());
            List<Long> entIds = entList.stream().map(EntCacheResDto::getId).toList();
            if (CollectionUtils.isNotEmpty(entIds)) {
                wrapper.and(e -> e.in(KwoTransportDemand::getEntId, entIds).or().like(KwoTransportDemand::getName, param.getKeywords()));
            } else {
                wrapper.like(KwoTransportDemand::getName, param.getKeywords());
            }
        }

        //专场逻辑
        String accessSpecial = request.getHeader("Access-Special");
        //是否主平台
        boolean mainPlatform = remoteSystemService.queryMainPlatform(accessSpecial);
        if (!mainPlatform) {
            List<Long> entIds = remoteSystemService.queryEntIdsByCode(accessSpecial, null);
            wrapper.in(KwoTransportDemand::getEntId, entIds);
        }

        wrapper.last("order by RAND()");
        Page<KwoTransportDemand> kwpGoodsPage = kwoTransportDemandMapper.selectPage(page, wrapper);
        List<KwoTransportDemand> list = kwpGoodsPage.getRecords();
        if (CollectionUtils.isEmpty(list)) {
            return PageResult.build(param.getPage(), param.getPageSize(), kwpGoodsPage.getTotal(), Collections.emptyList());
        }
        List<Long> entIds = list.stream().map(KwoTransportDemand::getEntId).toList();
        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntCacheMapByIds(entIds);

        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.PRODUCT_NAME_TYPE.getType(),
                DictTypeEnum.TRADE_TYPE.getType()));
        Map<String, String> productNameMap, tradeMap;
        if (CollectionUtils.isEmpty(dict)) {
            productNameMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
            tradeMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        } else {
            productNameMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType());
            tradeMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    new HashMap<>(Global.NUMERICAL_SIXTEEN) : dict.get(DictTypeEnum.TRADE_TYPE.getType());
        }
        List<TransportDemandSquaresListRes> result = Lists.newArrayList();
        list.forEach(e -> {
            TransportDemandSquaresListRes res = BeanUtils.copyProperties(e, TransportDemandSquaresListRes.class);
            String loadAreaName = Objects.nonNull(e.getLoadAreaName()) ? e.getLoadAreaName() : "";
            String loadDetailAddress = Objects.nonNull(e.getLoadDetailAddress()) ? e.getLoadDetailAddress() : "";
            String unloadAreaName = Objects.nonNull(e.getUnloadAreaName()) ? e.getUnloadAreaName() : "";
            String unloadDetailAddress = Objects.nonNull(e.getUnloadDetailAddress()) ? e.getUnloadDetailAddress() : "";
            EntCacheResDto ent = entMap.get(e.getEntId());
            res.setGoodsTypeLabel(productNameMap.get(e.getGoodsType()))
                    .setTradingLabel(tradeMap.get(e.getTrading()))
                    .setLoadAddress(loadAreaName + loadDetailAddress)
                    .setUnloadAddress(unloadAreaName + unloadDetailAddress)
                    .setCreateTime(DateUtils.format(e.getCreateTime()))
                    .setDemandUnit(Objects.nonNull(ent) ? ent.getFirmName() : null);
            result.add(res);
        });
        return PageResult.build(param.getPage(), param.getPageSize(), kwpGoodsPage.getTotal(), result);
    }

    /**
     * @desc: 查看联系方式
     * @author: yzc
     * @date: 2023-09-12 9:06
     * @Param id:
     * @return: com.sckw.order.model.vo.res.TransportDemandContactInfoRes
     */
    public TransportDemandContactInfoRes getContactInfo(Long id) {
        KwoTransportDemand transportDemand = getById(id, Boolean.FALSE);
        if (Objects.isNull(transportDemand)) {
            throw new BusinessException("数据不存在！");
        }
        TransportDemandContactInfoRes res = new TransportDemandContactInfoRes();
        res.setId(id).setContacts(transportDemand.getContacts()).setPhone(transportDemand.getPhone());
        return res;
    }
}
