package com.heyu.api.controller.mm;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heyu.api.alibaba.request.mm.VvUnShippingDTO;
import com.heyu.api.alibaba.request.mm.order.*;
import com.heyu.api.alibaba.request.mm.order.resp.VVOrderDetailResp;
import com.heyu.api.common.annotation.Describe;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.dao.vv.*;
import com.heyu.api.data.dto.PackageDelivedDelayDTO;
import com.heyu.api.data.entity.vv.*;
import com.heyu.api.data.enums.*;
import com.heyu.api.data.kuaidi100.AdminPackageDTO;
import com.heyu.api.data.kuaidi100.KuaiDi100Utils;
import com.heyu.api.data.kuaidi100.VVOrderListResp;
import com.heyu.api.data.kuaidi100.VvTradeOrderLineDO;
import com.heyu.api.data.service.impl.AbstractOrderAction;
import com.heyu.api.data.service.impl.AppliyReverseRequest;
import com.heyu.api.data.service.impl.ResourceDTO;
import com.heyu.api.data.service.impl.ReverseOrderService;
import com.heyu.api.data.service.vv.VvPackageService;
import com.heyu.api.data.service.vv.VvTradeOrderConvertService;
import com.heyu.api.data.utils.BigDecimalUtil;
import com.heyu.api.data.utils.DateUtils;
import com.heyu.api.data.utils.R;
import com.heyu.api.data.utils.SanUtils;
import com.heyu.api.jsapi.JsapiPrepay;
import com.heyu.api.jsapi.dto.refund.Refund;
import com.heyu.api.utils.ISelect;
import com.heyu.api.utils.PPageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/mm/order")
public class AdminOrderController {

    @Autowired
    private VvTradeOrderDao vvTradeOrderDao;

    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;

    @Autowired
    private VvPackageDao vvPackageDao;

    @Autowired
    private VvSettlementProveDao vvSettlementProveDao;

    @Autowired
    private VvSettlementProveDetailDao vvSettlementProveDetailDao;

    @Autowired
    private VvTradeOrderLineSettlementProveDao vvTradeOrderLineSettlementProveDao;

    @Autowired
    private VvTradeOrderConvertService vvTradeOrderConvertService;

    @Autowired
    private VvBuyerDao vvBuyerDao;

    @Value("${eb.config.rabbitQueue.delayQueue}")
    private String delayQueue;


    @Value("${eb.config.rabbitQueue.delayExchangeName}")
    private String delayExchangeName;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ReverseOrderService reverseOrderService;

    @Autowired
    private JsapiPrepay jsapiPrepay;

    @Autowired
    private VvReverseOrderDao vvReverseOrderDao;

    @Autowired
    private VvTradeOrderLineStatusLogDao vvTradeOrderLineStatusLogDao;

    @Autowired
    private VvPackageService vvPackageService;

    /***
     * 列表
     *  http://localhost:8888/mm/order/list
     */
    @Describe("后台订单列表")
    @RequestMapping("/list")
    public R list(@RequestBody VVOrderRequest vvOrderRequest) {
        if(OrderStatusEnums.refund.equals(vvOrderRequest.getStatus())){
            vvOrderRequest.setRefundCount(1);
        }

        PPageUtils pageUtils = PPageUtils.startPage(vvOrderRequest.getPageNum(), vvOrderRequest.getPageSize())
                .doSelect(new ISelect() {
                    @Override
                    public List doSelect(IPage page) {
                        return vvTradeOrderLineDao.selectByAdminCondition(page,
                                vvOrderRequest.getTradeOrderIds(),
                                vvOrderRequest.getBuyerPhone(),
                                vvOrderRequest.getBuyerName(),
                                vvOrderRequest.getBuyerWeixin(),
                                vvOrderRequest.getMinPromotionPrice(),
                                vvOrderRequest.getMaxPromotionPrice(),
                                vvOrderRequest.getStatus(),
                                vvOrderRequest.getSettleStatus(),
                                vvOrderRequest.getMinCreateTimestamp(),
                                vvOrderRequest.getMaxCreateTimestamp(),
                                vvOrderRequest.getProductName(),
                                vvOrderRequest.getRefundCount(),
                                vvOrderRequest.getProductId(),
                                vvOrderRequest.getSellerId(),
                                vvOrderRequest.getSellerName(),
                                vvOrderRequest.getBuyerId(),
                                vvOrderRequest.getCreateTimestampSort(),
                                vvOrderRequest.getModifyTimestampSort()
                        );
                    }
                });

        // 获取子单
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntities = pageUtils.getRows();
        /***
         * 如果没有数据，就直接返回吧
         */
        if(CollectionUtils.isEmpty(vvTradeOrderLineEntities)){
            return R.ok().setData(pageUtils);
        }

        // 获取订单

        List<Long> tradeOrderIds = SanUtils.list2listFilterNull(vvTradeOrderLineEntities, VvTradeOrderLineEntity::getTradeOrderId);

        List<VvTradeOrderEntity> tradeOrderEntities = vvTradeOrderDao.selectVvTradeOrderByTradeOrderIds(tradeOrderIds);
        // 对订单进行排序，必须按照子单的顺序
        Map<Long, VvTradeOrderEntity> vvTradeOrderEntityMap = SanUtils.groupByFiled2Map(tradeOrderEntities, VvTradeOrderEntity::getId);

        List<VvTradeOrderEntity> vvTradeOrderEntities = new ArrayList<>();
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntities) {
            vvTradeOrderEntities.add(vvTradeOrderEntityMap.get(vvTradeOrderLineEntity.getTradeOrderId()));
        }
        vvOrderRequest.setTradeOrderIds(tradeOrderIds);
        // 重新获取子单
        List<VvTradeOrderLineEntity> list = vvTradeOrderLineDao.selectByAdminConditionList(
                vvOrderRequest.getTradeOrderIds(),
                vvOrderRequest.getBuyerPhone(),
                vvOrderRequest.getBuyerName(),
                vvOrderRequest.getBuyerWeixin(),
                vvOrderRequest.getMinPromotionPrice(),
                vvOrderRequest.getMaxPromotionPrice(),
                vvOrderRequest.getStatus(),
                vvOrderRequest.getSettleStatus(),
                vvOrderRequest.getMinCreateTimestamp(),
                vvOrderRequest.getMaxCreateTimestamp(),
                vvOrderRequest.getProductName(),
                vvOrderRequest.getProductId(),
                vvOrderRequest.getSellerId(),
                vvOrderRequest.getSellerName(),
                vvOrderRequest.getBuyerId(),
                vvOrderRequest.getCreateTimestampSort(),
                vvOrderRequest.getModifyTimestampSort()
        );

        List<VVOrderListResp> vvOrderListResps = vvTradeOrderConvertService.convertTradeOrderLineResp(vvTradeOrderEntities, list, false);
        pageUtils.setRows(vvOrderListResps);
        return R.ok().setData(pageUtils);
    }

    /***
     * 订单详情
     *
     *   /mm/order/detail
     */
    @Describe("后台订单详情")
    @RequestMapping("/detail")
    public R detail(@RequestBody VVOrderDetailRequest request) {
        VvTradeOrderEntity vvTradeOrderEntity = vvTradeOrderDao.selectVvTradeOrderById(request.getTradeOrderId());
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTradeOrderId(request.getTradeOrderId());
        List<Long> tradeOrderLineIdList = SanUtils.getFieldList(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getId);

        List<VvTradeOrderLineStatusLogEntity> vvTradeOrderLineStatusLogList = vvTradeOrderLineStatusLogDao.selectVvTradeOrderLineStatusLogByIdList(tradeOrderLineIdList);
        Map<Long, List<VvTradeOrderLineStatusLogEntity>> tradeOrderLineStatusLogMap = SanUtils.groupByFiled2MapList(vvTradeOrderLineStatusLogList, VvTradeOrderLineStatusLogEntity::getTradeOrderLineId);
        List<VvTradeOrderEntity> vvTradeOrderEntities = SanUtils.asList(vvTradeOrderEntity);

        List<VVOrderListResp> vvOrderListResps = vvTradeOrderConvertService.convertTradeOrderLineResp(vvTradeOrderEntities, vvTradeOrderLineEntityList, false);
        VVOrderDetailResp vvOrderDetailResp = new VVOrderDetailResp();
        vvOrderDetailResp.setVvTradeOrderResp(vvOrderListResps.get(0));

        if (CollectionUtils.isEmpty(vvOrderListResps)) {
            for (VVOrderListResp vvOrderListResp : vvOrderListResps) {
                List<AdminPackageDTO> adminPackageDTOS = vvOrderListResp.getPackageList();
                if (CollectionUtils.isEmpty(adminPackageDTOS)) {
                    for (AdminPackageDTO adminPackageDTO : adminPackageDTOS) {
                        if (CollectionUtils.isNotEmpty(adminPackageDTO.getVvTradeOrderLineDOList())) {
                            VvTradeOrderLineDO tradeOrderLineDO = adminPackageDTO.getVvTradeOrderLineDOList().get(0);
                            adminPackageDTO.setVvTradeOrderLineStatusLogList(tradeOrderLineStatusLogMap.get(tradeOrderLineDO.getId()));
                        }
                    }
                }
            }
        }
        VvBuyerEntity vvBuyerEntity = vvBuyerDao.selectVvBuyerById(vvTradeOrderEntity.getBuyerId());
        vvOrderDetailResp.setVvBuyerEntity(vvBuyerEntity);
        return R.ok().setData(vvOrderDetailResp);
    }


    /***
     * 打包并发货
     * http://localhost:8888/mm/order/toShipping
     */
    @Describe("后台订单发货")
    @RequestMapping("/toShipping")
    public R toPackAndShipping(@RequestBody VvToShippingDTO vvOrderRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(vvOrderRequest.getTradeOrderLineIds());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (AbstractOrderAction.checkFailed(tradeOrderLineEntity, false, ActionEnums.Admin_To_Shipping)) {
                return R.error("订单状态不对");
            }
        }

        VvTradeOrderEntity vvTradeOrderEntity = vvTradeOrderDao.selectVvTradeOrderById(vvTradeOrderLineEntityList.get(0).getTradeOrderId());
        VvPackageEntity vvPackageEntity = vvPackageDao.selectVvPackageByTrackNumber(vvOrderRequest.getTrackNumber());
        if (vvPackageEntity == null) {
            vvPackageEntity = new VvPackageEntity();
        }
        if (CollectionUtils.isNotEmpty(vvOrderRequest.getPackageImageUrls())) {
            vvPackageEntity.setPackageImageUrl(JSON.toJSONString(vvOrderRequest.getPackageImageUrls()));
        }
        vvPackageEntity.setLogisticsCompany(vvOrderRequest.getLogisticsCompany());
        vvPackageEntity.setShippingAmount(vvOrderRequest.getShippingAmount());
        vvPackageEntity.setShippingFrom(vvOrderRequest.getShippingFrom());

        vvPackageEntity.setShippingTo(vvTradeOrderEntity.getContry()
                + vvTradeOrderEntity.getCity()
                + vvTradeOrderEntity.getDistrict()
                + vvTradeOrderEntity.getBuyerDetailAddress());

        vvPackageEntity.setTrackNumber(vvOrderRequest.getTrackNumber());
        vvPackageEntity.setShippingType(ShippingTypeEnums.order.getType());
        vvPackageEntity.setSignReceiptStatus(ApiConstants.NOT_SIGN_RECEIPT);
        vvPackageEntity.setSellerId(vvOrderRequest.getSellerId());
        vvPackageEntity.setSellerWarehouseId(vvOrderRequest.getSellerWarehouseId());

        vvPackageDao.insertOrUpdateVvPackage(vvPackageEntity);

        try {
            vvPackageService.selectVvKuaidiAndUpdateData(vvPackageEntity.getTrackNumber(), RoleEnums.admin.getRole(), false);
            VvPackageEntity vvPackageEntityNew = vvPackageDao.selectVvPackageByTrackNumber(vvPackageEntity.getTrackNumber());

            //  创建订阅
            KuaiDi100Utils.subscribe( vvPackageEntityNew.getTrackNumber(), vvTradeOrderLineEntityList.get(0).getBuyerPhone());
        } catch (Exception e) {
            log.error("AdminOrderController subscribe KuaiDi100 Utils.subscribe error", e);
        }

        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setTrackNumber(vvOrderRequest.getTrackNumber());
            tradeOrderLineEntity.setStatus(OrderStatusEnums.shipping.getStatus());              // 已经发货
            tradeOrderLineEntity.setGmtToShipping(new Date());
            tradeOrderLineEntity.setSellerId(vvOrderRequest.getSellerId());

            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
            vvTradeOrderConvertService.addOrderLineStatusLog(
                    tradeOrderLineEntity.getId(),
                    OrderStatusEnums.shipping,
                    vvOrderRequest.getAdminId(),
                    vvOrderRequest.getUserName());
        }
        return R.ok();
    }

    /***
     * 取消打包
     *  http://localhost:8888/mm/order/unShipping
     */
    @Describe("后台订单重新发货")
    @RequestMapping("/unShipping")
    public R unShipping(@RequestBody VvUnShippingDTO vvOrderRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(vvOrderRequest.getTradeOrderLineIds());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (AbstractOrderAction.checkFailed(tradeOrderLineEntity, false, ActionEnums.Admin_Un_Shipping)) {
                return R.error("没有Admin_Un_Shipping按钮");
            }
        }

        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(OrderStatusEnums.wait_shipping.getStatus());
            tradeOrderLineEntity.setTrackNumber(null);
            tradeOrderLineEntity.setGmtUnShipping(new Date());
            tradeOrderLineEntity.setUnShippingUser(vvOrderRequest.getUserName());
            tradeOrderLineEntity.setUnShippingReason(vvOrderRequest.getReason());
            vvTradeOrderLineDao.updateCoverVvTradeOrderLineById(tradeOrderLineEntity);

            vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                    OrderStatusEnums.wait_shipping,
                    vvOrderRequest.getAdminId(),
                    vvOrderRequest.getUserName(),
                    vvOrderRequest.getReason()
            );
        }
        return R.ok();
    }

    /***
     * 已签收
     * http://localhost:8888/mm/order/shipped
     */
    @Describe("后台订单签收")
    @RequestMapping("/shipped")
    public R shipped(@RequestBody VvShippedDTO vvDeliveredDTO) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(vvDeliveredDTO.getTrackNumber());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (AbstractOrderAction.checkFailed(tradeOrderLineEntity, false, ActionEnums.Admin_Shipped)) {
                return R.error("订单状态不对");
            }
        }

        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(OrderStatusEnums.shipped.getStatus());
            tradeOrderLineEntity.setGmtShipped(new Date());
            tradeOrderLineEntity.setShippedUser(vvDeliveredDTO.getUserName());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);

            vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                    OrderStatusEnums.shipped,
                    vvDeliveredDTO.getAdminId(),
                    vvDeliveredDTO.getUserName()
            );
        }

        VvPackageEntity vvPackageEntity = vvPackageDao.selectVvPackageByTrackNumber(vvDeliveredDTO.getTrackNumber());
        Date time = new Date();
        Date timeAfter15 = DateUtils.addDays(time, 15);
        // 设置签收时间
        vvPackageEntity.setGmtSignReceipt(time);
        PackageDelivedDelayDTO dto = new PackageDelivedDelayDTO();
        dto.setPackageId(vvPackageEntity.getId());
        dto.setRole(vvDeliveredDTO.getUserName());
        dto.setSendTime(DateUtils.formatDate(new Date(), com.heyu.api.data.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));
        dto.setDelayTime(DateUtils.formatDate(timeAfter15, com.heyu.api.data.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));

        dto.setType(DelayTypeEnums.delivered.getType());

        int second = DateUtils.betweenSecond(time, timeAfter15);
        log.info("AdminOrderController delay send :{}", JSON.toJSONString(dto));
        // 通过广播模式发布延时消息 延时30分钟 持久化消息 消费后销毁 这里无需指定路由，会广播至每个绑定此交换机的队列

        rabbitTemplate.convertAndSend(delayExchangeName, "", JSON.toJSONString(dto), message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            message.getMessageProperties().setDelay((second) * 1000);   // 毫秒为单位，指定此消息的延时时长 ,+ 1 尽量保证机器人跑完了，再发送消息
            return message;
        });

        return R.ok();
    }

    /***
     * 订单妥投
     * http://localhost:8888/mm/order/delivered
     */
    @Describe("后台订单妥投")
    @RequestMapping("/delivered")
    public R delivered(@RequestBody VvDeliveredDTO vvDeliveredDTO) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(vvDeliveredDTO.getTrackNumber());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (AbstractOrderAction.checkFailed(tradeOrderLineEntity, false, ActionEnums.Admin_Delivered)) {
                return R.error("订单状态不对");
            }
        }
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(OrderStatusEnums.delivered.getStatus());
            tradeOrderLineEntity.setGmtDelivered(new Date());
            tradeOrderLineEntity.setDeliveredUser(vvDeliveredDTO.getUserName());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);

            vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                    OrderStatusEnums.delivered,
                    vvDeliveredDTO.getAdminId(),
                    vvDeliveredDTO.getUserName()
            );
        }
        return R.ok();
    }

    /***
     * 订单取消
     * http://localhost:8888/mm/order/cancel
     */
    @Describe("后台订单取消")
    @RequestMapping("/cancel")
    public R delivered(@RequestBody VvCancelDTO vvCancelDTO) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTradeOrderId(vvCancelDTO.getTradeOrderId());
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (AbstractOrderAction.checkFailed(vvTradeOrderLineEntity, false, ActionEnums.Admin_Cancel)) {
                return R.error("订单状态不是wait_shipping，不能取消订单");
            }
        }

        AppliyReverseRequest appliyReverseRequest = new AppliyReverseRequest();
        appliyReverseRequest.setRefundType(RefundTypeEnums.only_refund.getCode());
        appliyReverseRequest.setRefundReason("订单取消:" + vvCancelDTO.getReason());
        appliyReverseRequest.setStatus(ReverseStatusEnums.seller_agree_cancel.getStatus());
        R r = reverseOrderService.createReverseOrder(vvTradeOrderLineEntityList, appliyReverseRequest);

        if (r.ifSuccessful()) {
            VvReverseOrderEntity reverseOrderEntity = (VvReverseOrderEntity) r.getData();
            Refund refund = jsapiPrepay.refund(reverseOrderEntity.getTradeOrderId(), reverseOrderEntity.getId());
            log.info("ReverseOrderServiceImpl reverseOrderEntity id:{} refund:{}", reverseOrderEntity.getId(), JSON.toJSONString(refund));
            reverseOrderEntity.setWeixinFundsAccount(JSON.toJSONString(refund.getFundsAccount()));
            reverseOrderEntity.setWeixinStatus(JSON.toJSONString(refund.getStatus()));
            reverseOrderEntity.setWeixinRefundId(refund.getRefundId());
            reverseOrderEntity.setStatus(ReverseStatusEnums.weixin_refunding.getStatus());        // 设置 状态为同意退款
            reverseOrderEntity.setWeixinTransactionId(refund.getTransactionId());
            reverseOrderEntity.setUserEceivedAccount(refund.getUserReceivedAccount());
            reverseOrderEntity.setPreRefundInfo(JSON.toJSONString(refund));
            reverseOrderEntity.setGmtPreRefund(new Date());

            for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntityList) {
                vvTradeOrderLineEntity.setGmtCancel(new Date());
                vvTradeOrderLineEntity.setCancelUser(vvCancelDTO.getUserName());
                vvTradeOrderLineEntity.setCancelReason(vvCancelDTO.getReason());
                vvTradeOrderLineDao.updateVvTradeOrderLineById(vvTradeOrderLineEntity);
                vvTradeOrderConvertService.addOrderLineStatusLog(
                        vvTradeOrderLineEntity.getId(),
                        OrderStatusEnums.cancel,
                        vvCancelDTO.getAdminId(),
                        vvCancelDTO.getUserName(),
                        vvCancelDTO.getReason()
                );
            }
            vvReverseOrderDao.updateVvReverseOrderById(reverseOrderEntity);
        }
        return r;
    }

    /***
     * 上传结算证据
     */
    @Describe("后台订单上传结算证据")
    @RequestMapping("/upload/settlement/prove")
    public R settlement(@RequestBody VvSettleProveDTO vvSettleProveDTO) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(vvSettleProveDTO.getTradeOrderLineIds());
        VvSettlementProveEntity vvSettlementProveEntity = new VvSettlementProveEntity();
        vvSettlementProveDao.insertOrUpdateVvSettlementProve(vvSettlementProveEntity);
        for (ResourceDTO resource : vvSettleProveDTO.getResources()) {
            VvSettlementProveDetailEntity vvSettlementProveDetailEntity = new VvSettlementProveDetailEntity();
            vvSettlementProveDetailEntity.setType(resource.getType());
            vvSettlementProveDetailEntity.setResourceUrl(resource.getResourceUrl());
            vvSettlementProveDetailEntity.setSettlementProveId(vvSettlementProveEntity.getId());
            vvSettlementProveDetailDao.insertOrUpdateVvSettlementProveDetail(vvSettlementProveDetailEntity);
        }


        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setSettleStatus(1);
            //  更新利润
            tradeOrderLineEntity.setProfitAmount(BigDecimalUtil.subtract(tradeOrderLineEntity.getPromotionPrice(), tradeOrderLineEntity.getOriginPrice()));
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);

            // 将子单和证据关联
            VvTradeOrderLineSettlementProveEntity vvTradeOrderLineSettlementProveEntity = new VvTradeOrderLineSettlementProveEntity();
            vvTradeOrderLineSettlementProveEntity.setTradeOrderLineId(tradeOrderLineEntity.getId());
            vvTradeOrderLineSettlementProveEntity.setSettlementProveId(vvSettlementProveEntity.getId());
            vvTradeOrderLineSettlementProveDao.insertOrUpdateVvTradeOrderLineSettlementProve(vvTradeOrderLineSettlementProveEntity);
        }
        return R.ok();
    }

}
