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.enums.OrderStatusEnums;
import com.heyu.api.alibaba.request.mm.enums.ShippingTypeEnums;
import com.heyu.api.alibaba.request.mm.order.*;
import com.heyu.api.alibaba.request.mm.order.resp.PackageDTO;
import com.heyu.api.alibaba.request.mm.order.resp.VVOrderListResp;
import com.heyu.api.data.utils.SanUtils;
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.StringUtils;
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.util.*;

@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;

    /***
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody VVOrderRequest vvOrderRequest) {

        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.getMinSalePrice(),
                                vvOrderRequest.getMaxSalePrice(),
                                vvOrderRequest.getStatus(),
                                vvOrderRequest.getSettleStatus(),
                                vvOrderRequest.getMinCreateTimestamp(),
                                vvOrderRequest.getMaxCreateTimestamp(),
                                vvOrderRequest.getProductName(),
                                vvOrderRequest.getSellerId(),
                                vvOrderRequest.getSellerName(),
                                vvOrderRequest.getBuyerId(),
                                vvOrderRequest.getReverseStatus(),
                                vvOrderRequest.getCreateTimestampSort()
                        );
                    }
                });

        // 获取子单
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntities = pageUtils.getRows();

        // 获取订单
        List<Long> tradeOrderIds = SanUtils.list2listFilterNull(vvTradeOrderLineEntities, VvTradeOrderLineEntity::getTradeOrderId);
        List<VvTradeOrderEntity> tradeOrderEntities = vvTradeOrderDao.selectVvTradeOrderByTradeOrderIds(tradeOrderIds);


        // 对订单进行排序，必须按照子单的顺序
        Map<Long, VvTradeOrderEntity> vvTradeOrderEntityMap = SanUtils.list2Map(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.getMinSalePrice(),
                vvOrderRequest.getMaxSalePrice(),
                vvOrderRequest.getStatus(),
                vvOrderRequest.getSettleStatus(),
                vvOrderRequest.getMinCreateTimestamp(),
                vvOrderRequest.getMaxCreateTimestamp(),
                vvOrderRequest.getProductName(),
                vvOrderRequest.getSellerId(),
                vvOrderRequest.getSellerName(),
                vvOrderRequest.getBuyerId(),
                vvOrderRequest.getReverseStatus(),
                vvOrderRequest.getCreateTimestampSort());


        List<String> trackNumbers = SanUtils.list2listFilterNull(list, VvTradeOrderLineEntity::getTrackNumber);
        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<VVOrderListResp> vvOrderListResps = new ArrayList<>();
        for (VvTradeOrderEntity vvTradeOrderEntity : vvTradeOrderEntities) {
            VVOrderListResp vvOrderListResp = new VVOrderListResp();
            BeanUtils.copyProperties(vvTradeOrderEntity, vvOrderListResp);

            List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = new ArrayList<>();
            for (VvTradeOrderLineEntity tradeOrderLineEntity : list) {
                if (vvTradeOrderEntity.getId().equals(tradeOrderLineEntity.getTradeOrderId())) {
                    vvTradeOrderLineEntityList.add(tradeOrderLineEntity);
                }
            }

            /***
             * 订单行信息
             */
            List<VvTradeOrderLineEntity> vvTradeOrderLineList = new ArrayList<>();
            Map<String, PackageDTO> packageDTOMap = new HashMap();

            for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
                if (StringUtils.isNotBlank(tradeOrderLineEntity.getTrackNumber())) {
                    PackageDTO packageDTO = packageDTOMap.get(tradeOrderLineEntity.getTrackNumber());

                    if (packageDTO == null) {
                        VvPackageEntity vvPackage = vvPackageEntityMap.get(tradeOrderLineEntity.getTrackNumber());
                        packageDTO = new PackageDTO();
                        BeanUtils.copyProperties(vvPackage, packageDTO);
                    }

                    List<VvTradeOrderLineEntity> vvTradeOrderLineEntitys = packageDTO.getVvTradeOrderLineEntityList();
                    if (vvTradeOrderLineEntitys == null) {
                        vvTradeOrderLineEntitys = new ArrayList<>();
                    }
                    vvTradeOrderLineEntitys.add(tradeOrderLineEntity);
                    packageDTO.setVvTradeOrderLineEntityList(vvTradeOrderLineEntitys);

                    packageDTOMap.put(tradeOrderLineEntity.getTrackNumber(), packageDTO);

                } else {
                    vvTradeOrderLineList.add(tradeOrderLineEntity);
                }
            }

            List<PackageDTO> packageList = new ArrayList<>();
            for (Map.Entry<String, PackageDTO> entry : packageDTOMap.entrySet()) {
                packageList.add(entry.getValue());
            }
            vvOrderListResp.setVvTradeOrderLineList(vvTradeOrderLineList);
            vvOrderListResp.setPackageList(packageList);

            vvOrderListResps.add(vvOrderListResp);
        }
        return R.ok().setData(vvOrderListResps);
    }

    /***
     * 订单发货
     */
    @RequestMapping("/toShipping")
    public R toShipping(@RequestBody VvToPackDTO vvOrderRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(vvOrderRequest.getTradeOrderLineIds());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (!OrderStatusEnums.wait_shipping.getStatus().equals(tradeOrderLineEntity.getStatus())) {
                return R.error("订单状态不对");
            }
        }
        VvTradeOrderEntity vvTradeOrderEntity = vvTradeOrderDao.selectVvTradeOrderById(vvTradeOrderLineEntityList.get(0).getTradeOrderId());
        VvPackageEntity 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(vvPackageEntity.getTrackNumber());
        vvPackageEntity.setShippingType(ShippingTypeEnums.order.getType());
        vvPackageDao.insertOrUpdateVvPackage(vvPackageEntity);


        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setTrackNumber(vvOrderRequest.getTrackNumber());
            tradeOrderLineEntity.setStatus(OrderStatusEnums.shipping.getStatus());              // 已经发货
            tradeOrderLineEntity.setGmtToShipping(new Date());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
        }
        return R.ok();
    }


    /***
     * 订单打包
     */
    @RequestMapping("/unpack")
    public R unpack(@RequestBody VvToPackDTO vvOrderRequest) {

        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(vvOrderRequest.getTradeOrderLineIds());

        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(OrderStatusEnums.wait_shipping.getStatus());
            tradeOrderLineEntity.setTrackNumber(null);
            vvTradeOrderLineDao.updateCoverVvTradeOrderLineById(tradeOrderLineEntity);
        }
        return R.ok();
    }

    /***
     * 订单打包
     */
    @RequestMapping("/delivered")
    public R delivered(@RequestBody VvDeliveredDTO vvDeliveredDTO) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByIds(vvDeliveredDTO.getTradeOrderLineIds());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (!OrderStatusEnums.shipping.getStatus().equals(tradeOrderLineEntity.getStatus())) {
                return R.error("订单状态不对");
            }
        }
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(OrderStatusEnums.delivered.getStatus());
            tradeOrderLineEntity.setGmtDelivered(new Date());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
        }

        return R.ok();
    }


    /***
     * 上传结算证据
     */
    @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();
    }

}
