package com.pj.tb_order;

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

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.core.injector.methods.SelectBatchByIds;
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.level_two_server.LevelTwoServerInterface;
import com.pj.api.client.payment_server.PaymentServerInterface;
import com.pj.api.consts.FeignFactory;
import com.pj.api.dto.*;
import com.pj.common.core.exception.ServiceException;
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.*;
import com.pj.ht_trade_settlement.HtTradeSettlement;
import com.pj.ht_trade_settlement.HtTradeSettlementService;
import com.pj.tb_enterprise.TbEnterprise;
import com.pj.tb_enterprise.TbEnterpriseMapper;
import com.pj.tb_goods_transit.TbGoodsTransit;
import com.pj.tb_goods_transit.TbGoodsTransitMapper;
import com.pj.tb_goods_transit.TbGoodsTransitService;
import com.pj.tb_import_order.TbImportOrder;
import com.pj.tb_import_order.TbImportOrderMapper;
import com.pj.tb_order.vo.ConfirmVo;
import com.pj.tb_order.vo.OrderVo;
import com.pj.tb_order.vo.PeopleConfirmVo;
import com.pj.tb_order_people_confirm.TbOrderPeopleConfirm;
import com.pj.tb_order_people_confirm.TbOrderPeopleConfirmMapper;
import com.pj.tb_people.TbPeople;
import com.pj.tb_people.TbPeopleMapper;
import com.pj.tb_people.TbPeopleService;
import com.pj.tb_shop.TbShop;
import com.pj.tb_shop.TbShopService;
import com.pj.tb_trade_area.TbTradeArea;
import com.pj.tb_trade_area.TbTradeAreaService;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.so.SoMap;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_order -- 订单表
 *
 * @author loovi
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class TbOrderService extends ServiceImpl<TbOrderMapper, TbOrder> implements IService<TbOrder> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbImportOrderMapper tbImportOrderMapper;
    /**
     * 互市组
     */
    @Autowired
    private TbPeopleService tbPeopleService;
    @Autowired
    private TbOrderPeopleConfirmMapper tbOrderPeopleConfirmMapper;
    @Autowired
    private MethodOrderService methodOrderService;

    @Autowired
    private TbGoodsTransitMapper tbGoodsTransitMapper;
    @Autowired
    private TbGoodsTransitService tbGoodsTransitService;
    @Autowired
    private LevelOneServerInterface levelOneServerInterface;
    @Autowired
    private LevelTwoServerInterface levelTwoServerInterface;
    @Autowired
    private TbEnterpriseMapper tbEnterpriseMapper;
    @Autowired
    private AsyncServerInterface asyncServerInterface;
    @Autowired
    private TbPeopleMapper tbPeopleMapper;
    @Autowired
    private TbShopService tbShopService;
    @Resource
    private HtTradeSettlementService htTradeSettlementService;
    @Autowired
    private PaymentServerInterface paymentServerInterface;
    @Autowired
    private TbTradeAreaService tbTradeAreaService;

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

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

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

    }

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

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

    /**
     * 组长或者边民取消订单
     *
     * @param orderId 一级市场订单ID
     */
    @Deprecated
    public boolean cancelOrder(Long orderId) {
        //获取登录用户
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new RuntimeException("当前登录账号信息已失效!");
        //查询订单
        TbOrder tbOrder = tbOrderMapper.selectById(orderId);
        if (tbOrder == null) throw new ServiceException("订单状态异常!");
        //如果该订单商户已叫车则无法进行取消
        if (tbOrder.getCallCarStatus() == 1 || tbOrder.getCallCarStatus() == 2) {
            TbEnterprise enterprise = tbEnterpriseMapper.selectById(appLoginInfo.getFk());
            String phone = null;
            if (enterprise != null) phone = enterprise.getOwnerTel();
            throw new ServiceException("您的订单单号为[ " + tbOrder.getTradeNo() + " ]商户已叫车,无法进行取消,请联系商户电话[ " + phone + " ]进行取消。");
        }
        //将状态设置已取消
        tbOrder.setCancelPeople(1);
        //执行保存
        int updateById = tbOrderMapper.updateById(tbOrder);
        //将goodstransit放开
        if (updateById == 1) {
            //获取goods TransitID
            Long goodsId = tbOrder.getGoodsId();
            TbGoodsTransit tbGoodsTransit = tbGoodsTransitMapper.selectById(goodsId);
            if (tbGoodsTransit == null) throw new RuntimeException("商品发布信息异常!");
            //将商品发布修改成可接单状态
            tbGoodsTransit.setIsOrders(0); // 未被下单
            tbGoodsTransit.setEnterpriseConfirm(0); // 修改商户确认状态为未确认
            //执行保存
            int updated = tbGoodsTransitMapper.updateById(tbGoodsTransit);
            //给互助组下属所有人发送取消的message
            PeopleDto peopleDto = levelOneServerInterface.getRpcById(appLoginInfo.getFk());
            methodOrderService.sendGroupMessage(peopleDto.getGroupId(), peopleDto.getName(), false);
            return updated == 1;
        }
        return false;
    }


    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     * APP专用 与该订单相关的任何人员能看
     *
     * @param so
     * @return
     */
    List<TbOrder> getAPPList(SoMap so) {
        //获取登录用户,登录的用户也许边民,互市组组长,一级市场商家
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();

        //与订单相关的人能看
        List<TbOrder> tbOrderList = methodOrderService.checkType(appLoginInfo.getUserType(), appLoginInfo.getFk(), so);
        return tbOrderList;
    }

    List<OrderVo> getPeopleOrderList(SoMap so) {
        //获取登录用户,登录的用户也许边民,互市组组长,一级市场商家
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo.getUserType() != 2) throw new RuntimeException("当前登陆用户不是边民组长!");

        TbPeople tbPeople = tbPeopleMapper.selectById(appLoginInfo.getFk());
        if (tbPeople.getGroupId() == null) throw new RuntimeException("当前登陆用户不在互助组内!");

        List<TbPeople> peopleList = tbPeopleService.lambdaQuery().eq(TbPeople::getGroupId, tbPeople.getGroupId()).list();
        List<Long> idList = peopleList.stream().map(people -> people.getId()).collect(Collectors.toList());

        List<TbOrder> tbOrderList = tbOrderMapper.getList(so);

        List<TbOrder> list = tbOrderList.stream().filter(order -> idList.contains(order.getBuyUserId())).collect(Collectors.toList());
        List<OrderVo> orderVoList = new ArrayList<>();
        for (TbOrder tbOrder : list) {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(tbOrder, orderVo);
            for (TbPeople people : peopleList) {
                if (people.getId().compareTo(tbOrder.getBuyUserId()) == 0 || people.getId().equals(tbOrder.getBuyUserId())) {
                    orderVo.setPhone(people.getPhone());
                }
            }
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }

    /**
     * 获取当前登陆人订单集合
     */
    public List<TbOrder> selectSelfOrders(SoMap so) {
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new RuntimeException("当前登陆用户信息已失效!");
        return findByBuyUserId(appLoginInfo.getLoginId());
    }

    /**
     * 查 转售列表：边民组长查看已完结订单，包括已转售/未转售
     */
    List<TbOrder> getResaleOrders() {
        //获取app登录用户
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null) throw new RuntimeException("当前登陆用户信息已失效!");

        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        //订单状态(0=未完成,1=已完成)
        wrapper.eq(TbOrder::getFinishStatus, 1);
        wrapper.eq(TbOrder::getBuyUserId, appLoginInfo.getLoginId());
        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);

        return tbOrders;
    }

    /**
     * 改 转售状态：根据订单Id把订单改为已转售
     */
    boolean updateResaleStatus(Long orderId) {
        TbOrder tbOrder = this.getById(orderId);
        if (tbOrder == null) {
            return false;
        }
        tbOrder.setResaleStatus(1);
        Long saleMainId = tbOrder.getSaleMainId();
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(saleMainId);
        if (htTradeSettlement == null) {
            return false;
        }
        Integer saleCount = htTradeSettlement.getOnSaleCount();
        htTradeSettlement.setOnSaleCount((saleCount == null ? 0 : saleCount) + 1);
        htTradeSettlementService.updateById(htTradeSettlement);
        return this.updateById(tbOrder);
    }

    boolean updateEnterpriseConfirm(TbOrder order) {

        // 商户拒绝接单后把商户确认状态改为否，并把商品发布表状态恢复为默认值
        if (2 == order.getEnterpriseConfirm()) {
            LambdaUpdateWrapper<TbGoodsTransit> wrapper = new LambdaUpdateWrapper<>();
            //商品未被下单
            wrapper.set(TbGoodsTransit::getIsOrders, OrderStatus.ORDER_STATUS_ZERO.getCode());
            //商品在售
            wrapper.set(TbGoodsTransit::getGoodsStatus, GoodsStatus.GOODS_STATUS_ON.getCode());

            wrapper.eq(TbGoodsTransit::getId, order.getGoodsId());
            boolean update = tbGoodsTransitService.update(wrapper);

        }

        TbOrder tbOrder = tbOrderMapper.selectById(order.getId());
        //todo:给组长发一条商家消息
        String message = order.getEnterpriseConfirm() == 1 ? "商户已确认,请及时发货。" : "已被商户拒绝,请重新接单或换一家商品。";
        MessageDto dto = new MessageDto();
        dto.setUrl("/pages/market/one/leader/order");
        dto.setUserId(tbOrder.getBuyUserId());
        dto.setContents("你接单的《" + tbOrder.getGoodsNames() + "》" + message);
        adminInterface.messageSave(dto);

        // 修改订单表的商家确认状态
        order.setGoodsId(null);
        boolean flag = updateById(order);

        return flag;
    }

    /**
     * 查看订单详情
     *
     * @param orderId 一级市场订单ID
     * @return 订单的vo
     */
    public OrderVo orderDetail(Long orderId) {
        //查询订单
        TbOrder order = tbOrderMapper.selectById(orderId);
        if (order == null) throw new ServiceException("订单信息异常!");
        //执行封装
        OrderVo orderVo = new OrderVo();
        //数据拷贝
        BeanUtils.copyProperties(order, orderVo);
        return orderVo;
    }

    /**
     * 根据订单ID查询边民确认订单信息
     *
     * @param orderId
     * @return
     */
    public List<TbOrderPeopleConfirm> selectPeopleConfirmByOrderId(Long orderId) {
        List<TbOrderPeopleConfirm> tbOrderPeopleConfirms = tbOrderPeopleConfirmMapper.selectList(new LambdaQueryWrapper<TbOrderPeopleConfirm>().eq(TbOrderPeopleConfirm::getOrderId, orderId));
        if (tbOrderPeopleConfirms.size() > 0) {
            tbOrderPeopleConfirms.forEach(item -> {
                item.setOrderId(null);
                item.setGroupId(null);
                item.setId(null);
                item.setPeopleId(null);
            });
        }
        return tbOrderPeopleConfirms;
    }

    public List<PeopleConfirmVo> getPeopleState(SoMap so) {
        List<PeopleConfirmVo> peopleConfirmList = new ArrayList<>();

        // 获取当前订单所有已确认的边民
        List<TbOrderPeopleConfirm> peopleConfirmlist = tbOrderPeopleConfirmMapper.getList(so);
        Set<Long> peopleIds = new HashSet<>();
        for (TbOrderPeopleConfirm tbOrderPeopleConfirm : peopleConfirmlist) {
            peopleIds.add(tbOrderPeopleConfirm.getPeopleId());
        }

        // 获取组内所有边民
        List<TbPeople> peopleList = tbPeopleService.getList(so);
        for (TbPeople people : peopleList) {
            PeopleConfirmVo peopleConfirmVo = new PeopleConfirmVo();
            peopleConfirmVo.setOrderId(so.getLong("orderId"));
            peopleConfirmVo.setGroupId(so.getLong("groupId"));
            peopleConfirmVo.setPeopleId(people.getId());
            peopleConfirmVo.setPeopleName(people.getName());

            // 订单确认状态
            if (peopleIds.contains(people.getId()) || 2 == people.getRole()) {
                peopleConfirmVo.setOrderStatus(1);
            } else {
                peopleConfirmVo.setOrderStatus(0);
            }
            // 进境申报状态
            peopleConfirmVo.setEntryStatus(0);
            // 进口申报状态
            peopleConfirmVo.setImportStatus(0);

            peopleConfirmList.add(peopleConfirmVo);
        }
        return peopleConfirmList;
    }

    /**
     * 接收订单推送消息，
     * 边民进行交易确认，
     * 支付申请，刷脸认
     * 证，系统发起进行交
     * 易
     */
    public void receiveOrderMessageFromHT() {
        //todo: 8月27日 接收航通申报单推送消息
        //1. 获取订单,并将订单保存到订单表

        //2 根据订单内容获取边民集合,创建订单监听表,将该订单内需要完成的边民数逐条保存到监听表内

        //3. 发起支付申请 , 刷脸认证

        //4. 第3步完成且通过后,调用银行的sdk,验证边民的支付信息,由银行将钱转入第三方监管账户,并给出回执

        //5. 拿到银行回执,判断其状态,修改监听表内该订单的完成情况

        //6. 如果监听表内全部边民完成验证,则更新订单表该订单的边民验证完成情况

        //7. todo: 如果订单表的边民验证状态为已完成,将信息同步至航通

    }


    /**
     * app首页获取边民未确认订单
     */
    public OrderVo getNoConfirmOrder() {
        //获取登录人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();

        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getBuyUserId, appLoginInfo.getFk());
        wrapper.eq(TbOrder::getPeopleConfirmStatus, ConfirmStatus.CONFIRM_STATUS_ZERO.getCode())//订单待确认
                .or().eq(TbOrder::getCooperEntrustStatus, ConfirmStatus.CONFIRM_STATUS_ZERO.getCode())//互助委托待确认
                .or().eq(TbOrder::getApplyConfirmStatus, ConfirmStatus.CONFIRM_STATUS_ZERO.getCode());//进口申报待确认
        wrapper.orderByDesc(TbOrder::getCreateTime);
        wrapper.orderByDesc(TbOrder::getUpdateTime);

        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);
        if (tbOrders.size() > 0) {
            TbOrder order = tbOrders.get(0);

            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo);
            return orderVo;
        }
        return null;
    }

    /**
     * 获取一级市场边民订单的所有确认状态
     *
     * @param orderId 一级市场订单表ID
     */
    public ConfirmVo getConfirmStatus(Long orderId) {
        return tbOrderMapper.getConfirmStatus(orderId);
    }

    private PaymentDto getPaymentData(TbOrder tbOrder) {
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());
        StaticLog.info("getPaymentData:{}", JSONUtil.toJsonStr(htTradeSettlement));
        PaymentDto paymentDto = new PaymentDto();
        BeanUtils.copyProperties(htTradeSettlement, paymentDto);
        paymentDto.setId(tbOrder.getId());
        paymentDto.setTradeNo(tbOrder.getTradeNo());
        paymentDto.setCodeTs(tbOrder.getCodeTs());
        paymentDto.setBuyQty(tbOrder.getBuyQty());
        paymentDto.setGrossWt(tbOrder.getGrossWt());
        paymentDto.setNetWt(tbOrder.getNetWt());
        paymentDto.setGoodsName(tbOrder.getGoodsNames());
        paymentDto.setGoodsUnit(tbOrder.getGoodsUnit());
        paymentDto.setDeclPrice(tbOrder.getDeclPrice());

        paymentDto.setTotalPrice(BigDecimal.valueOf(tbOrder.getTotalPrice()));
        //Double resalePrice = levelTwoServerInterface.getResalePriceByLevelOneOrderId(tbOrder.getId());
        //paymentDto.setResalePrice(BigDecimal.valueOf(resalePrice));

        TbPeople tbPeople = tbPeopleService.getById(tbOrder.getBuyUserId());
        StaticLog.info("tbPeople:{}", JSONUtil.toJsonStr(tbPeople));
        if (tbPeople == null) {
            throw new AjaxError("查询不到边民信息");
        }
        if (StrUtil.isEmpty(tbPeople.getBankCode())) {
            throw new AjaxError(tbPeople.getName() + "银行账号不完善");
        }
        paymentDto.setBankCode(tbPeople.getBankCode());
        paymentDto.setBankName(tbPeople.getBankName());
        paymentDto.setBankNo(tbPeople.getBankNo());
        paymentDto.setBorderName(tbPeople.getName());
        paymentDto.setBorderidno(tbPeople.getIdCard());
        paymentDto.setBorderTel(tbPeople.getPhone());
        paymentDto.setPapersType(tbPeople.getPapersType());
        paymentDto.setBorderNationality(tbPeople.getNationality());

        TbShop tbShop = tbShopService.findByCode(htTradeSettlement.getShopNo());
        if (tbShop == null) {
            throw new AjaxError("查询不到商铺信息");
        }
        if (StrUtil.isEmpty(tbShop.getBankAccount())) {
            throw new AjaxError(tbShop.getShopName() + "银行账号不完善");
        }
        StaticLog.info("tbShop:{}", JSONUtil.toJsonStr(tbShop));
        paymentDto.setOwnerName(tbShop.getOwnerName());
        paymentDto.setOwnerIdtype(tbShop.getOwnerIdtype());
        paymentDto.setBankAccount(tbShop.getBankAccount());
        paymentDto.setBank(tbShop.getBank());
        paymentDto.setOwnerTel(tbShop.getOwnerTel());
        paymentDto.setShopSccd(tbShop.getShopSccd());
        paymentDto.setNationality(tbShop.getNationality());
        return paymentDto;
    }

    /**
     * 边民订单确认
     *
     * @param orderId 一级市场订单表ID
     */
    public boolean confirmOrder(Long orderId) {
        TbOrder tbOrder = this.getById(orderId);
        if (tbOrder == null) {
            throw new AjaxError("订单不存在");
        } else if (2 == tbOrder.getCheckPassStatus()) {
            throw new AjaxError("当前订单查验不通过！边民不能进行交易确认。");
        }
        StaticLog.info("order: {}", JSONUtil.toJsonStr(tbOrder));
        tbOrder.setPeopleConfirmTime(new Date())
                .setPeopleConfirmStatus(ConfirmStatus.CONFIRM_STATUS_ONE.getCode())
                .setUpdateTime(new Date());
        //测试用，跳过银行接口
        //tbOrder.setTradeStatus(TradeStatus.TRADE_STATUS_ONE.getCode()); //已支付
        //tbOrder.setTradeTime(new Date()); //支付回执时间
        //tbOrder.setPayType(0); //支付类型
        /*if ("1".equals(tbOrder.getDeclareType())) {
            tbOrder.setFinishStatus(FinishStatus.FINISH_STATUS_ONE.getCode()); //已完成->完成后可以进行转售
            tbOrder.setFinishTime(new Date());
        }*/

        boolean update = super.updateById(tbOrder);
        // TODO: 2023/8/28 边民发起支付申请，调用银行接口：验证边民支付信息，将货款先存入银行第三方账户，并给出回执
        /*PaymentDto paymentDto = this.getPaymentData(tbOrder);
        StaticLog.info("\nsendSXB010——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
        paymentServerInterface.sendSXB010(paymentDto);*/

        return update;
    }

    /**
     * 边民订单确认-收到银行扣款回执——SXB011——SXB012
     *
     * @param tradeNo      一级市场边民订单-订单编号
     * @param note         回执内容
     * @param SXB010Status 回执状态-1=扣款成功 2=扣款失败
     */
    public boolean confirmOrderFromBank(String tradeNo, String note, Integer SXB010Status) {
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getTradeNo, tradeNo);
        List<TbOrder> tbOrderList = this.list(wrapper);
        if (tbOrderList.size() <= 0) {
            log.error("收到银行回执:{},{},{},订单不存在", tradeNo, note, SXB010Status);
            return false;
        }
        TbOrder tbOrder = tbOrderList.get(0);
        tbOrder.setSxbNote(note);
        // TODO: 2023/8/29 更新状态保存交易记录
        if (2 == SXB010Status) {//扣款失败
            tbOrder.setSxb010Status(2)
                    .setSxb010StatusTime(new Date());
        } else if (1 == SXB010Status) {//扣款成功
            tbOrder.setSxb010Status(1)
                    .setRefundStatus(0)
                    .setSxb010StatusTime(new Date());
            //如果已经过了卡三，则补发送一次通关报文给银行
            if (tbOrder.getFinishStatus() == 1) {
                HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());
                //TODO: 2023/8/30 补发通关报文
                PaymentDto paymentDto2 = new PaymentDto();
                paymentDto2.setTradeNos(tradeNo);
                paymentDto2.setVoyageNo(htTradeSettlement.getVoyageNo());
                paymentDto2.setVeNo(tbOrder.getVeNo());
                StaticLog.info("\n扣款成功，补发通关批文 sendSXB023——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto2));
                paymentServerInterface.sendSXB023(paymentDto2);
                //todo 补发结关信息
            }
        }

        return super.updateById(tbOrder);
    }

    /**
     * 互助委托申报确认
     *
     * @param orderId 一级市场订单表ID
     */
    public boolean cooperOrder(Long orderId) {
        //获取登录人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();

        LambdaUpdateWrapper<TbOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TbOrder::getCooperEntrustStatus, ConfirmStatus.CONFIRM_STATUS_ONE.getCode());//互助委托申报确认:1=确认
        wrapper.set(TbOrder::getCooperEntrustTime, new Date());

        wrapper.set(TbOrder::getUpdateBy, appLoginInfo.getLoginId());
        wrapper.set(TbOrder::getUpdateName, appLoginInfo.getLoginName());
        wrapper.set(TbOrder::getUpdateTime, new Date());

        wrapper.eq(TbOrder::getId, orderId);
        boolean result = update(wrapper);

        return result;
    }

    /**
     * 边民进口申报确认
     *
     * @param orderId 一级市场订单表ID
     */
    public boolean applyOrder(Long orderId) {
        TbOrder tbOrder = this.getById(orderId);
        if (tbOrder == null) {
            throw new AjaxError("订单不存在");
        }
        //获取登录人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();

        LambdaUpdateWrapper<TbOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TbOrder::getApplyConfirmStatus, ConfirmStatus.CONFIRM_STATUS_ONE.getCode());//进口申报确认:1=确认
        wrapper.set(TbOrder::getApplyConfirmTime, new Date());

        wrapper.set(TbOrder::getUpdateBy, appLoginInfo.getLoginId());
        wrapper.set(TbOrder::getUpdateName, appLoginInfo.getLoginName());
        wrapper.set(TbOrder::getUpdateTime, new Date());

        //测试用，跳过银行接口
        // wrapper.set(TbOrder::getFinishStatus, FinishStatus.FINISH_STATUS_ONE.getCode());//已完成->完成后可以进行转售
//        wrapper.set(TbOrder::getFinishTime, new Date());

        wrapper.eq(TbOrder::getId, orderId);
        boolean result = update(wrapper);

        if (result && tbOrder.getPeopleConfirmStatus() == 1) {
            // TODO: 2023/8/29 调用航通009接口，发送信息
            sendConfirmMsgToHt(tbOrder);
        }
        return result;
    }

    /**
     * 发送009信息到航通
     */
    public void sendConfirmMsgToHt(TbOrder tbOrder) {
        TbPeople tbPeople = tbPeopleService.getById(tbOrder.getBuyUserId());
        if (tbPeople == null) {
            StaticLog.info("\n--------------发送009信息到航通————边民不存在！！！");
            throw new AjaxError("--------------发送009信息到航通,边民不存在");
        }
        PeopleConfirmDTO peopleConfirmDTO = new PeopleConfirmDTO();
        peopleConfirmDTO.setBorderName(tbOrder.getBuyUserName());
        peopleConfirmDTO.setIdno(tbPeople.getIdCard());
        peopleConfirmDTO.setSettleBillNo(tbOrder.getSettleBillNo());
        peopleConfirmDTO.setPreIeportNo(tbOrder.getPreIeportNo());
        peopleConfirmDTO.setBorderPutrecNo(tbOrder.getBorderPutrecNo());
        StaticLog.info("\n--------------发送009信息到航通,sendConfirmMsgToHt:{}", JSONUtil.toJsonStr(peopleConfirmDTO));
        FeignFactory.asyncServerInterface.sendConfirm(peopleConfirmDTO);
    }


    /**
     * 判断当前边民的边民订单是否委托
     * cooper_entrust：是否校验互助委托协议【1校验  2不校验】
     */
    public OrderVo getByDeclareType(int cooper_entrust) {
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        TbPeople tbPeople = tbPeopleMapper.selectById(appLoginInfo.getFk());
        if (tbPeople == null) throw new ServiceException("当前用户不存在,请联系管理员!");
        List<TbOrder> list = findByBuyUserId(appLoginInfo.getFk());

        //互助社未确认关联的大订单时边民不能做订单确认
        List<TbOrder> orderList = new ArrayList<>();
        for (TbOrder order : list) {
            QueryWrapper<HtTradeSettlement> htWrapper = new QueryWrapper<>();
            htWrapper.lambda().eq(HtTradeSettlement::getId, order.getSaleMainId())
                    .eq(HtTradeSettlement::getHzsConfirmStatus, 1);
            List<HtTradeSettlement> tradeSettlementList = htTradeSettlementService.list(htWrapper);
            if (tradeSettlementList.size() > 0) {
                orderList.add(order);
            }
        }

        OrderVo orderVo = new OrderVo();
        //被委托订单,并且三个状态中有一个未确认
        List<TbOrder> declareList2 = orderList.stream().filter(item -> item.getApplyConfirmStatus() == 0).collect(Collectors.toList());
        if (declareList2.size() > 0) {
            if (1 == cooper_entrust) {
                List<Long> removeList = new ArrayList<>();
                declareList2.forEach(item -> {
                    TbImportOrder importOrder = tbImportOrderMapper.selectById(item.getImportOrderId());
                    if (StringUtils.isNotEmpty(importOrder.getCooperEntrustImg()) && 0 == importOrder.getJudgeStatus()) {//已上传互助委托协议并且未审核
                        removeList.add(item.getImportOrderId());
                    }
                });
                declareList2 = declareList2.stream().filter(item -> !removeList.contains(item.getImportOrderId())).collect(Collectors.toList());
            }
            if (declareList2.size() > 0) {
                BeanUtils.copyProperties(declareList2.get(0), orderVo);
                return orderVo;
            }
        }

        //未被委托订单,并且订单未确认
        List<TbOrder> declareList1 = orderList.stream().filter(item -> "1".equals(item.getDeclareType()) && item.getPeopleConfirmStatus() == 0).collect(Collectors.toList());
        if (declareList1.size() > 0) {
            BeanUtils.copyProperties(declareList1.get(0), orderVo);
            return orderVo;
        }
        return null;
    }

    /**
     * 根据购买者ID查询
     *
     * @param buyUserId
     * @return
     */
    private List<TbOrder> findByBuyUserId(Long buyUserId) {
        QueryWrapper<TbOrder> ew = new QueryWrapper<>();
        ew.lambda().eq(TbOrder::getBuyUserId, buyUserId)
                .eq(TbOrder::getDeleteStatus, DeleteStatus.DELETE_STATUS_ON.getCode());
        return list(ew);
    }

    /**
     * app调用 退货退款
     * 订单交易确认之后并且银行返回SXB011(银行扣边民的款成功)后，订单状态完成之前，边民可做退货退款操作
     */
    public boolean orderRefund(Long id) {
        TbOrder order = getById(id);
        int refundStatus = order.getRefundStatus();
        if (refundStatus == 1 || refundStatus == 3) {
            StaticLog.error("\n---------退货退款失败：{}已退货退款", id);
            throw new AjaxError("订单已退款或者退款中");
        }
        int sx010Status = order.getSxb010Status();
        if (sx010Status != 1) {
            StaticLog.error("\n---------退货退款失败：{}银行��边民的款未成功", id);
            throw new AjaxError("银行扣边民的款未成功");
        }

        PaymentDto paymentDto = this.getPaymentData(order);
        paymentServerInterface.sendSXB013(paymentDto);

        LambdaUpdateWrapper<TbOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(TbOrder::getRefundStatus, 3);//退款中
        updateWrapper.set(TbOrder::getRefundTime, new Date());//退款时间
        updateWrapper.eq(TbOrder::getId, id);
        boolean update = this.update(updateWrapper);
        StaticLog.info("\nsendSXB013(边民退货退款)——PaymentDto——:{},{}", update, JSONUtil.toJsonStr(paymentDto));

        return update;
    }

    /**
     * 订单补扣款——单个订单
     */
    public boolean deduction(Long id) {
        TbOrder tbOrder = getById(id);
        if (tbOrder == null) {
            StaticLog.error("\n---------补扣款失败：{}不存在", id);
            throw new AjaxError("订单不存在");
        }
        if (tbOrder.getSxb010Status() == 1 && tbOrder.getRefundStatus() == 0) {
            StaticLog.error("\n---------补扣款失败：{}已扣款", id);
            throw new AjaxError("订单已扣款");
        }
        if (tbOrder.getSxb010Status() == 3) {
            StaticLog.error("\n---------补扣款失败：{}退款中", id);
            throw new AjaxError("订单退款中");
        }
        if (StrUtil.isEmpty(tbOrder.getGoodsNames())) {
            StaticLog.error("\n---------无商品信息：{}", id);
            throw new AjaxError("订单无商品信息");
        }
        Integer deductionCount = tbOrder.getDeductionCount() + 1;
        if (tbOrder.getRefundStatus() != 0) {
            String tradeNo = tbOrder.getTradeNo();
            tradeNo = StrUtil.subBefore(tradeNo, "_", false);
            tbOrder.setTradeNo(tradeNo + "_" + deductionCount);
        }
        PaymentDto paymentDto = this.getPaymentData(tbOrder);
        StaticLog.info("\n---订单补扣款---sendSXB010——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
        paymentServerInterface.sendSXB010(paymentDto);
        tbOrder.setDeductionCount(deductionCount);
        tbOrder.setDeductionTime(new Date())
                .setSxb010Status(3);

        return super.updateById(tbOrder);
    }

    /**
     * 订单补扣款——按车，并且未扣款
     */
    public boolean deductionByVeNo(String veNo, Long id) {
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getVeNo, veNo);
        wrapper.eq(TbOrder::getSaleMainId, id);
        wrapper.and(i -> i.ne(TbOrder::getSxb010Status, 1).ne(TbOrder::getSxb010Status, 3))
                .orderByDesc(TbOrder::getCreateTime);
        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);
        if (!tbOrders.isEmpty()) {
            for (TbOrder tbOrder : tbOrders) {
                Integer deductionCount = tbOrder.getDeductionCount() + 1;
                if (tbOrder.getRefundStatus() != 0) {
                    String tradeNo = tbOrder.getTradeNo();
                    tradeNo = StrUtil.subBefore(tradeNo, "_", false);
                    tbOrder.setTradeNo(tradeNo + "_" + deductionCount);
                }
                PaymentDto paymentDto = this.getPaymentData(tbOrder);
                StaticLog.info("\n---订单补扣款——按车---sendSXB010——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
                paymentServerInterface.sendSXB010(paymentDto);

                tbOrder.setDeductionCount(deductionCount);
                tbOrder.setDeductionTime(new Date());
            }
        }

        return super.updateBatchById(tbOrders);
    }

    List<TbOrder> getDeductionByVeNoList(SoMap so) {
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getVeNo, so.getString("veNo"));
        wrapper.eq(TbOrder::getSaleMainId, so.getLong("id"));
        wrapper.ne(TbOrder::getSxb010Status, 1).orderByDesc(TbOrder::getCreateTime);
        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);
        return tbOrders;
    }

    /*-----           正常业务逻辑👆👆    rpc远程调用👇👇 -----*/

    /**
     * 航通发起的退单
     *
     * @param htDeclareChargebackDto
     * @return
     */
    //进出口申报单退单-逻辑处理
    public boolean chargeback(HtDeclareChargebackDto htDeclareChargebackDto) {
        //查询出被退单的所有边民订单
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getTradeAreaId, htDeclareChargebackDto.getFieldCode());
        wrapper.eq(TbOrder::getPreNo, htDeclareChargebackDto.getBillNo());
        wrapper.eq(TbOrder::getChargebacks, 0);
        List<TbOrder> tbOrderList = this.list(wrapper);

        if (tbOrderList.size() <= 0) {
            log.error("进出口申报单退单：{}不存在", JSONUtil.toJsonStr(htDeclareChargebackDto));
            return false;
        }
        // TODO: 2023/11/27 查验不通过，车辆不通过卡3，调用银行退款划扣申请，从银行第三方账户，退回至边民借记卡账户
        tbOrderList.forEach(order -> {
            PaymentDto paymentDto = this.getPaymentData(order);
            StaticLog.info("\nsendSXB013(进出口申报单退单)——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
            paymentServerInterface.sendSXB013(paymentDto);
        });
        Date now = new Date();
        //修改交易结算单(大订单)的查验结果
        LambdaUpdateWrapper<HtTradeSettlement> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(HtTradeSettlement::getChargebacks, 1);
        updateWrapper.set(HtTradeSettlement::getChargebacksTime, now);
        updateWrapper.eq(HtTradeSettlement::getFieldCode, htDeclareChargebackDto.getFieldCode());
        updateWrapper.eq(HtTradeSettlement::getDeclareId, htDeclareChargebackDto.getDeclareId());
        updateWrapper.eq(HtTradeSettlement::getCheckPassStatus, 0);
        boolean update = htTradeSettlementService.update(updateWrapper);

        //修改边民订单的查验结果
        LambdaUpdateWrapper<TbOrder> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.set(TbOrder::getRefundStatus, 3);//退款中
        updateWrapper1.set(TbOrder::getRefundTime, now);//退款时间
        updateWrapper1.set(TbOrder::getCheckPassTime, now);//查验时间（不通过）
        updateWrapper1.set(TbOrder::getChargebacks, 1);
        updateWrapper1.set(TbOrder::getChargebacksTime, now);

        updateWrapper1.eq(TbOrder::getTradeAreaId, htDeclareChargebackDto.getFieldCode());
        updateWrapper1.eq(TbOrder::getPreNo, htDeclareChargebackDto.getBillNo());
        updateWrapper1.eq(TbOrder::getChargebacks, 0);
        boolean update1 = this.update(updateWrapper1);

        return update && update1;
    }

    //收到银行退款回执——SXB014——SXB015
    public boolean chargebackFromBank(String tradeNo, Integer SXB013Status, String note) {
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getTradeNo, tradeNo);
        List<TbOrder> tbOrderList = this.list(wrapper);
        if (tbOrderList.size() <= 0) {
            log.error("收到银行退款回执：{}不存在", tradeNo);
            return false;
        }
        TbOrder tbOrder = tbOrderList.get(0);

        if (2 == SXB013Status) {//退款失败
            tbOrder.setRefundStatus(2).setRefundReason(note).setRefundTime(new Date());
        } else if (1 == SXB013Status) {//退款成功
            tbOrder.setRefundStatus(1)
                    .setRefundReason(note)
                    .setSxb010Status(0)
                    .setRefundTime(new Date());
        }
        return updateById(tbOrder);
    }

    /**
     * 订单补推结关信息给银行
     */
    public boolean sendCXB001(Long id) {
        TbOrder tbOrder = getById(id);
        if (tbOrder == null) {
            StaticLog.error("\n----------订单补推结关信息失败：{}不存在", id);
            return false;
        }

        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());

        //todo: 收到航通007报文即收到海关结关信息，转发结关信息给到银行
        PaymentDto paymentDto = new PaymentDto();
        paymentDto.setTradeNo(tbOrder.getTradeNo());
        paymentDto.setDeclTime(htTradeSettlement.getDeclTime());
        StaticLog.info("\nsendCXB001——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
        paymentServerInterface.sendCXB001(paymentDto);

        //todo: 收到航通007报文即收到海关结关信息，转发通车批信息给到银行
        PaymentDto paymentDto2 = new PaymentDto();
        paymentDto2.setTradeNos(tbOrder.getTradeNo());
        paymentDto2.setVoyageNo(htTradeSettlement.getVoyageNo());
        paymentDto2.setVeNo(tbOrder.getVeNo());
        StaticLog.info("\nsendSXB023——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto2));
        paymentServerInterface.sendSXB023(paymentDto2);


        tbOrder.setFinishTime(new Date());
        tbOrder.setFinishStatus(FinishStatus.FINISH_STATUS_ONE.getCode());

        return updateById(tbOrder);
    }

    /**
     * 订单补推结关信息给银行——按车，并且未完成
     */
    public boolean sendCXB001ByVeNo(String veNo, Long id) {
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getVeNo, veNo);
        wrapper.eq(TbOrder::getSaleMainId, id);
        wrapper.orderByDesc(TbOrder::getCreateTime);
        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);

        if (!tbOrders.isEmpty()) {
            HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrders.get(0).getSaleMainId());
            String tradeNos = "";
            PaymentDto paymentDto = new PaymentDto();
            for (TbOrder tbOrder : tbOrders) {
                tradeNos += tbOrder.getTradeNo() + ",";
                //收到007结关信息后边民即可上架订单，不需等收到打款给外籍商户的成功回执SXB017才能完成订单
                tbOrder.setFinishTime(new Date());
                tbOrder.setFinishStatus(FinishStatus.FINISH_STATUS_ONE.getCode());

                //todo: 收到航通007报文即收到海关结关信息，转发结关信息给到银行
                paymentDto.setTradeNo(tbOrder.getTradeNo());
                paymentDto.setDeclTime(htTradeSettlement.getDeclTime());
                StaticLog.info("\nsendCXB001——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
                log.info("log sendCXB001——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
                paymentServerInterface.sendCXB001(paymentDto);
            }
            this.updateBatchById(tbOrders);

            tradeNos = StringUtils.removeEnd(tradeNos, ",");
            //todo: 收到航通007报文即收到海关结关信息，转发通车批信息给到银行
            PaymentDto paymentDto2 = new PaymentDto();
            paymentDto2.setTradeNos(tradeNos);
            paymentDto2.setVoyageNo(htTradeSettlement.getVoyageNo());
            paymentDto2.setVeNo(veNo);
            StaticLog.info("\nsendSXB023——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto2));
            paymentServerInterface.sendSXB023(paymentDto2);
        }
        return true;
    }

    List<TbOrder> getSendCXB001ByVeNoList(SoMap so) {
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbOrder::getVeNo, so.getString("veNo"));
        wrapper.eq(TbOrder::getSaleMainId, so.getLong("id"));
        wrapper.orderByDesc(TbOrder::getCreateTime);
        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);
        return tbOrders;
    }

    // TODO: 2023/8/28 系统接收到航通007接口信息：车辆已出一级市场（系统接收到这个信息时，证明已经查验通过，不会有进出口申报单退单）
    public boolean orderFinish(HtPassCardDTO htPassCardDTO) {
        String billCodeStr = htPassCardDTO.getBillCode();
        List<String> billCodeList = Arrays.stream(billCodeStr.split(",")).collect(Collectors.toList());
        if (billCodeList.isEmpty()) {
            StaticLog.error("Invalid bill code:{}", JSONUtil.toJsonStr(htPassCardDTO));
            return false;
        }
        //获取出了一级市场的所有边民订单
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TbOrder::getPreIeportNo, billCodeList);
        wrapper.ne(TbOrder::getFinishStatus, 1).orderByDesc(TbOrder::getCreateTime);
        List<TbOrder> tbOrders = tbOrderMapper.selectList(wrapper);
        if (!tbOrders.isEmpty()) {
            String tradeNos = "";
            PaymentDto paymentDto = new PaymentDto();
            for (TbOrder tbOrder : tbOrders) {
                tradeNos += tbOrder.getTradeNo() + ",";
                //收到007结关信息后边民即可上架订单，不需等收到打款给外籍商户的成功回执SXB017才能完成订单
                tbOrder.setFinishTime(new Date());
                tbOrder.setFinishStatus(FinishStatus.FINISH_STATUS_ONE.getCode());

                //todo: 收到航通007报文即收到海关结关信息，转发结关信息给到银行
                paymentDto.setTradeNo(tbOrder.getTradeNo());
                paymentDto.setDeclTime(htPassCardDTO.getCheckTime());
                StaticLog.info("\nsendCXB001——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto));
                paymentServerInterface.sendCXB001(paymentDto);
            }
            this.updateBatchById(tbOrders);

            tradeNos = StringUtils.removeEnd(tradeNos, ",");
            //todo: 收到航通007报文即收到海关结关信息，转发通车批信息给到银行
            PaymentDto paymentDto2 = new PaymentDto();
            paymentDto2.setTradeNos(tradeNos);
            paymentDto2.setVoyageNo(htPassCardDTO.getManifestId());
            paymentDto2.setVeNo(tbOrders.get(0).getVeNo());
            StaticLog.info("\nsendSXB023——PaymentDto——:{}", JSONUtil.toJsonStr(paymentDto2));
            paymentServerInterface.sendSXB023(paymentDto2);
        }
        return true;
    }

    // TODO: 收到（一级市场-通车批信息）银行订单打款回执, tradeNos:订单号 n个——SXB017——SXB018
    public boolean orderFinishFromBank(String tradeNos, Integer SXB023Status) {
        String[] tradeNoArr = tradeNos.split(",");
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        for (String tradeNo : tradeNoArr) {
            wrapper.or().eq(TbOrder::getTradeNo, tradeNo);
        }
        List<TbOrder> tbOrderList = this.list(wrapper);
        if (tbOrderList.size() <= 0) {
            throw new RuntimeException("收到（一级市场-通车批信息）银行订单打款回执——SXB017——SXB018:订单不存在");
        }

        // 更新状态保存交易记录
        if (2 == SXB023Status) {
            tbOrderList.forEach(order -> {
                order.setTradeStatus(TradeStatus.TRADE_STATUS_Two.getCode()); //打款失败
                order.setTradeTime(new Date()); //打款回执时间
                order.setUpdateTime(new Date());

                boolean result = updateById(order);
            });
        } else if (1 == SXB023Status) {
            //更新结算单状态
            Long settleId = tbOrderList.get(0).getSaleMainId();
            HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(settleId);
            htTradeSettlement.setFinishStatus(1).setFinishTime(new Date());
            htTradeSettlementService.updateById(htTradeSettlement);
            tbOrderList.forEach(order -> {
                order.setTradeStatus(TradeStatus.TRADE_STATUS_ONE.getCode()); //打款成功
                order.setTradeTime(new Date()); //打款回执时间
                order.setPayType(0); //支付类型
                order.setFinishStatus(FinishStatus.FINISH_STATUS_ONE.getCode()); //已完成->完成后可以进行转售
                order.setFinishTime(new Date());
                order.setUpdateTime(new Date());

                boolean result = updateById(order);

                if (result) {
                    //todo:通知边民转售已经采购的商品；边民上架商品，初步定价

                    //发送短信
                    TbPeople tbPeople = tbPeopleService.getById(order.getBuyUserId());
                    String content = "您好,您的边民互市订单商品[车辆已出一级市场],订单商品是[" + order.getGoodsNames() + "]。请前往app进行商品转售";
                    SystemObject.smsFactory.handler().sendSMS(tbPeople.getPhone(), content);

                    MessageDto dto = new MessageDto();
                    dto.setUrl("/pages/market/one/leader/order");
                    dto.setUserId(order.getBuyUserId());
                    dto.setContents("你采购的《" + order.getGoodsNames() + "》订单已完成。请及时上架商品到二级市场。");
                    adminInterface.messageSave(dto);
                }
            });
        }
        return true;
    }

    /**
     * 远程调用:根据时间和登陆人查询订单
     */
    public List<OrderDto> selectOrderList(Long appUserId) {
        //判断当前是否已接单
        LambdaQueryWrapper<TbOrder> queryWrapper = new LambdaQueryWrapper<>();
        //根据当天时间查询
//		queryWrapper.eq(TbOrder::getCreateTime,sdf.format(currDay));
        queryWrapper.eq(TbOrder::getCreateBy, appUserId);
        //todo:届时放开该注释
//		queryWrapper.eq(TbOrder::getApply,ApplyStatus.APPLY_STATUS_ONE.getCode()); //申报通过
        queryWrapper.eq(TbOrder::getDeleteStatus, DeleteStatus.DELETE_STATUS_ON.getCode());
        queryWrapper.apply("DATE(create_time) = DATE({0})", new Date()); // 匹配当天的数据
        List<TbOrder> tbOrderList = tbOrderMapper.selectList(queryWrapper);
        //创建返回值集合
        List<OrderDto> result = new ArrayList<>();
        //执行数据封装
        if (tbOrderList.size() == 1) {
            tbOrderList.forEach(item -> {
                OrderDto orderDto = new OrderDto();
                BeanUtils.copyProperties(item, orderDto);
                result.add(orderDto);
            });
        }
        //返回
        return result;
    }

    /**
     * 远程调用  查订单
     */
    OrderDto getOrderDtoById(Long id) {
        TbOrder byId = super.getById(id);
        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(byId, orderDto);
        return orderDto;
    }

    /**
     * 远程调用  修改订单的叫车状态
     */
    public boolean updateOrderCallCarStatus(OrderDto orderDto) {
        TbOrder tbOrder = new TbOrder();
        BeanUtils.copyProperties(orderDto, tbOrder);
        int update = tbOrderMapper.updateById(tbOrder);
        System.out.println("finish update order call_car_status");
        return update == 1;
    }

    /**
     * 远程调用 根据订单Id修改状态：在二级市场被下单[0=未被下单,1=已被下单]
     */
    public boolean updateBeingOrder(Long levelOneOrderId) {
        TbOrder tbOrder = this.getById(levelOneOrderId);
        if (tbOrder == null) {
            return false;
        }
        tbOrder.setBeingOrder(1);
        int i = tbOrderMapper.updateById(tbOrder);
        if (1 != i) System.out.println("远程调用:根据订单Id修改状态（当前订单在二级市场被下单）失败！！！！！！");
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());
        if (htTradeSettlement == null) {
            return false;
        }
        Integer orderCount = htTradeSettlement.getOrderCount();
        Integer beOrderCount = htTradeSettlement.getBeOrderCount();
        orderCount = orderCount == null ? 0 : orderCount;
        beOrderCount = beOrderCount == null ? 0 : beOrderCount;
        if (beOrderCount >= orderCount) {
            return false;
        }
        htTradeSettlement.setBeOrderCount(beOrderCount + 1);
        htTradeSettlementService.updateById(htTradeSettlement);
        return true;
    }

    public void up(Long id, String upPrice) {
        TbOrder tbOrder = this.getById(id);
        tbOrder.setId(id);
        tbOrder.setUpPrice(new BigDecimal(upPrice)).setUpTime(new Date()).setUpStatus(2);
        int i = tbOrderMapper.updateById(tbOrder);
        if (i != 1) {
            throw new AjaxError("上架失败");
        }
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());
        htTradeSettlement.setUpCount(htTradeSettlement.getUpCount() + 1);
        htTradeSettlementService.updateById(htTradeSettlement);
    }

    public void down(Long id) {
        TbOrder db = getById(id);
        if (db == null) {
            throw new AjaxError("该订单不存在");
        }
        if (db.getBeingOrder() == 1) {
            throw new AjaxError("该订单在二级市场被下单，无法下架");
        }
        db.setUpStatus(1);
        this.updateById(db);
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(db.getSaleMainId());
        htTradeSettlement.setUpCount(htTradeSettlement.getUpCount() - 1);
        htTradeSettlementService.updateById(htTradeSettlement);
    }

    public List<OrderDto> getOrderListByMainIds(String mainIds) {
        List<Long> idList = Arrays.stream(mainIds.split(",")).mapToLong(Long::parseLong).boxed().collect(Collectors.toList());
        QueryWrapper<TbOrder> ew = new QueryWrapper<>();
        ew.in("sale_main_id", idList);
        List<TbOrder> list = list(ew);
        List<OrderDto> dtos = new ArrayList<>();
        for (TbOrder tbOrder : list) {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(tbOrder, orderDto);
            dtos.add(orderDto);
        }
        return dtos;
    }

    public List<TbOrder> getOnSaleList(SoMap so) {
        return tbOrderMapper.getOnSaleList(so);
    }


    public Map<String, Object> staticsStatus(Long saleMainId) {
        SoMap soMap = new SoMap();
        soMap.put("saleMainId", saleMainId);
        List<TbOrder> list = tbOrderMapper.getList(soMap);
        int total = list.size();
        List<TbOrder> upList = list.stream().filter(tbOrder -> !Objects.isNull(tbOrder.getUpPrice())).collect(Collectors.toList());
        int upSize = upList.size();
        double upTotalPrice = upList.stream().collect(Collectors.summarizingDouble(order -> order.getUpPrice().doubleValue())).getSum();
        List<TbOrder> saleList = list.stream().filter(tbOrder -> tbOrder.getResaleStatus() == 1).collect(Collectors.toList());
        int saleSize = saleList.size();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("upTotalPrice", upTotalPrice);
        resultMap.put("upSize", upSize);
        resultMap.put("notUpSize", total - upSize);
        resultMap.put("saleSize", saleSize);
        resultMap.put("notSaleSize", total - saleSize);
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancelSale(Long id) {
        TbOrder tbOrder = getById(id);
        if (tbOrder.getBeingOrder() == 1) {
            throw new AjaxError("该订单在二级市场被下单，无法取消转售");
        }
        tbOrder.setResaleStatus(0);
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());
        htTradeSettlement.setOnSaleCount(htTradeSettlement.getOnSaleCount() - 1);
        boolean result = FeignFactory.levelTwoServerInterface.removeOnSaleOrderByLevelOneOrderId(id);
        if (!result) {
            throw new AjaxError("无法撤销转售");
        }
        updateById(tbOrder);
        htTradeSettlementService.updateById(htTradeSettlement);

    }

    public void cancelSaleBatch(List<Long> ids) {
        String idsStr = ids.stream().map(id -> id + "").collect(Collectors.joining(","));
        List<TbOrder> orders = tbOrderMapper.selectBatchIds(ids);
        TbOrder tbOrder = orders.get(0);
        HtTradeSettlement htTradeSettlement = htTradeSettlementService.getById(tbOrder.getSaleMainId());
        boolean result = FeignFactory.levelTwoServerInterface.removeOnSaleOrderByLevelOneOrderIds(idsStr);
        if (!result) {
            throw new AjaxError("无法撤销转售");
        }
        for (TbOrder order : orders) {
            order.setResaleStatus(0);
            htTradeSettlement.setOnSaleCount(htTradeSettlement.getOnSaleCount() - 1);
        }
        this.updateBatchById(orders);
        htTradeSettlementService.updateById(htTradeSettlement);
    }

    public double sumUpPrice(Long htTradeSettlementId) {
        return tbOrderMapper.sumUpPrice(htTradeSettlementId);
    }
}
