package com.heyu.api.controller.vv;


import com.alibaba.fastjson.JSON;
import com.heyu.api.alibaba.request.mm.reverse.AppliyReverseCloseRequest;
import com.heyu.api.alibaba.request.mm.reverse.AppliyReverseProveRequest;
import com.heyu.api.common.annotation.AppRealyLogin;
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.enums.*;
import com.heyu.api.data.kuaidi100.KuaiDi100Utils;
import com.heyu.api.data.service.impl.AbstractReverseAction;
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.NumberUtil;
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;

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

    @Autowired
    private VvReverseOrderDao vvReverseOrderDao;

    @Autowired
    private VvReverseOrderLineDao vvReverseOrderLineDao;

    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;

    @Autowired
    private VvReverseOrderProveDao vvReverseOrderProveDao;

    @Autowired
    private VvPackageDao vvPackageDao;

    @Autowired
    private ReverseOrderService reverseOrderService;

    @Autowired
    private VvTradeOrderConvertService vvTradeOrderConvertService;

    @Autowired
    private VvPackageService vvPackageService;

    @Autowired
    private VvSellerWarehouseDao vvSellerWarehouseDao;

    /***
     *
     * https://api.1024api.com/api-interface/app/reverse/add
     * 逆向订单创建
     * @param appliyReverseRequest
     * @return
     */
    @Describe("逆向订单创建")
    @RequestMapping("/add")
    @AppRealyLogin
    public R add(@RequestBody AppliyReverseRequest appliyReverseRequest) {
        // 退款类型 1   仅退款， 2 退款退货
        if (NumberUtil.equals(appliyReverseRequest.getRefundType(), 1)) {
            appliyReverseRequest.setStatus(ReverseStatusEnums.buyer_apply_refund_wait_seller_agree.getStatus());
        } else {
            appliyReverseRequest.setStatus(ReverseStatusEnums.buyer_apply_return_wait_seller_agree.getStatus());
        }
        appliyReverseRequest.setRefundReason("买家申请退款：" + appliyReverseRequest.getRefundReason());
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(appliyReverseRequest.getTradeOrderLineIds());
        R r = reverseOrderService.createReverseOrder(vvTradeOrderLineEntityList, appliyReverseRequest);
        if (r.ifSuccessful()) {
            VvReverseOrderEntity vvReverseOrderEntity = (VvReverseOrderEntity) r.getData();
            vvReverseOrderEntity.setGmtBuyerApplyRefund(new Date());
            vvReverseOrderDao.updateVvReverseOrderById(vvReverseOrderEntity);
        }
        return R.ok();
    }

    /**
     * 退货退款 ： /app/reverse/tracknumber
     *
     */
    @Describe("逆向订单更新订单号")
    @RequestMapping("/upload/tracknumber")
    @AppRealyLogin
    public R uploadTracknumber(@RequestBody AppliyReverseProveRequest appliyReverseRequest) {
        VvReverseOrderEntity vvReverseOrderEntity = vvReverseOrderDao.selectVvReverseOrderById(appliyReverseRequest.getReverseOrderId());
        if (AbstractReverseAction.checkFailed(vvReverseOrderEntity, false,
                ActionEnums.App_Buyer_Upload_Reverse_TrackNumber.getButtonName())) {
            return R.error("逆向订单状态非seller_agree_return_wait_buyer_post，不对");
        }
        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 = vvPackageDao.selectVvPackageByReverseOrderId(vvReverseOrderEntity.getId());
        vvPackageEntity.setPackageImageUrl(JSON.toJSONString(packageImageUrls));
        vvPackageEntity.setTrackNumber(vvPackageEntity.getTrackNumber());
        vvPackageDao.insertOrUpdateVvPackage(vvPackageEntity);

        vvPackageService.selectVvKuaidiAndUpdateData(vvPackageEntity.getTrackNumber(), RoleEnums.user.getRole(), false);

        List<VvReverseOrderLineEntity> vvReverseOrderLineEntities = vvReverseOrderLineDao.selectVvReverseOrderLineByReverseOrderId(vvReverseOrderEntity.getId());

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

        VvPackageEntity vvPackageEntityNew = vvPackageDao.selectVvPackageByTrackNumber(vvPackageEntity.getTrackNumber());
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderByTradeOrderIds(tradeOrderLineIds);

        Long sellerWarehouseId = NumberUtil.objToLongDefault(vvPackageEntity.getSellerWarehouseId(), 1);
        VvSellerWarehouseEntity vvSellerWarehouseEntity = vvSellerWarehouseDao.selectVvSellerWarehouseById(sellerWarehouseId);
        //  创建订阅
        KuaiDi100Utils.subscribe( vvPackageEntityNew.getTrackNumber(), vvSellerWarehouseEntity.getWarehousePhone());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(ReverseStatusEnums.shipping.getStatus());              // 已经发货
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
            vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                    OrderStatusEnums.shipping,
                    appliyReverseRequest.getBuyerId(),
                    appliyReverseRequest.getBuyerName()
            );
        }
        return R.ok();
    }

    /**
     * 逆向订单关闭 ： /app/reverse/close
     */
    @Describe("逆向订单关闭")
    @RequestMapping("/close")
    @AppRealyLogin
    public R close(@RequestBody AppliyReverseCloseRequest request) {
        VvReverseOrderEntity vvReverseOrderEntity = vvReverseOrderDao.selectVvReverseOrderById(request.getReverseOrderId());
        if (AbstractReverseAction.checkFailed(vvReverseOrderEntity, false,
                ActionEnums.App_Buyer_Reverse_Order_Close.getButtonName())) {
            return R.error("逆向订单状态不允许关闭 ");
        }
        vvReverseOrderEntity.setStatus(ReverseStatusEnums.close.getStatus());
        vvReverseOrderEntity.setGmtClose(new Date());
        vvReverseOrderEntity.setCloseReason(request.getReason());
        vvReverseOrderDao.updateVvReverseOrderById(vvReverseOrderEntity);

        List<VvReverseOrderLineEntity> vvReverseOrderLineEntities = vvReverseOrderLineDao.selectVvReverseOrderLineByReverseOrderId(request.getReverseOrderId());
        List<Long> tradeOrderLineIds = SanUtils.list2FieldList(vvReverseOrderLineEntities, VvReverseOrderLineEntity::getTradeOrderLineId);
        List<VvTradeOrderLineEntity> tradeOrderLineEntities = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(tradeOrderLineIds);
        for (VvTradeOrderLineEntity tradeOrderLineEntity : tradeOrderLineEntities) {
            tradeOrderLineEntity.setReverseStatus(ReverseStatusEnums.close.getStatus());



            // 设置退款数量为0
            tradeOrderLineEntity.setRefundCount(0);
            tradeOrderLineEntity.setRefundAmount(BigDecimal.ZERO);
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);

            vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                    ReverseStatusEnums.close.getStatus(),
                    request.getBuyerId(),
                    request.getBuyerName()
            );
        }
        return R.ok("逆向订单关闭成功");
    }
}
