package com.heyu.api.controller.vv;


import com.alibaba.fastjson.JSON;
import com.heyu.api.alibaba.request.mm.enums.ReverseStatusEnums;
import com.heyu.api.alibaba.request.mm.enums.ReverseUploadSceneEnums;
import com.heyu.api.alibaba.request.mm.enums.ShippingTypeEnums;
import com.heyu.api.alibaba.request.mm.order.ResourceDTO;
import com.heyu.api.alibaba.request.mm.reverse.AppliyReverseCloseRequest;
import com.heyu.api.alibaba.request.mm.reverse.AppliyReverseProveRequest;
import com.heyu.api.alibaba.request.mm.reverse.AppliyReverseRequest;
import com.heyu.api.common.annotation.Describe;
import com.heyu.api.data.dao.vv.*;
import com.heyu.api.data.entity.vv.*;
import com.heyu.api.data.utils.BigDecimalUtil;
import com.heyu.api.data.utils.R;
import com.heyu.api.data.utils.SanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@RestController
@RequestMapping("/app/reverse")
public class AppReverseController {


    @Autowired
    private VvReverseOrderDao vvReverseOrderDao;

    @Autowired
    private VvReverseOrderLineDao vvReverseOrderLineDao;

    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;

    @Autowired
    private VvTradeOrderDao vvTradeOrderDao;

    @Autowired
    private VvReverseOrderProveDao vvReverseOrderProveDao;

    @Autowired
    private VvPackageDao vvPackageDao;

    /***
     * /app/reverse/add
     *
     * 逆向订单创建
     * @param appliyReverseRequest
     * @return
     */
    @Describe("逆向订单创建")
    @RequestMapping("/add")
    public R add(@RequestBody AppliyReverseRequest appliyReverseRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(appliyReverseRequest.getTrackNumber());
        List<Long> tradeOrderLineIds = SanUtils.list2list(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getId);

        Map<Long, VvTradeOrderLineEntity> vvTradeOrderLineEntityMap = SanUtils.list2Map(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getId);

        Long tradeOrderId = SanUtils.findAnyNotNull(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getTradeOrderId);

        VvTradeOrderEntity vvTradeOrderEntity = vvTradeOrderDao.selectVvTradeOrderById(tradeOrderId);

        VvReverseOrderEntity vvReverseOrderEntity = new VvReverseOrderEntity();

        vvReverseOrderEntity.setTradeOrderId(vvTradeOrderEntity.getId());

        vvReverseOrderEntity.setStatus(ReverseStatusEnums.buyer_apply_reverse_wait_seller_agree.getStatus());

        BigDecimal realRefundAmount = appliyReverseRequest.getRefundAmount() == null
                ? SanUtils.sum(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getPromotionPrice)
                : appliyReverseRequest.getRefundAmount();
        // 设置退款金额
        vvReverseOrderEntity.setRefundAmount(realRefundAmount);


        BigDecimal originRefundAmount = SanUtils.sum(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getPromotionPrice); // 本来应该退款金额
        if (realRefundAmount.compareTo(originRefundAmount) > 0) {
            return R.error("退款金额不能超过商品总额度");
        }

        vvReverseOrderEntity.setRefundTradeOrderLineCount(tradeOrderLineIds.size());
        vvReverseOrderEntity.setRefundType(appliyReverseRequest.getRefundType());
        vvReverseOrderEntity.setGmtBuyerApplyRefund(new Date());
        vvReverseOrderEntity.setCreateTimestamp(System.currentTimeMillis());
        vvReverseOrderEntity.setModifyTimestamp(System.currentTimeMillis());
        vvReverseOrderEntity.setRefundCount(tradeOrderLineIds.size());
        vvReverseOrderEntity.setGmtBuyerApplyRefund(new Date());
        vvReverseOrderEntity.setRefundReason(appliyReverseRequest.getRefundReason());
        vvReverseOrderDao.insertOrUpdateVvReverseOrder(vvReverseOrderEntity);
        BigDecimal preSum = BigDecimal.ZERO;
        for (int i = 0; i < tradeOrderLineIds.size(); i++) {
            Long tradeOrderLineId = tradeOrderLineIds.get(i);
            VvTradeOrderLineEntity vvTradeOrderLineEntity = vvTradeOrderLineEntityMap.get(tradeOrderLineId);
            VvReverseOrderLineEntity vvReverseOrderLineEntity = new VvReverseOrderLineEntity();
            vvReverseOrderLineEntity.setReverseOrderId(vvReverseOrderEntity.getId());
            vvReverseOrderLineEntity.setTradeOrderId(vvTradeOrderEntity.getId());
            vvReverseOrderLineEntity.setTradeOrderLineId(tradeOrderLineId);
            if (appliyReverseRequest.getRefundAmount() == null) {
                vvReverseOrderLineEntity.setRefundAmount(vvTradeOrderLineEntity.getPromotionPrice());
            } else {
                if (i == tradeOrderLineIds.size() - 1) {
                    BigDecimal lastRefundAmount = BigDecimalUtil.subtract(realRefundAmount, preSum);
                    vvReverseOrderLineEntity.setRefundAmount(lastRefundAmount);
                } else {
                    BigDecimal allPrice = BigDecimalUtil.multiply(vvTradeOrderLineEntity.getPromotionPrice(), realRefundAmount);
                    BigDecimal subLineRefundAmount = BigDecimalUtil.divide(allPrice, originRefundAmount);
                    preSum = preSum.add(subLineRefundAmount);
                    vvReverseOrderLineEntity.setRefundAmount(subLineRefundAmount);
                }
            }
            vvReverseOrderLineEntity.setSellerId(vvTradeOrderLineEntity.getSellerId());
            vvReverseOrderLineEntity.setSellerName(vvTradeOrderLineEntity.getSellerName());
            vvReverseOrderLineEntity.setProductId(vvTradeOrderLineEntity.getProductId());
            vvReverseOrderLineEntity.setProductName(vvTradeOrderLineEntity.getProductName());
            vvReverseOrderLineEntity.setSkuImageUrl(vvTradeOrderLineEntity.getSkuImageUrl());
            // 保存逆向子单
            vvReverseOrderLineDao.insertVvReverseOrderLine(vvReverseOrderLineEntity);

            // 设置退款相关的东西
            vvTradeOrderLineEntity.setRefundCount(1);
            vvTradeOrderLineEntity.setRefundAmount(vvReverseOrderLineEntity.getRefundAmount());
            // 更新子单的逆向状态
            vvTradeOrderLineEntity.setReverseStatus(ReverseStatusEnums.buyer_apply_reverse_wait_seller_agree.getStatus());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(vvTradeOrderLineEntity);
        }

        if (CollectionUtils.isNotEmpty(appliyReverseRequest.getResourceDTOList())) {
            for (ResourceDTO resourceDTO : appliyReverseRequest.getResourceDTOList()) {
                VvReverseOrderProveEntity vvReverseOrderProveEntity = new VvReverseOrderProveEntity();
                vvReverseOrderProveEntity.setReverseOrderId(vvReverseOrderEntity.getId());
                vvReverseOrderProveEntity.setResourceUrl(resourceDTO.getResourceUrl());
                vvReverseOrderProveEntity.setType(resourceDTO.getType());
                vvReverseOrderProveEntity.setScene(ReverseUploadSceneEnums.upload_reverse_prove.getCode());

                vvReverseOrderProveDao.insertOrUpdateVvReverseOrderProve(vvReverseOrderProveEntity);
            }
        }
        return R.ok("申请退款成功");
    }

    /**
     * 退货退款 ： /app/reverse/tracknumber
     *
     */
    @Describe("逆向订单更新订单号")
    @RequestMapping("/upload/tracknumber")
    public R uploadTracknumber(@RequestBody AppliyReverseProveRequest appliyReverseRequest) {
        VvReverseOrderEntity vvReverseOrderEntity = vvReverseOrderDao.selectVvReverseOrderById(appliyReverseRequest.getReverseOrderId());
        if (!ReverseStatusEnums.seller_agree_return_wait_buyer_post.getStatus().equals(vvReverseOrderEntity.getStatus())) {
            return R.error("逆向订单状态不对");
        }
        vvReverseOrderEntity.setStatus(ReverseStatusEnums.shipping.getStatus());
        vvReverseOrderEntity.setTrackNumber(appliyReverseRequest.getTrackNumber());
        vvReverseOrderEntity.setGmtBuyerPost(new Date());
        vvReverseOrderDao.updateVvReverseOrderById(vvReverseOrderEntity);

        List<String> packageImageUrls = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(appliyReverseRequest.getResourceDTOList())) {
            for (ResourceDTO resourceDTO : appliyReverseRequest.getResourceDTOList()) {
                VvReverseOrderProveEntity vvReverseOrderProveEntity = new VvReverseOrderProveEntity();
                vvReverseOrderProveEntity.setReverseOrderId(vvReverseOrderEntity.getId());
                vvReverseOrderProveEntity.setResourceUrl(resourceDTO.getResourceUrl());
                vvReverseOrderProveEntity.setType(resourceDTO.getType());
                vvReverseOrderProveEntity.setScene(ReverseUploadSceneEnums.upload_track_number.getCode());
                packageImageUrls.add(resourceDTO.getResourceUrl());
                vvReverseOrderProveDao.insertOrUpdateVvReverseOrderProve(vvReverseOrderProveEntity);
            }
        }

        VvPackageEntity vvPackageEntity = new VvPackageEntity();
        vvPackageEntity.setPackageImageUrl(JSON.toJSONString(packageImageUrls));
        vvPackageEntity.setShippingAmount(BigDecimal.ZERO);
        vvPackageEntity.setShippingType(ShippingTypeEnums.reverse.getType());
        vvPackageEntity.setTrackNumber(vvPackageEntity.getTrackNumber());
        vvPackageDao.insertOrUpdateVvPackage(vvPackageEntity);
        return R.ok();
    }


    @Describe("逆向订单关闭")
    @RequestMapping("/close")
    public R close(@RequestBody AppliyReverseCloseRequest appliyReverseRequest) {

        VvReverseOrderEntity vvReverseOrderEntity = vvReverseOrderDao.selectVvReverseOrderById(appliyReverseRequest.getReverseOrderId());

        vvReverseOrderEntity.setStatus(ReverseStatusEnums.close.getStatus());

        vvReverseOrderEntity.setGmtClose(new Date());

        vvReverseOrderDao.updateVvReverseOrderById(vvReverseOrderEntity);

        List<VvReverseOrderLineEntity> vvReverseOrderLineEntities = vvReverseOrderLineDao.selectVvReverseOrderLineByReverseOrderId(appliyReverseRequest.getReverseOrderId());

        List<Long> tradeOrderLineIds = SanUtils.list2list(vvReverseOrderLineEntities, VvReverseOrderLineEntity::getTradeOrderLineId);

        List<VvTradeOrderLineEntity> tradeOrderLineEntities = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(tradeOrderLineIds);

        for (VvTradeOrderLineEntity tradeOrderLineEntity : tradeOrderLineEntities) {

            tradeOrderLineEntity.setReverseStatus(ReverseStatusEnums.close.getStatus());

            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
        }

        return R.ok();
    }
}
