package com.sckw.order.serivce;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.PageRes;
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.StringUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.excel.utils.DateUtil;
import com.sckw.order.dao.KwpWantBuyAddressMapper;
import com.sckw.order.dao.KwpWantBuyMapper;
import com.sckw.order.dao.KwpWantBuyTradingMapper;
import com.sckw.order.enums.WantBuyStatusEnum;
import com.sckw.order.model.KwoWantBuy;
import com.sckw.order.model.KwoWantBuyAddress;
import com.sckw.order.model.KwoWantBuyTrading;
import com.sckw.order.model.dto.WantBuyExport;
import com.sckw.order.model.vo.req.*;
import com.sckw.order.model.vo.res.*;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @desc: 求购service
 * @author: yzc
 * @date: 2023-06-25 14:54
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class KwpWantBuyService {
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    private final KwpWantBuyMapper kwpWantBuyMapper;
    private final KwpWantBuyTradingMapper kwpWantBuyTradingMapper;
    private final KwpWantBuyAddressMapper kwpWantBuyAddressMapper;
    private final KwoWantBuyAddressService kwoWantBuyAddressService;
    private final KwoWantBuyTradingService kwoWantBuyTradingService;

    /**
     * @desc: 求购大厅列表查询
     * @author lt
     * @Date 11:50 2023/8/1 0001
     **/
    public PageRes<WantBuyHallRes> buyHallList(WantBuySelectParam wantBuySelectParam) {
        // 如果有求购方式的查询条件，需要先查询出求购方式的id
        if (StringUtils.isNotBlank(wantBuySelectParam.getTrading())) {
            List<String> longList = stringToLongList(wantBuySelectParam.getTrading());
            wantBuySelectParam.setTradings(longList);
        }
        // 商品分类筛选处理
        if (StringUtils.isNotBlank(wantBuySelectParam.getGoodsType()) && StringUtils.isNotBlank(wantBuySelectParam.getGoodsTypeValue())) {
            List<String> goodsTypes = goodsTypeHandle(wantBuySelectParam);
            wantBuySelectParam.setGoodsTypeValueSearch(goodsTypes);
        }
        //区域筛选
        String cityCode = wantBuySelectParam.getCityCode();
        Integer areaLevel = wantBuySelectParam.getAreaLevel();
        if (StringUtils.isNotBlank(cityCode) && Objects.nonNull(areaLevel)) {
            if (Objects.equals(1, areaLevel)) {
                cityCode = cityCode.substring(0, 2);
            } else if (Objects.equals(2, areaLevel)) {
                cityCode = cityCode.substring(0, 4);
            }
            wantBuySelectParam.setCityCode(cityCode);
        }
        //关键字模糊匹配
        if (StringUtils.isNotBlank(wantBuySelectParam.getKeywords())) {
            List<EntCacheResDto> entList = remoteSystemService.queryEntCacheByName(wantBuySelectParam.getKeywords());
            List<Long> entIds = entList.stream().map(EntCacheResDto::getId).toList();
            if (CollectionUtils.isNotEmpty(entIds)) {
                wantBuySelectParam.setEntIds(entIds);
            }
        }
        wantBuySelectParam.setStatus(WantBuyStatusEnum.PUT_ON_SHELVES.getCode());

        // 分页查询求购列表
        PageHelper.startPage(wantBuySelectParam.getPage(), wantBuySelectParam.getPageSize());
        List<WantBuySelectRes> wantBuyDto = kwpWantBuyMapper.queryBuyHallList(wantBuySelectParam);

        if (CollectionUtils.isEmpty(wantBuyDto)) {
            return new PageRes<>();
        }
        List<WantBuyHallRes> res = BeanUtils.copyToList(wantBuyDto, WantBuyHallRes.class);

        // 获取供应企业信息
        List<Long> supplyEntIds = res.stream()
                .map(WantBuyHallRes::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.TRADE_TYPE.getType(),
                DictTypeEnum.PRODUCT_NAME_TYPE.getType(), DictTypeEnum.GOODS_STATUS.getType()));
        Map<String, String> tradeMap, productNameMap, goodsStatusMap;
        if (CollectionUtils.isNotEmpty(dict)) {
            tradeMap = CollectionUtils.isNotEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    dict.get(DictTypeEnum.TRADE_TYPE.getType()) : new HashMap<>();
            productNameMap = CollectionUtils.isNotEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType()) : new HashMap<>();
            goodsStatusMap = CollectionUtils.isNotEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    dict.get(DictTypeEnum.GOODS_STATUS.getType()) : new HashMap<>();
        } else {
            tradeMap = new HashMap<>();
            productNameMap = new HashMap<>();
            goodsStatusMap = new HashMap<>();
        }
        // 对求购列表进行数据处理
        res.forEach(e -> {
            List<String> tradings = e.getWantBuyTradings().stream()
                    .map(f -> tradeMap.get(f.getTrading()))
                    .collect(Collectors.toList());
            e.setTradings(String.join(Global.COMMA, tradings));
            e.setGoodsTypeLabel(productNameMap.get(e.getGoodsType()));
            e.setStatusLabel(goodsStatusMap.get(String.valueOf(e.getStatus())));
            e.setEntName(Objects.nonNull(entMap.get(e.getEntId())) ? entMap.get(e.getEntId()) : null);
        });

        return new PageRes<>(new PageInfo<>(res));
    }

    /**
     * @desc 求购列表查询
     * @author lt
     * @Date 11:50 2023/8/1 0001
     **/
    public PageRes<WantBuySelectRes> select(WantBuySelectParam wantBuySelectParam) {
        if (StringUtils.isNotBlank(wantBuySelectParam.getTrading())) {
            List<String> longList = stringToLongList(wantBuySelectParam.getTrading());
            wantBuySelectParam.setTradings(longList);
        }
        //商品分类筛选处理
        if (StringUtils.isNotBlank(wantBuySelectParam.getGoodsType()) && StringUtils.isNotBlank(wantBuySelectParam.getGoodsTypeValue())) {
            List<String> goodsTypes = goodsTypeHandle(wantBuySelectParam);
            wantBuySelectParam.setGoodsTypeValueSearch(goodsTypes);
        }
        wantBuySelectParam.setEntId(!Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? LoginUserHolder.getEntId() : null);
        wantBuySelectParam.setSystemType(LoginUserHolder.getSystemType());

        PageHelper.startPage(wantBuySelectParam.getPage(), wantBuySelectParam.getPageSize());
        List<WantBuySelectRes> wantBuyDto = kwpWantBuyMapper.pageSelect(wantBuySelectParam);
        if (CollectionUtils.isEmpty(wantBuyDto)) {
            return new PageRes<>();
        }
        // 获取供应企业信息
        List<Long> supplyEntIds = wantBuyDto.stream()
                .map(WantBuySelectRes::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.TRADE_TYPE.getType(),
                DictTypeEnum.PRODUCT_NAME_TYPE.getType(), DictTypeEnum.WANT_BUY_STATUS.getType()));
        Map<String, String> tradeMap, productNameMap, statusMap;
        if (CollectionUtils.isEmpty(dict)) {
            tradeMap = new HashMap<>();
            productNameMap = new HashMap<>();
            statusMap = new HashMap<>();
        } else {
            tradeMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.TRADE_TYPE.getType());
            productNameMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType());
            statusMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.WANT_BUY_STATUS.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.WANT_BUY_STATUS.getType());
        }
        //把查询出来的集合wantBuyTradings里面对的tranding 转成字符串放在String里面
        wantBuyDto.forEach(wantBuySelectRes -> {
            List<String> tradings = wantBuySelectRes.getWantBuyTradings().stream()
                    .map(wantBuyTradingRes -> tradeMap.get(wantBuyTradingRes.getTrading()))
                    .collect(Collectors.toList());
            wantBuySelectRes.setTradings(String.join(Global.COMMA, tradings));
            wantBuySelectRes.setGoodsTypeLabel(productNameMap.get(wantBuySelectRes.getGoodsType()));
            wantBuySelectRes.setStatusLabel(statusMap.get(String.valueOf(wantBuySelectRes.getStatus())));
            wantBuySelectRes.setEntName(Objects.nonNull(entMap.get(wantBuySelectRes.getEntId())) ? entMap.get(wantBuySelectRes.getEntId()) : null);
        });

        return new PageRes<>(new PageInfo<>(wantBuyDto));
    }

    /**
     * @param wantBuySelectParam
     * @return
     * @Desc 求购列表查询
     */
    private List<String> goodsTypeHandle(WantBuySelectParam wantBuySelectParam) {
        List<SysDictResDto> goodsTypeList = remoteSystemService.queryDictBottom(wantBuySelectParam.getGoodsType(), wantBuySelectParam.getGoodsTypeValue());
        if (CollectionUtils.isNotEmpty(goodsTypeList)) {
            return goodsTypeList.stream().map(SysDictResDto::getValue).toList();
        }
        return null;
    }

    /**
     * @return
     * @Desc 字符串转数组
     */
    private List<String> stringToLongList(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
// 使用逗号分隔字符串，并去除两端空格
        String[] stringArray = str.split(Global.COMMA);
        return Arrays.asList(stringArray);
    }

    /**
     * @Desc 求购草稿新增
     * @Author lt
     * @Param
     * @Return
     * @Date 11:56 2023/7/25 0025
     **/
    @Transactional(rollbackFor = Exception.class)
    public void addDraft(AddDraftWantBuyParam param) {
        addWantBuy(BeanUtils.copyProperties(param, AddWantBuyParam.class), WantBuyStatusEnum.SAVED.getCode());
    }

    /**
     * @Desc 求购上架新增
     * @Author lt
     * @Param
     * @Return
     * @Date 11:57 2023/7/25 0025
     **/
    @Transactional(rollbackFor = Exception.class)
    public void addShelves(AddWantBuyParam param) {
        addWantBuy(param, WantBuyStatusEnum.PUT_ON_SHELVES.getCode());
    }

    /**
     * @desc 新增求购统一方法
     * @author lt
     * @Date 11:52 2023/8/1 0001
     **/
    public void addWantBuy(AddWantBuyParam param, Integer status) {
        //添加求购
        KwoWantBuy kwoWantBuy = BeanUtils.copyProperties(param, KwoWantBuy.class);
        kwoWantBuy.setEntId(LoginUserHolder.getEntId()).setStatus(status);
        kwpWantBuyMapper.insert(kwoWantBuy);
        //添加支付方式
        List<String> list = param.getTradings();
        if (CollectionUtils.isNotEmpty(list)) {
            Long wantBuyId = kwoWantBuy.getId();
            List<KwoWantBuyTrading> tradingList = list.stream()
                    .map(item -> {
                        KwoWantBuyTrading kwoWantBuyTrading = new KwoWantBuyTrading();
                        kwoWantBuyTrading.setWantBuyId(wantBuyId);
                        kwoWantBuyTrading.setTrading(item);
                        return kwoWantBuyTrading;
                    })
                    .collect(Collectors.toList());
            kwoWantBuyTradingService.insertBatch(tradingList);
        }
        //地址信息添加,如果存在地址信息-新增入库
        WantBuyAddressParam addressInfo = param.getAddressInfo();
        if (Objects.nonNull(addressInfo)) {
            KwoWantBuyAddress address = BeanUtils.copyProperties(addressInfo, KwoWantBuyAddress.class);
            address.setWantBuyId(kwoWantBuy.getId());
            kwpWantBuyAddressMapper.insert(address);
        }
    }

    /**
     * @Desc: 求购上架
     * @Author: lt
     * @Date: 13:38 2023/7/25 0025
     **/
    public void batchPutOnShelves(List<Long> ids) {
        LambdaQueryWrapper<KwoWantBuy> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwoWantBuy::getId, ids).ne(KwoWantBuy::getStatus, WantBuyStatusEnum.PUT_ON_SHELVES.getCode())
                .eq(KwoWantBuy::getEntId, LoginUserHolder.getEntId()).eq(KwoWantBuy::getDelFlag, Global.NO);
        List<KwoWantBuy> list = kwpWantBuyMapper.selectList(wrapper);
        if (!Objects.equals(ids.size(), list.size())) {
            throw new BusinessException("上架操作仅针对“已下架”“草稿”状态的单据！");
        }
        LambdaUpdateWrapper<KwoWantBuy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwoWantBuy::getStatus, WantBuyStatusEnum.PUT_ON_SHELVES.getCode())
                .in(KwoWantBuy::getId, ids);
        kwpWantBuyMapper.update(null, updateWrapper);
    }

    /**
     * @desc 求购批量下架
     * @author lt
     * @Date 14:56 2023/7/25 0025
     **/
    public void batchTakeOffShelves(WantBuyDels param) {
        List<Long> ids = StringUtils.splitStrToList(param.getIds(), Long.class);
        LambdaQueryWrapper<KwoWantBuy> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwoWantBuy::getId, ids).eq(KwoWantBuy::getStatus, WantBuyStatusEnum.PUT_ON_SHELVES.getCode())
                .eq(KwoWantBuy::getEntId, LoginUserHolder.getEntId()).eq(KwoWantBuy::getDelFlag, Global.NO);
        List<KwoWantBuy> list = kwpWantBuyMapper.selectList(wrapper);
        if (!Objects.equals(ids.size(), list.size())) {
            throw new BusinessException("下架操作仅针对“已上架”状态的单据");
        }
        LambdaUpdateWrapper<KwoWantBuy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwoWantBuy::getStatus, WantBuyStatusEnum.TAKE_OFF_SHELVES.getCode()).in(KwoWantBuy::getId, ids);
        kwpWantBuyMapper.update(null, updateWrapper);
    }

    /**
     * @desc 求购删除
     * @author lt
     * @Date 10:15 2023/8/1 0001
     **/
    @Transactional(rollbackFor = Exception.class)
    public void dels(WantBuyDels param) {
        List<Long> ids = StringUtils.splitStrToList(param.getIds(), Long.class);
        LambdaQueryWrapper<KwoWantBuy> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(KwoWantBuy::getId, ids).ne(KwoWantBuy::getStatus, 1)
                .eq(KwoWantBuy::getEntId, LoginUserHolder.getEntId()).eq(KwoWantBuy::getDelFlag, Global.NO);
        List<KwoWantBuy> list = kwpWantBuyMapper.selectList(wrapper);
        if (!Objects.equals(ids.size(), list.size())) {
            throw new BusinessException("删除操作仅针对“已下架”“草稿”状态的单据");
        }
        LambdaUpdateWrapper<KwoWantBuy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwoWantBuy::getDelFlag, Global.YES).in(KwoWantBuy::getId, ids);
        kwpWantBuyMapper.update(null, updateWrapper);
        //删除地址信息
        kwoWantBuyAddressService.delAddressByWantBuyIds(ids);
        //删除支付方式
        kwoWantBuyTradingService.delTradingByWantBuyids(ids);

    }

    /**
     * @desc 求购详情查询
     * @author lt
     * @Date 10:15 2023/8/1 0001
     **/
    public WantBuyDetailRes detail(Long id) {
        //先判断求购订单是否存在
        KwoWantBuy kwoWantBuy = kwpWantBuyMapper.selectById(id);
        if (Objects.isNull(kwoWantBuy)) {
            throw new BusinessException("求购信息不存在");
        }
        WantBuyDetailRes responseData = BeanUtils.copyProperties(kwoWantBuy, WantBuyDetailRes.class);
        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.PRODUCT_NAME_TYPE.getType(),
                DictTypeEnum.WANT_BUY_STATUS.getType(), DictTypeEnum.TORDER_ADDRESS_TYPE.getType(), DictTypeEnum.TRADE_TYPE.getType()));
        Map<String, String> productNameMap, wantBuyStatusMap, orderAddressMap, tradeMap;
        if (CollectionUtils.isEmpty(dict)) {
            productNameMap = new HashMap<>();
            wantBuyStatusMap = new HashMap<>();
            orderAddressMap = new HashMap<>();
            tradeMap = new HashMap<>();
        } else {
            productNameMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType());
            wantBuyStatusMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.WANT_BUY_STATUS.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.WANT_BUY_STATUS.getType());
            orderAddressMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TORDER_ADDRESS_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.TORDER_ADDRESS_TYPE.getType());
            tradeMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.TRADE_TYPE.getType());
        }
        List<SysDictResDto> types = remoteSystemService.queryDictFrontAll(DictTypeEnum.PRODUCT_NAME_TYPE.getType(), responseData.getGoodsType());
        if (CollectionUtils.isNotEmpty(types)) {
            responseData.setGoodsTypes(types.stream().map(SysDictResDto::getValue).toList())
                    .setGoodsTypeLabels(String.join(Global.RIGHT_SLASH, types.stream().map(SysDictResDto::getLabel).toList()));
        }
        responseData.setGoodsTypeLabel(productNameMap.get(responseData.getGoodsType()))
                .setStatusLabel(wantBuyStatusMap.get(String.valueOf(responseData.getStatus())));
        //求购地址信息
        KwoWantBuyAddress address = kwpWantBuyAddressMapper.selectOne(new LambdaQueryWrapper<KwoWantBuyAddress>()
                .eq(KwoWantBuyAddress::getWantBuyId, id).eq(KwoWantBuyAddress::getDelFlag, Global.NO).last("LIMIT 1"));
        if (Objects.nonNull(address)) {
            WantBuyAddressDetailRes wantBuyAddressInfo = BeanUtils.copyProperties(address, WantBuyAddressDetailRes.class);
            wantBuyAddressInfo.setTypeLabel(orderAddressMap.get(wantBuyAddressInfo.getType()));
            responseData.setAddressInfo(wantBuyAddressInfo);
        }
        //获取求购企业信息
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(kwoWantBuy.getEntId());
        if (Objects.nonNull(entCacheResDto)) {
            responseData.setEntName(entCacheResDto.getFirmName());
        }
        //求购支付方式集合
        List<KwoWantBuyTrading> tradingList = kwoWantBuyTradingService.getByWantBuyId(id);
        if (CollectionUtils.isNotEmpty(tradingList)) {
            List<String> tradings = tradingList.stream().map(KwoWantBuyTrading::getTrading).collect(Collectors.toList());
            responseData.setTradings(tradings);
            //改成stream流的方式
            List<String> result = tradings.stream()
                    .map(tradeMap::get)
                    .collect(Collectors.toList());
            String tradingLabels = String.join(Global.COMMA, result);
            //获取到的是一个集合,需要转换成字符串
            responseData.setTradingLabels(tradingLabels);
        }
        return responseData;
    }

    /**
     * @desc: 更新求购信息
     * @author lt
     * @Date 15:20 2023/7/26 0026
     **/
    public void update(UpdateWantBuyParam param) {
        Long id = param.getId();
        KwoWantBuy kwoWantBuy = selectOneById(id);
        if (Objects.isNull(kwoWantBuy)) {
            throw new BusinessException("求购信息不存在");
        }
        //1.更新求购信息
        LambdaUpdateWrapper<KwoWantBuy> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(KwoWantBuy::getName, param.getName())
                .set(KwoWantBuy::getGoodsType, param.getGoodsType())
                .set(KwoWantBuy::getSpec, param.getSpec())
                .set(KwoWantBuy::getPrice, param.getPrice())
                .set(KwoWantBuy::getAmount, param.getAmount())
                .set(KwoWantBuy::getContacts, param.getContacts())
                .set(KwoWantBuy::getPhone, param.getPhone())
                .set(KwoWantBuy::getRemark, param.getRemark())
                .eq(KwoWantBuy::getId, param.getId());
        kwpWantBuyMapper.update(null, wrapper);
        //2.更新求购地址信息
        kwoWantBuyAddressService.delAddressByWantBuyIds(List.of(id));
        if (Objects.nonNull(param.getAddressInfo())) {
            KwoWantBuyAddress kwoWantBuyAddress = BeanUtils.copyProperties(param.getAddressInfo(), KwoWantBuyAddress.class);
            kwoWantBuyAddress.setWantBuyId(id);
            kwpWantBuyAddressMapper.insert(kwoWantBuyAddress);

        }
        //3.更新求购支付方式
        kwoWantBuyTradingService.deleteByWantBuyid(id);
        List<String> tradings = param.getTradings();
        if (CollectionUtils.isNotEmpty(tradings)) {
            List<KwoWantBuyTrading> list = new ArrayList<>(param.getTradings().size());
            for (String trading : tradings) {
                KwoWantBuyTrading kwoWantBuyTrading = new KwoWantBuyTrading();
                kwoWantBuyTrading.setWantBuyId(id);
                kwoWantBuyTrading.setTrading(trading);
                list.add(kwoWantBuyTrading);
            }
            kwpWantBuyTradingMapper.insertBatch(list);
        }
    }

    private void checkParams(UpdateWantBuyParam 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 (Objects.isNull(param.getPhone())) {
            throw new BusinessException("联系电话不能为空！");
        }
    }

    /**
     * @param id
     * @return
     * @Desc: 根据id查询求购信息
     */
    public KwoWantBuy selectOneById(Long id) {
        LambdaQueryWrapper<KwoWantBuy> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KwoWantBuy::getId, id).eq(KwoWantBuy::getDelFlag, Global.NO).last("LIMIT 1");
        return kwpWantBuyMapper.selectOne(queryWrapper);
    }

    /**
     * @param
     * @return
     * @Desc: 查询求购角标统计数量
     */
    public TableStatisticRes statistic(WantBuySelectParam params) {
        TableStatisticRes res = new TableStatisticRes();
        if (StringUtils.isNotBlank(params.getTrading())) {
            List<String> longList = stringToLongList(params.getTrading());
            params.setTradings(longList);
        }
        params.setStatus(null);
        //商品分类筛选处理
        if (StringUtils.isNotBlank(params.getGoodsType()) && StringUtils.isNotBlank(params.getGoodsTypeValue())) {
            List<String> goodsTypes = goodsTypeHandle(params);
            params.setGoodsTypeValueSearch(goodsTypes);
        }
        params.setEntId(!Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? LoginUserHolder.getEntId() : null);
        params.setSystemType(LoginUserHolder.getSystemType());

        List<WantBuySelectRes> result = kwpWantBuyMapper.pageSelect(params);
        Map<Integer, List<WantBuySelectRes>> map = result.stream().collect(Collectors.groupingBy(WantBuySelectRes::getStatus));
        List<TableTop> tableTops = new ArrayList<>();
        TableTop all = new TableTop();
        all.setName("全部").setTotal(CollectionUtils.isEmpty(result) ? 0 : result.size());
        tableTops.add(all);
        List<WantBuyStatusEnum> enums = WantBuyStatusEnum.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<WantBuySelectRes> 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(result) ? 0 : result.size());
        res.setTableTops(tableTops).setTableBottom(tableBottom);
        return res;
    }

    public List<WantBuyExport> export(WantBuySelectParam param) {
        WantBuySelectParam selectParam = new WantBuySelectParam();
        if (StringUtils.isNotBlank(param.getIds())) {
            List<Long> ids = StringUtils.splitStrToList(param.getIds(), Long.class);
            selectParam.setWantBuyIds(ids);
        } else {
            BeanUtils.copyProperties(param, selectParam);
            if (StringUtils.isNotBlank(selectParam.getTrading())) {
                List<String> longList = stringToLongList(selectParam.getTrading());
                selectParam.setTradings(longList);
            }
            //商品分类筛选处理
            if (StringUtils.isNotBlank(selectParam.getGoodsType()) && StringUtils.isNotBlank(selectParam.getGoodsTypeValue())) {
                List<String> goodsTypes = goodsTypeHandle(selectParam);
                selectParam.setGoodsTypeValueSearch(goodsTypes);
            }
        }
        selectParam.setEntId(!Objects.equals(LoginUserHolder.getSystemType(), SystemTypeEnum.MANAGE.getCode()) ? LoginUserHolder.getEntId() : null);
        selectParam.setSystemType(LoginUserHolder.getSystemType());

        List<WantBuySelectRes> wantBuyDto = kwpWantBuyMapper.pageSelect(selectParam);
        if (CollectionUtils.isEmpty(wantBuyDto)) {
            return Collections.emptyList();
        }
        // 获取供应企业信息
        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntCacheMapByIds(
                wantBuyDto.stream().map(WantBuySelectRes::getEntId).collect(Collectors.toList()));
        // 字典信息
        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.TRADE_TYPE.getType(),
                DictTypeEnum.PRODUCT_NAME_TYPE.getType(), DictTypeEnum.WANT_BUY_STATUS.getType()));
        Map<String, String> tradeMap, productNameMap, statusMap;
        if (CollectionUtils.isEmpty(dict)) {
            tradeMap = new HashMap<>();
            productNameMap = new HashMap<>();
            statusMap = new HashMap<>();
        } else {
            tradeMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.TRADE_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.TRADE_TYPE.getType());
            productNameMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.PRODUCT_NAME_TYPE.getType());
            statusMap = CollectionUtils.isEmpty(dict.get(DictTypeEnum.WANT_BUY_STATUS.getType())) ?
                    new HashMap<>() : dict.get(DictTypeEnum.WANT_BUY_STATUS.getType());
        }
        List<WantBuyExport> result = new ArrayList<>();
        wantBuyDto.forEach(e -> {
            WantBuyExport export = BeanUtils.copyProperties(e, WantBuyExport.class);
            List<String> tradings = e.getWantBuyTradings().stream()
                    .map(wantBuyTradingRes -> tradeMap.get(wantBuyTradingRes.getTrading()))
                    .collect(Collectors.toList());
            export.setStatusLabel(statusMap.get(String.valueOf(e.getStatus())))
                    .setEntName(Objects.nonNull(entMap.get(e.getEntId())) ? entMap.get(e.getEntId()).getFirmName() : null)
                    .setTradings(String.join(Global.COMMA, tradings))
                    .setGoodsTypeLabel(productNameMap.get(e.getGoodsType()))
                    .setCreateTime(Objects.isNull(e.getCreateTime()) ? null : DateUtil.getDateTime(e.getCreateTime()))
                    .setUpdateTime(Objects.isNull(e.getUpdateTime()) ? null : DateUtil.getDateTime(e.getUpdateTime()));
            result.add(export);
        });
        return result;
    }

    /**
     * @desc: 查看联系方式
     * @author: yzc
     * @date: 2023-09-12 9:24
     * @Param id:
     * @return: com.sckw.order.model.vo.res.WantBuyContactInfoRes
     */
    public WantBuyContactInfoRes getContactInfo(Long id) {
        LambdaQueryWrapper<KwoWantBuy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwoWantBuy::getId, id)
                .eq(KwoWantBuy::getDelFlag, Global.NO)
                .last("LIMIT 1");
        KwoWantBuy wantBuy = kwpWantBuyMapper.selectOne(wrapper);
        if (Objects.isNull(wantBuy)) {
            throw new BusinessException("求购信息不存在");
        }
        WantBuyContactInfoRes res = new WantBuyContactInfoRes();
        res.setId(id).setContacts(wantBuy.getContacts()).setPhone(wantBuy.getPhone());
        return res;
    }
}
