package com.pj.tb_orders;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.client.admin.AdminInterface;
import com.pj.api.client.async_server.AsyncServerInterface;
import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.client.payment_server.PaymentServerInterface;
import com.pj.api.dto.*;
import com.pj.common.core.text.Convert;
import com.pj.common.core.utils.StringUtils;
import com.pj.current.config.SystemObject;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.enummj.DataType;
import com.pj.enummj.DeleteStatus;
import com.pj.enummj.OrderStatus;
import com.pj.tb_company.TbCompany;
import com.pj.tb_company.TbCompanyService;
import com.pj.tb_demand_quotation.TbDemandQuotation;
import com.pj.tb_demand_quotation.TbDemandQuotationService;
import com.pj.tb_fee_item.TbFeeItem;
import com.pj.tb_fee_item.TbFeeItemService;
import com.pj.tb_fee_item_record.TbFeeItemRecord;
import com.pj.tb_fee_item_record.TbFeeItemRecordService;
import com.pj.tb_goods_demand.TbGoodsDemand;
import com.pj.tb_goods_demand.TbGoodsDemandService;
import com.pj.tb_goods_demand.vo.GoodsDemandVo;
import com.pj.tb_item_rules.TbItemRules;
import com.pj.tb_item_rules.TbItemRulesService;
import com.pj.tb_orders.vo.OrderFeeItemVO;
import com.pj.tb_item_rules.TbItemRulesVo;
import com.pj.tb_orders.vo.OrderStaticsDTO;
import com.pj.tb_orders.vo.TbOrdersEmailVo;
import com.pj.tb_orders.vo.TbOrdersPrintVo;
import com.pj.tb_orders_cart.TbOrdersCart;
import com.pj.tb_orders_cart.TbOrdersCartMapper;
import com.pj.tb_purchaser.TbPurchaser;
import com.pj.tb_purchaser.TbPurchaserMapper;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.so.SoMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * Service: tb_orders -- 订单表
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class TbOrdersService extends ServiceImpl<TbOrdersMapper, TbOrders> implements IService<TbOrders> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbOrdersMapper tbOrdersMapper;
    @Autowired
    private TbPurchaserMapper tbPurchaserMapper;
    @Autowired
    private LevelOneServerInterface levelOneServerInterface;
    @Autowired
    private TbGoodsDemandService goodsDemandService;
    @Autowired
    private TbDemandQuotationService demandQuotationService;
    @Autowired
    private AsyncServerInterface asyncServerInterface;
    @Autowired
    TbOrdersCartMapper tbOrdersCartMapper;

    @Autowired
    private TbCompanyService companyService;
    @Autowired
    private TbFeeItemService tbFeeItemService;
    @Autowired
    private TbItemRulesService tbItemRulesService;

    @Autowired
    TbFeeItemRecordService tbFeeItemRecordService;
    @Autowired
    private PaymentServerInterface paymentServerInterface;

    /**
     * 远程调用
     */
    @Autowired
    private AdminInterface adminInterface;

    /**
     * 增
     */
    void add(TbOrders t) {
        save(t);
    }

    /**
     * 删
     */
    void delete(Long id) {
        removeById(id);
    }

    /**
     * 改
     */
    void update(TbOrders t) {
        updateById(t);

    }

    private PaymentTwoDto getPaymentData(TbOrders t, OrderDto orderOne) {
        TradeSettlementDto htTradeSettlement = levelOneServerInterface.getHtTradeSettlementById(orderOne.getSaleMainId());
        PaymentTwoDto paymentTwoDto = new PaymentTwoDto();
        BeanUtils.copyProperties(htTradeSettlement, paymentTwoDto);

        //二级市场订单号
        paymentTwoDto.setOrderNo(t.getOrderNo());
        //转售金额
        paymentTwoDto.setResalePrice(BigDecimal.valueOf(t.getResalePrice()));
        //商品信息
        paymentTwoDto.setBuyQty(orderOne.getBuyQty());
        paymentTwoDto.setGrossWt(orderOne.getGrossWt());
        paymentTwoDto.setNetWt(orderOne.getNetWt());
        paymentTwoDto.setGoodsName(orderOne.getGoodsNames());
        paymentTwoDto.setGoodsUnit(orderOne.getGoodsUnit());
        paymentTwoDto.setDeclPrice(orderOne.getDeclPrice());
        paymentTwoDto.setCodeTs(orderOne.getCodeTs());

        PeopleDto tbPeople = levelOneServerInterface.getRpcById(orderOne.getBuyUserId());
        StaticLog.info("边民tbPeople:{}", JSONUtil.toJsonStr(tbPeople));
        if (tbPeople != null) {
            paymentTwoDto.setBankCode(tbPeople.getBankCode());
            paymentTwoDto.setBankName(tbPeople.getBankName());
            paymentTwoDto.setBankNo(tbPeople.getBankNo());
            paymentTwoDto.setBorderName(tbPeople.getName());
            paymentTwoDto.setBorderidno(tbPeople.getIdCard());
            paymentTwoDto.setBorderTel(tbPeople.getPhone());
            paymentTwoDto.setPapersType(tbPeople.getPapersType());
            paymentTwoDto.setBorderNationality(tbPeople.getNationality());
        }

        TbPurchaser purchaser = tbPurchaserMapper.selectById(t.getPurchaserId());
        StaticLog.info("采购商purchaser:{}", JSONUtil.toJsonStr(purchaser));
        if (purchaser != null) {
            paymentTwoDto.setPcName(purchaser.getBusinessName());
            if (purchaser.getType() == 2) {
                paymentTwoDto.setPcName(purchaser.getName());
            }
            paymentTwoDto.setDutyParagraph(purchaser.getDutyParagraph());
            paymentTwoDto.setPcBankAccount(purchaser.getBankAccount());
            paymentTwoDto.setPcBankNo(purchaser.getBankNo());
            paymentTwoDto.setPcContact(purchaser.getContact());
            paymentTwoDto.setPcIdCard(purchaser.getIdCard());
            paymentTwoDto.setPcType(purchaser.getType());
        }

        return paymentTwoDto;
    }

    /**
     * 改 收购商购买
     */
    boolean purchaserBuy(String idStr, Long purchaserId) {
        // 获取收购商ID与名称
        TbPurchaser purchaser = tbPurchaserMapper.selectById(purchaserId);
        if (null == purchaser) throw new RuntimeException("当前收购商账号异常，请重新登录或联系管理员！");
        log.info("收购商采购：{}，{}", purchaser.getName(), idStr);

        Long[] idArr = Convert.toLongArray(idStr);
        for (Long id : idArr) {
            TbOrders orderTwo = this.getById(id);
            if (orderTwo == null) {
                log.error(id + "订单不存在");
                throw new AjaxError("订单不存在！");
            }
            if (StrUtil.isNotEmpty(orderTwo.getPurchaserName())) {
                throw new AjaxError(orderTwo.getOrderNo() + "订单已被购买！");
            }
            orderTwo.setPurchaserId(purchaser.getId());
            orderTwo.setPurchaserName(purchaser.getName());
            orderTwo.setIsPay(0);//支付中

            orderTwo.setOrderTime(new Date());//支付时间
            boolean b = updateById(orderTwo);
            if (!b) throw new RuntimeException("购买异常，请重新登录或联系管理员！");

            //修改对应的一级市场订单状态：BeingOrder值为已被下单
            boolean updateResult = levelOneServerInterface.updateBeingOrder(orderTwo.getLevelOneOrderId());
            if (!updateResult) throw new AjaxError(orderTwo.getOrderNo() + "下单异常");

            OrderDto orderOne = levelOneServerInterface.getOrderDtoById(orderTwo.getLevelOneOrderId());

            //todo 接收国内采购商的货款支付申请，划扣至边民账户并给出回执 并且同步至航通
            PaymentTwoDto paymentTwoDto = this.getPaymentData(orderTwo, orderOne);
            paymentServerInterface.sendMKT006_NoCommission(paymentTwoDto);

            //给每个购买他商品的边民发一条支付成功消息，通知边民发起缴税申请以及缴费申请
           /* MessageDto dto = new MessageDto();
            dto.setUrl("/pages/market/two/leader/order");
            dto.setUserId(t.getLeaderId());
            dto.setContents("你转售的《" + t.getGoodsName() + "》收购商已付款。请及时发起缴税申请以及缴费申请。");
            adminInterface.messageSave(dto);*/
        }
        // 清空购物车
        LambdaQueryWrapper<TbOrdersCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TbOrdersCart::getOrderId, Arrays.asList(idArr));
        int del = tbOrdersCartMapper.delete(wrapper);
        return true;
    }

    /**
     * 收到采购商支付扣款回执：成功——> 边民缴税以及各服务费
     *
     * @param orderNo 二级市场边民订单-订单编号
     */
    boolean payTax(String orderNo, Integer MKT008Status) {
        LambdaQueryWrapper<TbOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbOrders::getOrderNo, orderNo);
        List<TbOrders> list = this.list(queryWrapper);
        if (list.size() <= 0) new RuntimeException("收到采购商支付扣款回执:二级市场订单不存在");
        TbOrders orderTwo = list.get(0);

        OrderDto orderOne = levelOneServerInterface.getOrderDtoById(orderTwo.getLevelOneOrderId());
        if (null == orderOne) new RuntimeException("收到采购商支付扣款回执:一级市场订单不存在");

        if (2 == MKT008Status) {//支付失败
            //todo 订单状态更新
            orderTwo.setIsPay(2);
            orderTwo.setPayTime(new Date());
        } else if (1 == MKT008Status) {//支付成功
            //todo 1、订单状态更新
            orderTwo.setIsPay(1);
            orderTwo.setPayTime(new Date());
            orderTwo.setOrderFinish(1);//支付成功订单完成
            //orderTwo.setPayTax(3);//缴费中
            //orderTwo.setPayTaxTime(new Date());//缴费时间
            //todo 2、同步订单信息，发送航通
            /*OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orderTwo, ordersDto);
            asyncServerInterface.sendLevelTwoOrdersDto(ordersDto, DataType.DATA_TYPE_FOUR.getCode());*/

            //todo 3、系统将服务费自动分账，将分账信息自动发送至银行进行划扣
            /*List<TbItemRules> ruleList = new ArrayList<>();
            List<TbFeeItem> feeItemList = tbFeeItemService.getFeeItems();
            feeItemList.forEach(feeItem -> {
                ruleList.addAll(tbItemRulesService.getList(new SoMap().set("itemId", feeItem.getId())));
            });
            //目前逻辑为一个边民订单只有一个商品
            GoodsDto goods = levelOneServerInterface.getByGoodsId(orderOne.getGoodsId());
            //找出所有含有该商品的费项规则
            List<TbItemRules> newRuleList = ruleList.stream().filter(rule -> rule.getGoodsCodes().contains(goods.getCode())).collect(Collectors.toList());
            List<CompanyDto> companyDtoList = new ArrayList<>();
            for (TbItemRules ruleItem : newRuleList) {
                BigDecimal chargesPrice = BigDecimal.ZERO;
                BigDecimal TotalPrice = new BigDecimal(orderOne.getTotalPrice());
                BigDecimal Percent = new BigDecimal(ruleItem.getPercent());
                //类型(1=按交易额收取,2=按次收取,3=按吨)
                if ("1".equals(ruleItem.getFeeType())) {
                    chargesPrice = TotalPrice.multiply(Percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);//保留两位小数，四舍五入
                } else if ("2".equals(ruleItem.getFeeType())) {
                    chargesPrice = ruleItem.getFeeMoney();
                } else if ("3".equals(ruleItem.getFeeType())) {
                    chargesPrice = TotalPrice.multiply(Percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);//保留两位小数，四舍五入
                }
                CompanyDto companyDto = new CompanyDto();
                List<TbFeeItem> feeItems = feeItemList.stream().filter(feeItem -> feeItem.getId().equals(ruleItem.getItemId())).collect(Collectors.toList());
                if (feeItems.size() > 0) {
                    TbCompany company = companyService.getById(feeItems.get(0).getCompanyId());
                    BeanUtils.copyProperties(company, companyDto);
                    companyDto.setChargesPrice(chargesPrice);
                }
                companyDtoList.add(companyDto);
            }

            PaymentTwoDto paymentTwoDto = this.getPaymentData(orderTwo, orderOne);
            paymentTwoDto.setCompanyDtoList(companyDtoList);
            paymentServerInterface.sendMKT006(paymentTwoDto);*/
        }

        return updateById(orderTwo);
    }

    /**
     * 收到边民缴税以及各服务费回执
     *
     * @param orderNo 二级市场边民订单-订单编号
     */
    boolean payTaxFromBank(String orderNo, Integer MKT008Status) {
        LambdaQueryWrapper<TbOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbOrders::getOrderNo, orderNo);
        List<TbOrders> list = this.list(queryWrapper);
        if (list.size() <= 0) new RuntimeException("收到边民缴税以及各服务费回执:二级市场订单不存在");
        TbOrders orderTwo = list.get(0);

        if (2 == MKT008Status) {//缴费失败
            //todo 订单状态更新
            orderTwo.setPayTax(2);
            orderTwo.setPayTaxTime(new Date());
        } else if (1 == MKT008Status) {//缴费成功
            //todo 订单状态更新
            orderTwo.setPayTax(1);
            orderTwo.setPayTaxTime(new Date());
            orderTwo.setOrderFinish(1);//缴费成功订单完成

            //保存缴费记录
            List<TbFeeItem> feeItems = tbFeeItemService.getFeeItems();
            feeItems.stream().forEach(e -> {
                TbFeeItemRecord record = new TbFeeItemRecord();
                record.setItemId(e.getId());
                record.setCompanyName(e.getCompanyName());
                record.setItemName(e.getName());
                record.setOrderNo(orderTwo.getOrderNo());
                record.setLevelTwoOrderId(orderTwo.getId());
                record.setPayTime(new Date());
                record.setCreateTime(new Date());
                record.setPayStatus("1");
                record.setPayRemark("缴纳:" + e.getName());
                tbFeeItemRecordService.save(record);
            });
            //todo:给收购商发送边民缴费成功消息
            MessageDto dto = new MessageDto();
            dto.setUrl("/pages/market/two/purchaser/order/list");
            dto.setUserId(orderTwo.getPurchaserId());
            dto.setContents("你购买的《" + orderTwo.getGoodsName() + "》边民已缴清税以及各服务费。");
            adminInterface.messageSave(dto);
        }

        return updateById(orderTwo);
    }

    List<TbOrders> getDetailById(SoMap so) {
        String idStr = so.getString("ids");
        if (StringUtils.isEmpty(idStr)) throw new RuntimeException("当前订单操作异常，请重新登录或联系管理员！");

        List<TbOrders> list = new ArrayList<>();

        String[] idArr = idStr.split(",");
        for (String id : idArr) {
            TbOrders orders = getById(id);
            list.add(orders);
        }
        return list;
    }

    /**
     * 查
     */
    TbOrders getById(Long id) {
        return super.getById(id);
    }

    /**
     * pc端查看订单列表,并可根据状态进行查询
     */
    List<TbOrders> getPCList(SoMap soMap, Integer ordersStatus) {
        //检查登录
        StpUtil.checkLogin();
        return tbOrdersMapper.getList(soMap);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbOrders> getList(SoMap so) {
        return tbOrdersMapper.getList(so);
    }

    /**
     * 查集合 - 查二级市场订单(未被购买的订单)
     */
    List<TbOrders> getLevelTwoList(SoMap so) {
        List<TbOrders> levelTwoList = tbOrdersMapper.getLevelTwoList(so);

        String typeCode = so.getString("typeCode");
        if (StringUtils.isNotEmpty(typeCode)) {
            List<TbOrders> collect = new ArrayList<>();
            List<Long> goodsIds = levelOneServerInterface.getGoodsIds(typeCode);
            goodsIds.forEach(goodsId -> {
                collect.addAll(levelTwoList.stream().filter(map -> map.getGoodsId().equals(goodsId)).collect(Collectors.toList()));
            });
            return collect;
        }
        return levelTwoList;
    }

    /**
     * 二级市场订单 组长/边民角色入口
     * 管理购买的商品订单（包括已支付、运输中、售后）
     */
    List<TbOrders> getLeaderOrderList(SoMap so) {
        // 边民组长id
        so.put("leaderId", StpAPPUserUtil.getAPPLoginInfo().getFk());
        so.put("sortType", 22);
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode());
        List<TbOrders> orderList = tbOrdersMapper.getList(so);

        return orderList;
    }

    /**
     * 二级市场订单 收购商角色入口
     * 管理购买的商品订单（包括已支付、运输中、售后）
     */
    List<TbOrders> getPurchaserOrderList(SoMap so) {
        // 收购商id
        so.put("sortType", 22);
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode());
        return tbOrdersMapper.getList(so);
    }

    /**
     * 管理二级市场的开票申请信息、并审核
     *
     * @param tbOrdersID 二级市场订单ID主键
     * @param isBill     审核是否开票状态 1=通过 0=未通过
     */
    public void bill(Long tbOrdersID, Integer isBill) {
        //todo: 管理二级市场的开票申请信息、并审核
    }

    /**
     * 增 一级市场已完成订单进行转售时，新增二级市场订单
     */
    public boolean addOrderByResale(SoMap so) {
        OrderDto orderDto = levelOneServerInterface.getOrderDtoById(so.getLong("id"));
        if (null == orderDto) throw new RuntimeException("当前一级市场订单为空，请联系管理员！");

        //获取app登录用户
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();

        TbOrders orders = new TbOrders();
        orders.setResalePrice(so.getDouble("resalePrice"));
        orders.setLevelOneOrderId(so.getLong("id"));
        orders.setGoodsId(orderDto.getGoodsId());
        orders.setGoodsName(orderDto.getGoodsNames());
        orders.setTradeAreaName(orderDto.getTradeAreaName());
        orders.setTradeAreaId(orderDto.getTradeAreaId());
        orders.setVeNo(orderDto.getVeNo());
        //订单编号:EJSCDD=二级市场订单
        orders.setOrderNo(SystemObject.getREFcode("EJSCDD", new Date()));
        //订单完成状态 (0=未完成,1=已完成)
        orders.setOrderFinish(OrderStatus.ORDER_STATUS_ZERO.getCode());
        //删除状态(0=禁用,1=启用)
        orders.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());

        PeopleDto people = levelOneServerInterface.getRpcById(appLoginInfo.getFk());
        //转售订单的边民
        orders.setLeaderId(people.getId());
        orders.setLeaderName(people.getName());
        orders.setLeaderPhone(people.getPhone());
        //创建人
        orders.setCreateBy(appLoginInfo.getLoginId());
        orders.setCreateName(appLoginInfo.getLoginName());
        orders.setCreateTime(new Date());
        orders.setVeNo(orderDto.getVeNo())
                .setGoodsUnit(orderDto.getGoodsUnit())
                .setNetWet(orderDto.getNetWt() + "")
                .setTotalWeight(orderDto.getTotalWeight() + "")
                .setSinglePrice(orderDto.getDeclPrice() + "")
                .setBuyQty(orderDto.getBuyQty())
                .setBuyQty1(orderDto.getBuyQty1())
                .setBuyQty2(orderDto.getBuyQty2());
        this.add(orders);

        //修改一级市场边民订单转售状态为已转售
        boolean b = levelOneServerInterface.updateResaleStatus(so.getLong("id"));
        if (!b) throw new RuntimeException("修改一级市场边民订单转售状态为已转售失败！");

        return true;
    }

    public OrderFeeItemVO countPrice(SoMap so) {
        OrderDto orderDto = levelOneServerInterface.getOrderDtoById(so.getLong("id"));
        if (null == orderDto) {
            log.error("当前一级市场订单为空，请联系管理员:{}", so.getLong("id"));
            throw new RuntimeException("当前一级市场订单为空，请联系管理员！");
        }
        //目前逻辑为一个边民订单只有一个商品
        GoodsDto goods = levelOneServerInterface.getByGoodsId(orderDto.getGoodsId());
        List<TbFeeItem> feeItemList = tbFeeItemService.getFeeItems();

        BigDecimal TotalPrice = new BigDecimal(orderDto.getTotalPrice());
        BigDecimal GrossWt = new BigDecimal(orderDto.getNetWt() + "");
        if (orderDto.getGoodsUnit().contains("千克") || orderDto.getGoodsUnit().contains("kg")) {
            GrossWt = GrossWt.divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
        }
        //需要交的费用
        BigDecimal chargesPrice = BigDecimal.ZERO;
        OrderFeeItemVO vo = new OrderFeeItemVO();
        List<OrderFeeItemVO.FeeDTO> feeDTOList = new ArrayList<>();
        for (TbFeeItem feeItem : feeItemList) {
            List<TbItemRules> ruleList = tbItemRulesService.getList(new SoMap().set("itemId", feeItem.getId()));
            List<TbItemRules> newRuleList = ruleList.stream()
                    .filter(rule -> rule.getGoodsCodes().contains(goods.getCode()))
                    .collect(Collectors.toList());
            if (newRuleList.isEmpty()) {
                continue;
            }
            for (TbItemRules ruleItem : newRuleList) {
                OrderFeeItemVO.FeeDTO feeDTO = new OrderFeeItemVO.FeeDTO();
                BigDecimal Percent = new BigDecimal(ruleItem.getPercent());
                BigDecimal timesPrice = BigDecimal.ZERO;
                //类型(1=按交易额收取,2=按次收取,3=按吨)
                if ("1".equals(ruleItem.getFeeType())) {
                    feeDTO.setPercent(Percent);
                    timesPrice = TotalPrice.multiply(Percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                } else if ("2".equals(ruleItem.getFeeType())) {
                    timesPrice = ruleItem.getFeeMoney();
                } else if ("3".equals(ruleItem.getFeeType())) {
                    feeDTO.setPercent(Percent);
                    timesPrice = GrossWt.multiply(Percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                }
                chargesPrice = chargesPrice.add(timesPrice);
                feeDTO.setName(feeItem.getName()).setFeeType(ruleItem.getFeeType())
                        .setFeeMoney(timesPrice.doubleValue() + "");
                vo.setCompanyName(feeItem.getCompanyName());
                feeDTOList.add(feeDTO);
            }
        }
        vo.setTotalFee(chargesPrice).setFeeList(feeDTOList).setTitle("交易服务费用明细");
        return vo;
    }

    /**
     * 根据一级市场id查询二级市场订单
     */
    public TbOrders getByLevelOneOrderId(SoMap so) {
        Long levelOneOrderId = so.getLong("levelOneOrderId");
        LambdaQueryWrapper<TbOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrders::getLevelOneOrderId, levelOneOrderId);
        List<TbOrders> tbOrders = tbOrdersMapper.selectList(wrapper);

        if (tbOrders.size() > 0) return tbOrders.get(0);
        return null;
    }

    /**
     * 修改转售金额
     */
    public boolean updateResalePrice(TbOrders tbOrders) {
        return updateById(tbOrders);
    }

    /**
     * 增  二级市场订单
     */
    boolean addByDetail(GoodsDemandVo goodsDemandVo) {
        TbOrders orders = new TbOrders();

        //查询商品基本信息
        GoodsDto goodsDto = levelOneServerInterface.getByGoodsId(goodsDemandVo.getLevelOneGoodsId());
        orders.setGoodsFrom(goodsDto.getSource());

        //订单编号:EJSCDD=二级市场订单
        orders.setOrderNo(SystemObject.getREFcode("EJSCDD", new Date()));
        orders.setGoodsId(goodsDemandVo.getLevelOneGoodsId());
        orders.setGoodsName(goodsDemandVo.getGoodsName());
        orders.setConsigneeName(goodsDemandVo.getName());
        orders.setConsigneePhone(goodsDemandVo.getPhone());
        orders.setUnloadingAddress(goodsDemandVo.getAddressName());
        orders.setLeaderId(goodsDemandVo.getLeaderId());
        // 需求表主键Id
        orders.setFkGoodsDemandId(goodsDemandVo.getGoodsDemandId());
        //订单完成状态 (0=未完成,1=已完成)
        orders.setOrderFinish(OrderStatus.ORDER_STATUS_ZERO.getCode());
        //删除状态(0=禁用,1=启用)
        orders.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
        //创建人
        orders.setCreateBy(StpAPPUserUtil.getAPPLoginInfo().getLoginId());
        orders.setCreateName(StpAPPUserUtil.getAPPLoginInfo().getLoginName());
        orders.setCreateTime(new Date());

        orders.setPurchaserId(StpAPPUserUtil.getAPPLoginInfo().getFk());
        orders.setTradeAreaId(goodsDemandVo.getTradeAreaId());
        orders.setTradeAreaName(goodsDemandVo.getTradeAreaName());

        this.add(orders);

        // 回写到收购商发布需求表，把收购商确认状态改为已确认
        LambdaUpdateWrapper<TbGoodsDemand> wrapper1 = new LambdaUpdateWrapper();
        //收购商是否确认:0=未确认,1=已确认
        wrapper1.set(TbGoodsDemand::getIsConfirm, 1);
        wrapper1.eq(TbGoodsDemand::getId, goodsDemandVo.getGoodsDemandId());
        boolean update1 = goodsDemandService.update(wrapper1);

        // 回写到组长报价表，把报价结果状态改为已确认
        LambdaUpdateWrapper<TbDemandQuotation> wrapper2 = new LambdaUpdateWrapper();
        //收购商是否确认:0=未确认,1=已确认
        wrapper2.set(TbDemandQuotation::getQuotationResult, 1);
        wrapper2.eq(TbDemandQuotation::getDemandId, goodsDemandVo.getGoodsDemandId());
        wrapper2.eq(TbDemandQuotation::getQuotationResult, 0);
        boolean update2 = demandQuotationService.update(wrapper2);

        //todo:给组长发一条已确认接单消息
        MessageDto dto = new MessageDto();
        dto.setUrl("/pages/market/two/leader/order");
        dto.setUserId(goodsDemandVo.getLeaderId());
        dto.setContents("你接单的《" + goodsDemandVo.getGoodsName() + "》商户已确认,请及时发货。");
        adminInterface.messageSave(dto);

        return true;
    }

    /**
     * 根据年份查询每月订单交易额和交易量统计
     *
     * @param type
     * @param year
     * @return
     */
    public List<Map<String, Object>> orderStatistics(String type, String year, Long tradeAreaId) {
        return tbOrdersMapper.orderStatistics(type, year, tradeAreaId);
    }

    /**
     * 查询所有统计年份
     *
     * @return
     */
    public List<Map<String, Object>> selectYear() {
        return tbOrdersMapper.selectYear();
    }

    /**
     * 累计交易额
     *
     * @return
     */
    public Map<String, Object> totalMoney(Long tradeAreaId) {
        return tbOrdersMapper.totalMoney(tradeAreaId);
    }

    public TbOrders findByLevelOneOrderId(Long levelOneOrderId) {
        LambdaQueryWrapper<TbOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrders::getLevelOneOrderId, levelOneOrderId);
        return tbOrdersMapper.selectOne(wrapper);
    }

    public List<TbOrders> findByLevelOneOrderIds(List<Long> levelOneOrderIds) {
        LambdaQueryWrapper<TbOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TbOrders::getLevelOneOrderId, levelOneOrderIds);
        return list(wrapper);
    }

    public List<TbOrders> getOnSaleList(SoMap so) {
        return tbOrdersMapper.getOnSaleList(so);

    }

    public List<OrderStaticsDTO> getPurchaserStatistics(SoMap so) {
        return tbOrdersMapper.getPurchaserStatistics(so);
    }

    /**
     * 采购商补扣款
     */
    public boolean deduction(Long id) {
        TbOrders tbOrders = getById(id);
        if (tbOrders == null) {
            log.error("采购商补扣款失败：{}不存在", id);
            return false;
        }
        if (tbOrders.getIsPay() == 1) {
            log.error("订单已支付：{}", id);
            return false;
        }
        OrderDto orderOne = levelOneServerInterface.getOrderDtoById(tbOrders.getLevelOneOrderId());
        if (StrUtil.isEmpty(orderOne.getGoodsNames())) {
            log.error("采购商扣款失败：{} 订单未找到相关商品", tbOrders.getId());
            return false;
        }
        PaymentTwoDto paymentTwoDto = this.getPaymentData(tbOrders, orderOne);
        StaticLog.info("\n---采购商补扣款---sendMKT006_NoCommission——PaymentTwoDto——:{}", JSONUtil.toJsonStr(paymentTwoDto));
        paymentServerInterface.sendMKT006_NoCommission(paymentTwoDto);
        tbOrders.setIsPay(3);
        tbOrders.setDeductionCount(tbOrders.getDeductionCount() + 1);
        tbOrders.setDeductionTime(new Date());

        return super.updateById(tbOrders);
    }

    /**
     * 查 - 交易凭证
     */
    public TbOrdersPrintVo getSubPrint(Long id) {
        TbOrdersPrintVo vo = new TbOrdersPrintVo();

        TbOrders tbOrders = super.getById(id);
        BeanUtils.copyProperties(tbOrders, vo);

        List<BankInfoDto> bankInfoList = paymentServerInterface.getListBySource(tbOrders.getOrderNo());
        if (bankInfoList.size() > 0) vo.setResult(bankInfoList.get(0).getResult());

        PeopleDto people = levelOneServerInterface.getRpcById(tbOrders.getLeaderId());
        if (people != null) {
            vo.setIdCard(people.getIdCard());
            vo.setGroupName(people.getGroupName());
        }

        return vo;
    }

    /**
     * 查 - 电子协议
     */
    public TbOrdersEmailVo getSubEmail(Long id) {
        TbOrdersEmailVo vo = new TbOrdersEmailVo();

        TbOrders tbOrders = super.getById(id);
        BeanUtils.copyProperties(tbOrders, vo);

        OrderDto orderOne = levelOneServerInterface.getOrderDtoById(tbOrders.getLevelOneOrderId());
        if (orderOne != null) {
            vo.setSettleBillNo(orderOne.getSettleBillNo());
        }

        List<BankInfoDto> bankInfoList = paymentServerInterface.getListBySource(tbOrders.getOrderNo());
        if (bankInfoList.size() > 0) {
            vo.setResult(bankInfoList.get(0).getResult());
        }

        PeopleDto people = levelOneServerInterface.getRpcById(tbOrders.getLeaderId());
        if (people != null) {
            vo.setIdCard(people.getIdCard());
            vo.setGroupName(people.getGroupName());
        }

        PeopleTaxAccountDto peopleTaxAccount = levelOneServerInterface.getTaxAccountByPeopleId(tbOrders.getLeaderId());
        if (peopleTaxAccount != null) {
            vo.setBusinessName(peopleTaxAccount.getBusinessName());
            vo.setContacts(peopleTaxAccount.getContacts());
            vo.setPhone(peopleTaxAccount.getPhone());
            vo.setPeopleBankName(peopleTaxAccount.getBankName());
            vo.setPeopleBankCode(peopleTaxAccount.getBankCode());
            vo.setPeopleDutyParagraph(peopleTaxAccount.getDutyParagraph());
        }

        TbPurchaser purchaser = tbPurchaserMapper.selectById(tbOrders.getPurchaserId());
        if (purchaser != null) {
            vo.setPurchaserBusinessName(purchaser.getBusinessName());
            vo.setLegalPerson(purchaser.getLegalPerson());
            vo.setPurchaserContact(purchaser.getContact());
            vo.setPurchaserBankName(purchaser.getBankName());
            vo.setPurchaserBankAccount(purchaser.getBankAccount());
            vo.setPurchaserDutyParagraph(purchaser.getDutyParagraph());
        }

        return vo;
    }

    public boolean removeOnSaleOrderByLevelOneOrderId(Long levelOneOrderId) {
        LambdaQueryWrapper<TbOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrders::getLevelOneOrderId, levelOneOrderId)
                .eq(TbOrders::getOrderFinish, OrderStatus.ORDER_STATUS_ZERO.getCode()).eq(TbOrders::getIsPay, 0);

        return tbOrdersMapper.delete(wrapper) == 1;
    }

    public boolean removeOnSaleOrderByLevelOneOrderIds(String levelOneOrderIds) {
        List<Long> ids = StrUtil.split(levelOneOrderIds, ",").stream().map(Long::valueOf).collect(Collectors.toList());
        LambdaQueryWrapper<TbOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TbOrders::getLevelOneOrderId, ids)
                .eq(TbOrders::getOrderFinish, OrderStatus.ORDER_STATUS_ZERO.getCode())
                .eq(TbOrders::getIsPay, 0);

        return tbOrdersMapper.delete(wrapper) == ids.size();
    }


    public void payBatch(List<TbOrders> orders) {
        for (TbOrders tbOrders : orders) {
            OrderDto orderOne = levelOneServerInterface.getOrderDtoById(tbOrders.getLevelOneOrderId());
            if (StrUtil.isEmpty(orderOne.getGoodsNames())) {
                log.error("采购商扣款失败：{} 订单未找到相关商品", tbOrders.getId());
                throw new AjaxError(tbOrders.getOrderNo() + "找不到商品信息");
            }
            PaymentTwoDto paymentTwoDto = this.getPaymentData(tbOrders, orderOne);
            StaticLog.info("\n---采购商扣款---sendMKT006_NoCommission——PaymentTwoDto——:{}", JSONUtil.toJsonStr(paymentTwoDto));
            paymentServerInterface.sendMKT006_NoCommission(paymentTwoDto);
            if (tbOrders.getIsPay() == 2) {
                tbOrders.setDeductionCount(tbOrders.getDeductionCount() + 1);
                tbOrders.setDeductionTime(new Date());
            }
            tbOrders.setIsPay(3)
                    .setPayTime(new Date());
        }
        this.updateBatchById(orders);
    }
}
