package com.heyu.api.controller.mm;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.enums.AwardStatusEnums;
import com.heyu.api.data.enums.ShippingTypeEnums;
import com.heyu.api.data.kuaidi100.ActionDTO;
import com.heyu.api.alibaba.request.mm.reverse.VvApproveRequest;
import com.heyu.api.alibaba.request.mm.reverse.VvReverseListRequest;
import com.heyu.api.alibaba.request.mm.reverse.VvReverseOrderDTO;
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.ReverseStatusEnums;
import com.heyu.api.data.enums.RoleEnums;
import com.heyu.api.data.service.vv.VvPackageService;
import com.heyu.api.data.utils.R;
import com.heyu.api.data.utils.SanUtils;
import com.heyu.api.data.utils.StringUtils;
import com.heyu.api.jsapi.JsapiPrepay;
import com.heyu.api.jsapi.dto.refund.Refund;
import com.heyu.api.data.service.vv.VvTradeOrderConvertService;
import com.heyu.api.data.service.impl.AbstractReverseAction;
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.beans.BeanUtils;
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.*;

@Slf4j
@RestController
@RequestMapping("/mm/reverse")
public class AdminReverseController {

    @Autowired
    private VvReverseOrderDao vvReverseOrderDao;

    @Autowired
    private VvReverseOrderLineDao vvReverseOrderLineDao;


    @Autowired
    private VvReverseOrderProveDao vvReverseOrderProveDao;


    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;

    @Autowired
    private JsapiPrepay jsapiPrepay;

    @Autowired
    private VvPackageDao vvPackageDao;

    @Autowired
    private VvPackageService vvPackageService;

    @Autowired
    private VvTradeOrderConvertService vvTradeOrderConvertService;


    @Autowired
    private VvPromoterTradeOrderAwardDao vvPromoterTradeOrderAwardDao;

    @Autowired
    private VvPromoterTradeOrderLineAwardDao vvPromoterTradeOrderLineAwardDao;

    @Autowired
    private VvBuyerDao vvBuyerDao;

    /***
     * 逆向列表 https://api.1024api.com/api-interface/mm/reverse/list
     * @param vvReverseListRequest
     * @return
     */
    @Describe("后台逆向列表")
    @RequestMapping("/list")
    public R list(@RequestBody VvReverseListRequest vvReverseListRequest) {
        PPageUtils pageUtils = PPageUtils.startPage(vvReverseListRequest.getPageNum(), vvReverseListRequest.getPageSize())
                .doSelect(new ISelect() {
                    @Override
                    public List doSelect(IPage page) {
                        return vvReverseOrderDao.selectByAdminCondition(page,
                                vvReverseListRequest.getTradeOrderId(),
                                vvReverseListRequest.getStatus(),
                                vvReverseListRequest.getTrackNumber(),
                                vvReverseListRequest.getRefundType(),
                                vvReverseListRequest.getMinCreateTimestamp(),
                                vvReverseListRequest.getMaxCreateTimestamp(),
                                vvReverseListRequest.getCreateTimestampSort()
                        );
                    }
                });

        List<VvReverseOrderEntity> vvReverseOrderEntities = pageUtils.getRows();
        List<Long> reverseOrderIds = SanUtils.list2listFilterNull(vvReverseOrderEntities, VvReverseOrderEntity::getId);
        List<VvReverseOrderLineEntity> reverseOrderLineEntities = vvReverseOrderLineDao.selectVvReverseOrderLineByReverseOrderIds(reverseOrderIds);
        Map<Long, List<VvReverseOrderLineEntity>> vvReverseOrderLineEntityMap = SanUtils.groupByFiled2MapList(reverseOrderLineEntities, VvReverseOrderLineEntity::getReverseOrderId);
        List<VvReverseOrderProveEntity> vvReverseOrderProveEntities = vvReverseOrderProveDao.selectVvReverseOrderProveByReverseOrderId(reverseOrderIds);
        Map<Long, List<VvReverseOrderProveEntity>> vvProveMap = SanUtils.groupByFiled2MapList(vvReverseOrderProveEntities, VvReverseOrderProveEntity::getReverseOrderId);
        List<String> trackNumbers = new ArrayList<>();
        for (VvReverseOrderEntity vvReverseOrderEntity : vvReverseOrderEntities) {
            if (StringUtils.isNotEmpty(vvReverseOrderEntity.getTrackNumber())) {
                trackNumbers.add(vvReverseOrderEntity.getTrackNumber());
                vvPackageService.selectVvKuaidiAndUpdateData(vvReverseOrderEntity.getTrackNumber(), RoleEnums.admin.getRole(), true);
            }
        }

        Map<String, VvPackageEntity> vvPackageEntityMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(trackNumbers)) {
            List<VvPackageEntity> packageEntities = vvPackageDao.selectVvPackageByTrackNumbers(trackNumbers);
            for (VvPackageEntity packageEntity : packageEntities) {
                vvPackageEntityMap.put(packageEntity.getTrackNumber(), packageEntity);
            }
        }

        List<VvReverseOrderDTO> vvReverseOrderDTOS = new ArrayList<>();
        for (VvReverseOrderEntity vvReverseOrderEntity : vvReverseOrderEntities) {
            VvReverseOrderDTO vvReverseOrderDTO = new VvReverseOrderDTO();
            BeanUtils.copyProperties(vvReverseOrderEntity, vvReverseOrderDTO);
            vvReverseOrderDTO.setVvReverseOrderLineEntities(vvReverseOrderLineEntityMap.get(vvReverseOrderEntity.getId()));
            vvReverseOrderDTO.setVvReverseOrderProveEntities(vvProveMap.get(vvReverseOrderEntity.getId()));

            vvReverseOrderDTO.setVvPackageEntity(vvPackageEntityMap.get(vvReverseOrderEntity.getTrackNumber()));
            List<ActionDTO> actionDTOS = AbstractReverseAction.getOrderActionDTO(vvReverseOrderEntity, false);
            vvReverseOrderDTO.setOrderActionList(actionDTOS);
            vvReverseOrderDTOS.add(vvReverseOrderDTO);
        }
        pageUtils.setRows(vvReverseOrderDTOS);
        return R.ok().setData(pageUtils);
    }


    /***
     * 逆向审批 ： https://api.1024api.com/api-interface/mm/reverse/list
     */
    @Describe("后台逆向审批")
    @RequestMapping("/approve")
    public R approve(@RequestBody VvApproveRequest vvApproveRequest) {
        VvReverseOrderEntity vvReverseOrderEntity = vvReverseOrderDao.selectVvReverseOrderById(vvApproveRequest.getReverseOrderId());
        ActionDTO orderActionDTO = AbstractReverseAction.getOrderAction(vvReverseOrderEntity, false, vvApproveRequest.getButtonName());
        if (orderActionDTO == null) {
            return R.error("没有这个按钮的权限");
        }
        String targetStatus = orderActionDTO.getTargetStatus();
        vvReverseOrderEntity.setStatus(targetStatus);
        vvReverseOrderDao.updateVvReverseOrderById(vvReverseOrderEntity);

        if (ReverseStatusEnums.seller_agree_return_wait_buyer_post.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtSellerAgreeReturn(new Date());
            vvReverseOrderEntity.setSellerAgreeReturnUser(vvApproveRequest.getUserName());

            VvPackageEntity vvPackageEntity = new VvPackageEntity();
            vvPackageEntity.setShippingAmount(BigDecimal.ZERO);
            vvPackageEntity.setShippingType(ShippingTypeEnums.reverse.getType());
            vvPackageEntity.setSellerId(vvApproveRequest.getSellerId());
            vvPackageEntity.setSellerWarehouseId(vvApproveRequest.getSellerWarehouseId());
            vvPackageEntity.setSignReceiptStatus(ApiConstants.NOT_SIGN_RECEIPT);
            vvPackageDao.insertOrUpdateVvPackage(vvPackageEntity);
        } else if (ReverseStatusEnums.reject_return.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtRejectReturn(new Date());
            vvReverseOrderEntity.setRejectReturnUser(vvApproveRequest.getUserName());
            vvReverseOrderEntity.setRejectReturnReason(vvApproveRequest.getReason());
        } else if (ReverseStatusEnums.shipped.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtShipped(new Date());
            vvReverseOrderEntity.setShippedUser(vvApproveRequest.getUserName());
        } else if (ReverseStatusEnums.reject_sign_receipt.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtRejectSignReceipt(new Date());
            vvReverseOrderEntity.setRejectSignReceiptUser(vvApproveRequest.getUserName());
            vvReverseOrderEntity.setRejectSignReceiptReason(vvApproveRequest.getReason());
        } else if (ReverseStatusEnums.agree_sign_receipt.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtAgreeSignReceipt(new Date());
            vvReverseOrderEntity.setAgreeSignReceiptUser(vvApproveRequest.getUserName());
        } else if (ReverseStatusEnums.qa_check_finished.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtQaCheckFinished(new Date());
            vvReverseOrderEntity.setQaCheckFinishedUser(vvApproveRequest.getUserName());
            vvReverseOrderEntity.setQaCheckFinishedComment(vvApproveRequest.getReason());
        } else if (ReverseStatusEnums.agree_refund.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtAgreeRefund(new Date());
            vvReverseOrderEntity.setAgreeRefundUser(vvApproveRequest.getUserName());
        } else if (ReverseStatusEnums.reject_refund.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtRejectRefund(new Date());
            vvReverseOrderEntity.setRejectRefundUser(vvApproveRequest.getUserName());
            vvReverseOrderEntity.setRejectRefundReason(vvApproveRequest.getReason());
        } else if (ReverseStatusEnums.close.getStatus().equals(targetStatus)) {
            vvReverseOrderEntity.setGmtClose(new Date());
            vvReverseOrderEntity.setCloseUser(vvApproveRequest.getUserName());
            vvReverseOrderEntity.setCloseReason(vvApproveRequest.getReason());
        }

        List<VvReverseOrderLineEntity> vvReverseOrderLineEntities = vvReverseOrderLineDao.selectVvReverseOrderLineByReverseOrderId(vvApproveRequest.getReverseOrderId());
        List<Long> tradeOrderLineIds = SanUtils.list2FieldList(vvReverseOrderLineEntities, VvReverseOrderLineEntity::getTradeOrderLineId);
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(tradeOrderLineIds);

        Long promoterId = SanUtils.findAnyNotNull(vvTradeOrderLineEntityList, VvTradeOrderLineEntity::getPromoterId);
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntityList) {
            vvTradeOrderLineEntity.setReverseStatus(vvReverseOrderEntity.getStatus());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(vvTradeOrderLineEntity);
            // 添加逆向状态日志
            vvTradeOrderConvertService.addOrderLineStatusLog(
                    vvTradeOrderLineEntity.getId(),
                    targetStatus,
                    vvApproveRequest.getAdminId(),
                    vvApproveRequest.getUserName(),
                    vvApproveRequest.getReason(),
                    JSON.toJSONString(vvApproveRequest.getResources())
            );
        }

        if (ReverseStatusEnums.agree_refund.getStatus().equals(targetStatus)) {
            Refund refund = jsapiPrepay.refund(vvReverseOrderEntity.getTradeOrderId(), vvReverseOrderEntity.getId());
            log.info("AdminReverseController reverseOrderEntity id:{} refund:{}", vvReverseOrderEntity.getId(), JSON.toJSONString(refund));
            vvReverseOrderEntity.setWeixinFundsAccount(JSON.toJSONString(refund.getFundsAccount()));
            vvReverseOrderEntity.setWeixinStatus(JSON.toJSONString(refund.getStatus()));
            vvReverseOrderEntity.setWeixinRefundId(refund.getRefundId());
            vvReverseOrderEntity.setWeixinTransactionId(refund.getTransactionId());
            vvReverseOrderEntity.setUserEceivedAccount(refund.getUserReceivedAccount());
            vvReverseOrderEntity.setPreRefundInfo(JSON.toJSONString(refund));
            vvReverseOrderEntity.setGmtPreRefund(new Date());
            vvReverseOrderEntity.setStatus(ReverseStatusEnums.weixin_refunding.getStatus());
            vvReverseOrderDao.updateVvReverseOrderById(vvReverseOrderEntity);
            if (promoterId !=null) {

                List<VvPromoterTradeOrderAwardEntity> vvPromoterTradeOrderAwardEntities = vvPromoterTradeOrderAwardDao.selectVvPromoterTradeOrderAwardByPromoterId(promoterId);
                for (VvPromoterTradeOrderAwardEntity vvPromoterTradeOrderAwardEntity : vvPromoterTradeOrderAwardEntities) {
                    vvPromoterTradeOrderAwardEntity.setStatus(AwardStatusEnums.canceled.getStatus());
                    vvPromoterTradeOrderAwardEntity.setCanceledReason("订单退款");
                    vvPromoterTradeOrderAwardDao.updateVvPromoterTradeOrderAwardById(vvPromoterTradeOrderAwardEntity);

                    vvBuyerDao.updateVvBuyerByIdPromoterCanceledAmountPromoterNotArriveAmount(
                            vvPromoterTradeOrderAwardEntity.getAwardAmount()
                            ,vvPromoterTradeOrderAwardEntity.getAwardAmount(),
                            vvPromoterTradeOrderAwardEntity.getId());
                }

                List<VvPromoterTradeOrderLineAwardEntity> vvPromoterTradeOrderLineAwardEntities = vvPromoterTradeOrderLineAwardDao.selectVvPromoterTradeOrderLineAwardByPromoterId(promoterId);
                for (VvPromoterTradeOrderLineAwardEntity vvPromoterTradeOrderLineAwardEntity : vvPromoterTradeOrderLineAwardEntities) {
                    vvPromoterTradeOrderLineAwardEntity.setStatus(AwardStatusEnums.canceled.getStatus());
                    vvPromoterTradeOrderLineAwardEntity.setCanceledReason("订单退款");
                    vvPromoterTradeOrderLineAwardDao.updateVvPromoterTradeOrderLineAwardById(vvPromoterTradeOrderLineAwardEntity);
                }
            }
        }
        return R.ok();
    }

}
