package com.heyu.api.controller.vv;


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.order.AppDeliveredDTO;
import com.heyu.api.alibaba.request.mm.order.VvTradeOrderLineTrackNumberDTO;
import com.heyu.api.alibaba.request.mm.order.resp.*;
import com.heyu.api.alibaba.request.vv.AppOrderRequest;
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 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.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("/app/order")
public class AppOrderController {


    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;


    @Autowired
    private VvTradeOrderDao vvTradeOrderDao;


    @Autowired
    private VvPackageDao vvPackageDao;

    @Autowired
    private VvSkuDao vvSkuDao;


    @Autowired
    private VvProductDao vvProductDao;


    @Autowired
    private VvSkuPropertyValueDao vvSkuPropertyValueDao;


    @Autowired
    private VvBuyerDao vvBuyerDao;

    @Autowired
    private VvBuyerAddressDao vvBuyerAddressDao;

    /***
     * https://api.1024api.com/api-interface/app/order/list
     *
     * 列表
     * todo quyixiao
     */
    @Describe("订单列表")
    @RequestMapping("/list")
    public R list(@RequestBody AppOrderRequest vvOrderRequest) {
        PPageUtils pageUtils = PPageUtils.startPage(vvOrderRequest.getPageNum(), vvOrderRequest.getPageSize())
                .doSelect(new ISelect() {
                    @Override
                    public List doSelect(IPage page) {
                        return vvTradeOrderLineDao.selectByAppCondition(page,
                                vvOrderRequest.getTradeOrderIds(),
                                vvOrderRequest.getStatus(),
                                OrderStatusEnums.delete.getStatus(),
                                vvOrderRequest.getMinCreateTimestamp(),
                                vvOrderRequest.getMaxCreateTimestamp(),
                                vvOrderRequest.getProductName(),
                                vvOrderRequest.getBuyerId(),
                                vvOrderRequest.getReverseStatus(),
                                vvOrderRequest.getCreateTimestampSort()
                        );
                    }
                });

        // 获取子单
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntitiesGroupByTradeOrderId = pageUtils.getRows();
        // 获取订单
        List<Long> tradeOrderIds = SanUtils.list2listFilterNull(vvTradeOrderLineEntitiesGroupByTradeOrderId, VvTradeOrderLineEntity::getTradeOrderId);
        // 拿到订单的顺序
        List<VvTradeOrderEntity> tradeOrderEntities = vvTradeOrderDao.selectVvTradeOrderByTradeOrderIds(tradeOrderIds);

        // 拿到所有的子订单
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntities = vvTradeOrderLineDao.selectVvTradeOrderByTradeOrderIds(tradeOrderIds);

        Map<Long, List<VvTradeOrderLineEntity>> listGroupByTradeOrderId = SanUtils.list2GroupBy(vvTradeOrderLineEntities, VvTradeOrderLineEntity::getTradeOrderId);

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

        // 拿到所有的trackNumbers
        List<String> trackNumbers = SanUtils.list2listFilterNull(vvTradeOrderLineEntities, VvTradeOrderLineEntity::getTrackNumber);

        List<VvPackageEntity> packageEntities = vvPackageDao.selectVvPackageByTrackNumbers(trackNumbers);

        Map<String, VvPackageEntity> vvPackageEntityMap = SanUtils.list2Map(packageEntities, VvPackageEntity::getTrackNumber);

        List<AppTradeOrderLineResp> vvOrderListResps = new ArrayList<>();

        // 如果有tracknumber  ,则以 trader_order_id_sku_id 分组， 如果有trackNumber ，则以 trader_order_id_track_number_sku_id 分组
        Map<Long, Map<String, VvTradeOrderLineTrackNumberDTO>> groupBytrader_order_id_sku_id = new HashMap<>();
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntities) {

            Long tradeOrderId = vvTradeOrderLineEntity.getTradeOrderId();
            Map<String, VvTradeOrderLineTrackNumberDTO> keyMap = groupBytrader_order_id_sku_id.get(tradeOrderId);
            if (keyMap == null) {
                keyMap = new HashMap<>();
            }
            String key = vvTradeOrderLineEntity.getSkuId() + "";

            if (StringUtils.isNotEmpty(vvTradeOrderLineEntity.getTrackNumber())) {
                key = vvTradeOrderLineEntity.getTrackNumber() +"_"+ vvTradeOrderLineEntity.getSkuId() + "";
            }

            VvTradeOrderLineTrackNumberDTO vvTradeOrderLineTrackNumberDTO = keyMap.get(key);
            if (vvTradeOrderLineTrackNumberDTO == null) {
                vvTradeOrderLineTrackNumberDTO = new VvTradeOrderLineTrackNumberDTO();
            }
            vvTradeOrderLineTrackNumberDTO.getVvTradeOrderLineEntities().add(vvTradeOrderLineEntity);
            vvTradeOrderLineTrackNumberDTO.setTrackNumber(vvTradeOrderLineEntity.getTrackNumber());


            keyMap.put(key, vvTradeOrderLineTrackNumberDTO);
            groupBytrader_order_id_sku_id.put(tradeOrderId, keyMap);
        }

        for (Long tradeOrderId : tradeOrderIds) {
            VvTradeOrderLineEntity vvTradeOrderLineEntity = listGroupByTradeOrderId.get(tradeOrderId).get(0);
            Map<String, VvTradeOrderLineTrackNumberDTO> stringVvTradeOrderLineTrackNumberDTOMap = groupBytrader_order_id_sku_id.get(tradeOrderId);
            for (Map.Entry<String, VvTradeOrderLineTrackNumberDTO> mapEntry : stringVvTradeOrderLineTrackNumberDTOMap.entrySet()) {
                VvTradeOrderLineTrackNumberDTO vvTradeOrderLineTrackNumberDTO = mapEntry.getValue();
                AppTradeOrderLineResp appTradeOrderLineResp = new AppTradeOrderLineResp();
                BeanUtils.copyProperties(vvTradeOrderLineEntity, appTradeOrderLineResp);
                // 如果有tracknumber  ,则以 trader_order_id_sku_id 分组， 如果有trackNumber ，则以 trader_order_id_track_number_sku_id 分组
                if (StringUtils.isNotEmpty(vvTradeOrderLineTrackNumberDTO.getTrackNumber())) {
                    VvPackageEntity packageDTO = vvPackageEntityMap.get(vvTradeOrderLineTrackNumberDTO.getTrackNumber());
                    appTradeOrderLineResp.setVvPackageEntity(packageDTO);
                }
                appTradeOrderLineResp.setNum(vvTradeOrderLineTrackNumberDTO.getVvTradeOrderLineEntities().size());
                VvTradeOrderEntity vvTradeOrderEntity = vvTradeOrderEntityMap.get(vvTradeOrderLineEntity.getTradeOrderId());
                appTradeOrderLineResp.setTrackNumber(vvTradeOrderLineTrackNumberDTO.getTrackNumber());
                appTradeOrderLineResp.setTradeOrderEntity(vvTradeOrderEntity);

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


    /***
     *  订单添加
     */
    @Describe("添加订单")
    @RequestMapping("/add")
    public R add(@RequestBody VvTradeOrderDTO vvOrderRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = new ArrayList<>();
        BigDecimal allPrice = BigDecimal.ZERO;
        int allNum = 0;

        List<Long> skuIds = new ArrayList<>();
        for (VvTradeOrderLineDTO vvTradeOrderLineDTO : vvOrderRequest.getVvTradeOrderLineDTOList()) {
            skuIds.add(vvTradeOrderLineDTO.getSkuId());
        }

        Set<Long> productIds = new HashSet<>();
        List<VvSkuPropertyValueEntity> vvSkuPropertyValueList = vvSkuPropertyValueDao.selectVvSkuPropertyValueBySkuIds(skuIds);
        Map<Long, List<VvSkuPropertyValueEntity>> vvSkuPropertyValueMap = new HashMap<>();
        for (VvSkuPropertyValueEntity vvSkuPropertyValueEntity : vvSkuPropertyValueList) {
            List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuPropertyValueMap.get(vvSkuPropertyValueEntity.getSkuId());
            if (vvSkuPropertyValueEntities == null) {
                vvSkuPropertyValueEntities = new ArrayList<>();
            }
            vvSkuPropertyValueEntities.add(vvSkuPropertyValueEntity);
            vvSkuPropertyValueMap.put(vvSkuPropertyValueEntity.getSkuId(), vvSkuPropertyValueEntities);
            productIds.add(vvSkuPropertyValueEntity.getProductId());
        }

        Map<Long, VvSkuEntity> skuEntityMap = new HashMap<>();

        List<VvSkuEntity> vvSkuEntities = vvSkuDao.selectVvSkuBySkuIds(skuIds);

        for (VvSkuEntity vvSkuEntity : vvSkuEntities) {
            skuEntityMap.put(vvSkuEntity.getId(), vvSkuEntity);
            // 如果库存少于 0 ，则显示库存不足
            if (vvSkuEntity.getStock() <= 0) {
                OrderSkuDTO orderSkuDTO = new OrderSkuDTO();
                orderSkuDTO.setSkuId(vvSkuEntity.getId());
                orderSkuDTO.setMessage("库存不足");
                return R.error().setData(orderSkuDTO);
            }
        }

        List<Long> productIdList = new ArrayList<>();
        productIdList.addAll(productIds);
        List<VvProductEntity> vvProductList = vvProductDao.selectVvProductByProductIds(productIdList);

        Map<Long, VvProductEntity> vvProductMap = new HashMap<>();
        for (VvProductEntity vvProductEntity : vvProductList) {
            vvProductMap.put(vvProductEntity.getId(), vvProductEntity);
        }

        Map<Long, Integer> productNumMap = new HashMap<>();

        for (VvTradeOrderLineDTO vvTradeOrderLineDTO : vvOrderRequest.getVvTradeOrderLineDTOList()) {
            VvSkuEntity vvSkuEntity = skuEntityMap.get(vvTradeOrderLineDTO.getSkuId());
            Integer saleCount = productNumMap.get(vvSkuEntity.getProductId());
            if (saleCount == null) {
                saleCount = 0;
            }

            saleCount = saleCount + vvTradeOrderLineDTO.getNum();

            productNumMap.put(vvSkuEntity.getProductId(), saleCount);

            allNum = allNum + vvTradeOrderLineDTO.getNum();

            allPrice = BigDecimalUtil.add(BigDecimalUtil.multiply(vvSkuEntity.getSalePrice(), new BigDecimal(vvTradeOrderLineDTO.getNum())), allPrice);

            List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuPropertyValueMap.get(vvTradeOrderLineDTO.getSkuId());

            VvProductEntity vvProduct = vvProductMap.get(vvSkuEntity.getProductId());

            List<PropertyNameValue> propertyNameValues = new ArrayList<>();
            for (VvSkuPropertyValueEntity vvSkuPropertyValueEntity : vvSkuPropertyValueEntities) {
                PropertyNameValue propertyNameValue = new PropertyNameValue();
                propertyNameValue.setPropertyName(vvSkuPropertyValueEntity.getProductPropertyName());
                propertyNameValue.setPropertyValue(vvSkuPropertyValueEntity.getProductPropertyValue());
                propertyNameValues.add(propertyNameValue);
            }
            for (int i = 0; i < vvTradeOrderLineDTO.getNum(); i++) {
                VvTradeOrderLineEntity vvTradeOrderLineEntity = new VvTradeOrderLineEntity();
                vvTradeOrderLineEntity.setSkuId(vvTradeOrderLineDTO.getSkuId());
                vvTradeOrderLineEntity.setNum(1);                   // 拆成最细粒度的单
                vvTradeOrderLineEntity.setCreateTime(new Date());
                vvTradeOrderLineEntity.setModifyTime(new Date());
                vvTradeOrderLineEntity.setSalePrice(vvSkuEntity.getSalePrice());
                vvTradeOrderLineEntity.setSkuImageUrl(vvSkuEntity.getImageUrl());
                vvTradeOrderLineEntity.setOriginPrice(vvSkuEntity.getOriginPrice());
                vvTradeOrderLineEntity.setStatus(OrderStatusEnums.wait_pay.getStatus());
                vvTradeOrderLineEntity.setProductId(vvSkuEntity.getProductId());
                vvTradeOrderLineEntity.setProductName(vvProduct.getTitle());
                vvTradeOrderLineEntity.setPromotionPrice(vvSkuEntity.getPromotionPrice());
                vvTradeOrderLineEntity.setProductMainImageUrl(vvProduct.getMainImageUrl());
                vvTradeOrderLineEntity.setSkuInfo(JSON.toJSONString(propertyNameValues));
                vvTradeOrderLineEntityList.add(vvTradeOrderLineEntity);
                vvTradeOrderLineEntity.setBatchNum(vvTradeOrderLineDTO.getNum());
            }
        }

        VvTradeOrderEntity vvTradeOrderEntity = new VvTradeOrderEntity();
        VvBuyerEntity vvBuyerEntity = vvBuyerDao.selectVvBuyerById(vvOrderRequest.getBuyerId());

        //创建时间
        vvTradeOrderEntity.setCreateTime(new Date());
        vvTradeOrderEntity.setModifyTime(new Date());
        vvTradeOrderEntity.setNum(allNum);
        vvTradeOrderEntity.setBuyerPhone(vvBuyerEntity.getBuyerPhone());
        vvTradeOrderEntity.setBuyerName(vvBuyerEntity.getBuyerName());
        vvTradeOrderEntity.setBuyerWeixin(vvBuyerEntity.getBuyerWeixin());
        vvTradeOrderEntity.setGmtDownOrder(new Date());

        VvBuyerAddressEntity vvBuyerAddress = vvBuyerAddressDao.selectVvBuyerAddressById(vvOrderRequest.getBuyerAddressId());
        vvTradeOrderEntity.setContry(vvBuyerAddress.getContry());
        vvTradeOrderEntity.setProvince(vvBuyerAddress.getProvince());
        vvTradeOrderEntity.setCity(vvBuyerAddress.getCity());
        vvTradeOrderEntity.setDistrict(vvBuyerAddress.getDistrict());
        vvTradeOrderEntity.setBuyerDetailAddress(vvBuyerAddress.getDetail());
        vvTradeOrderEntity.setAllPrice(allPrice);
        vvTradeOrderEntity.setBuyerId(vvOrderRequest.getBuyerId());
        vvTradeOrderEntity.setCreateTimestamp(System.currentTimeMillis());
        vvTradeOrderEntity.setModifyTimestamp(System.currentTimeMillis());

        vvTradeOrderDao.insertVvTradeOrder(vvTradeOrderEntity);
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setTradeOrderId(vvTradeOrderEntity.getId());
            vvTradeOrderLineDao.insertOrUpdateVvTradeOrderLine(tradeOrderLineEntity);
        }

        for (VvTradeOrderLineDTO vvTradeOrderLineDTO : vvOrderRequest.getVvTradeOrderLineDTOList()) {
            vvSkuDao.updateVvSkuStockSaleCountById(vvTradeOrderLineDTO.getNum(), vvTradeOrderLineDTO.getNum(), vvTradeOrderLineDTO.getNum(), vvTradeOrderLineDTO.getSkuId());
        }

        for (Map.Entry<Long, Integer> map : productNumMap.entrySet()) {
            vvProductDao.updateShowSaleCountAndSaleCount(map.getValue(), map.getValue(), map.getKey());
        }






        return R.ok("订单创建成功");
    }

    @Describe("删除订单")
    @RequestMapping("/delete")
    public R add(@RequestBody VvTradeOrderDeleteDTO vvOrderRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(vvOrderRequest.getTrackNumber());
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntityList) {
            vvTradeOrderDao.updateByBuerIdAndIds(OrderStatusEnums.delete.getStatus(), vvOrderRequest.getBuyerId(), vvTradeOrderLineEntity.getId());
        }
        return R.ok();
    }

    /***
     * 订单 妥投   /app/order/delivered
     */
    @Describe("订单确认收货")
    @RequestMapping("/delivered")
    public R topack(@RequestBody AppDeliveredDTO vvDeliveredDTO) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(vvDeliveredDTO.getTrackNumber());
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            if (!OrderStatusEnums.shipping.getStatus().equals(tradeOrderLineEntity.getStatus())) {
                return R.error("订单状态不对");
            }
        }
        for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
            tradeOrderLineEntity.setStatus(OrderStatusEnums.delivered.getStatus());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
        }
        return R.ok();
    }

}
