package com.hzs.sale.all.controller.api;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.enums.ESysName;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.sale.all.AllProduct;
import com.hzs.common.domain.sale.all.AllProductDetail;
import com.hzs.sale.all.param.SyncDataDetailParam;
import com.hzs.sale.all.param.SyncDateParam;
import com.hzs.sale.all.service.IAllProductDetailService;
import com.hzs.sale.all.service.IAllProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/all-product")
@Slf4j
public class ApiAllProductController extends BaseController {

    @Autowired
    private IAllProductService iAllProductService;
    @Autowired
    private IAllProductDetailService iAllProductDetailService;

    @PostMapping("/sync-data")
    public AjaxResult syncData(@RequestHeader("authorization") String authorization,
                               @RequestBody SyncDateParam param) {
        log.info("全网产品同步数据, authorization: {}", authorization);
        if (StringUtils.isEmpty(authorization)) {
            return AjaxResult.error("缺少参数");
        }
        log.info("全网产品同步数据, param: {}", param);
        if (null == param) {
            return AjaxResult.error("缺少参数");
        }

        String header = new String(Base64Decoder.decode(authorization));
        ESysName headSys = ESysName.getEnumByValue(header.split("!")[0]);
        if (null == headSys) {
            log.warn("head请求来源为空");
            return AjaxResult.error("数据错误");
        }
        if (!headSys.getValue().equals(param.getSource())) {
            log.warn("head请求来源错误");
            return AjaxResult.error("数据错误");
        }
        String headOrder = header.split("!")[1];
        if (null == headOrder) {
            log.warn("head请求订单为空");
            return AjaxResult.error("数据错误");
        }
        if (!headOrder.equals(param.getOrderCode())) {
            log.warn("head请求订单错误");
            return AjaxResult.error("数据错误");
        }

        if (iAllProductDetailService.count(Wrappers.<AllProductDetail>lambdaQuery()
                .eq(AllProductDetail::getSource, param.getSource())
                .eq(AllProductDetail::getOrderCode, param.getOrderCode())
        ) > 0) {
            log.info("订单已经处理过");
            return AjaxResult.success();
        }

        // 产品明细
        List<SyncDataDetailParam> detailList = param.getDetailList();
        if (CollectionUtil.isNotEmpty(detailList)) {
            // 获取仓储编号等数据
            Set<String> wmsCodeList = detailList.stream().map(SyncDataDetailParam::getWmsCode).collect(Collectors.toSet());
            List<AllProduct> productList = iAllProductService.list(Wrappers.<AllProduct>lambdaQuery()
                    .in(AllProduct::getWmsCode, wmsCodeList)
            );
            Map<String, AllProduct> wmsCodeMap = productList.stream().collect(Collectors.toMap(AllProduct::getWmsCode, item -> item));

            // 商品明细列表
            List<AllProductDetail> productDetailList = new ArrayList<>();
            for (SyncDataDetailParam syncDataDetailParam : detailList) {
                AllProduct allProduct = wmsCodeMap.get(syncDataDetailParam.getWmsCode());
                if (null == allProduct) {
                    // 仓储编号不存在，则创建
                    allProduct = AllProduct.builder()
                            .wmsCode(syncDataDetailParam.getWmsCode())
                            .remark("仓储编号不存在，自动创建")
                            .build();
                    allProduct.setPkCreator(MagicNumberConstants.PK_ADMIN);
                    iAllProductService.save(allProduct);
                    wmsCodeMap.put(syncDataDetailParam.getWmsCode(), allProduct);
                }

                AllProductDetail productDetail = AllProductDetail.builder()
                        .pkAllProduct(allProduct.getPkId())
                        .source(param.getSource())
                        .orderCode(param.getOrderCode())
                        .changeNum(syncDataDetailParam.getChangeNum() * -1)
                        .remark(param.getSource() + "系统,订单编号：" + param.getOrderCode() + ",扣减：" + syncDataDetailParam.getWmsCode() + "库存" + syncDataDetailParam.getChangeNum())
                        .build();
                productDetail.setPkCreator(1L);
                productDetailList.add(productDetail);
            }
            iAllProductService.syncData(productDetailList);
        }
        return AjaxResult.success();
    }

}
