package com.jsh.erp.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.datasource.entities.DepotHeadVo4Body;
import com.jsh.erp.datasource.entities.MaterialVo4Unit;
import com.jsh.erp.datasource.vo.DepotHeadXsddRequestVO;
import com.jsh.erp.datasource.vo.DepotItemXsddRequestVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description TODO
 * @Author MS.BLUE
 * @Date 2025-04-12
 */
@Service
public class SyncTescoSystemService {

    private Logger logger = LoggerFactory.getLogger(SyncTescoSystemService.class);

    @Resource
    private MaterialService materialService;

    @Resource
    private DepotHeadService depotHeadService;

    @Resource
    private SequenceService sequenceService;

    public String syncSystemSku(String param) {
        logger.info("获取商品系统sku，返回信息集采系统 param:{}", param);
        JSONObject result = new JSONObject();
        JSONArray dataArray = new JSONArray();

        try {
            // 参数校验
            if (param == null || param.isEmpty()) {
                result.put("code", 1);
                result.put("msg", "参数不能为空");
                return result.toJSONString();
            }

            // 解析传入的JSON参数
            JSONArray barCodeArray = JSONArray.parseArray(param);
            if (barCodeArray == null || barCodeArray.isEmpty()) {
                result.put("code", 1);
                result.put("msg", "参数格式错误");
                return result.toJSONString();
            }

            // 提取 barCode 到字符串数组
            List<String> barCodeList = new ArrayList<>();
            for (int i = 0; i < barCodeArray.size(); i++) {
                JSONObject barCodeObj = barCodeArray.getJSONObject(i);
                String barCode = barCodeObj.getString("barCode");
                barCodeList.add(barCode);
            }

            // 查询商品信息
            List<MaterialVo4Unit> materialList = materialService.getMaterialByBarCode(barCodeList);
            if (materialList != null && !materialList.isEmpty()) {
                result.put("code", 0);
                for (MaterialVo4Unit material : materialList) {
                    JSONObject item = new JSONObject();
                    item.put("barCode", material.getmBarCode());
                    item.put("systemSku", material.getSystemSku());
                    dataArray.add(item);
                }
            } else {
                result.put("code", 1);
                result.put("msg", "未找到对应商品信息");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "系统异常，请稍后重试");
        }

        // 将数据数组放入返回结果
        result.put("data", dataArray);
        logger.info("  result:{}", param);
        return result.toJSONString();
    }

    /**
     *
     集采下单成功->封装同步erp销售订单请求体

     {
     orderSn:"订单编号"，
     customer:{//客户信息
     name:"客户名称",
     contact:"客户联系方式",
     address:"客户地址"
     },
     item:[{//订单商品信息
     erp_sku:"erp_sku编号",
     unitPrice:"商品单价",
     quantity:"商品下单数量",
     price:"商品实付价格"
     }]
     }

     * @param param
     * @return
     */
    public String syncOrder(String param) {
        logger.info("同步集采订单-》销售订单 param:{}", param);
        JSONObject result = new JSONObject();
        try {
            // 解析传入的JSON参数
            JSONObject paramJson = JSONObject.parseObject(param);
            if (paramJson == null || paramJson.isEmpty()) {
                result.put("code", 1);
                result.put("msg", "参数不能为空");
                return result.toJSONString();
            }

            // 校验订单编号
            String orderSn = paramJson.getString("orderSn");
            if (orderSn == null || orderSn.isEmpty()) {
                result.put("code", 1);
                result.put("msg", "订单编号不能为空");
                return result.toJSONString();
            }

            // 校验客户信息
            JSONObject customer = paramJson.getJSONObject("customer");
            if (customer == null || customer.isEmpty()) {
                result.put("code", 1);
                result.put("msg", "客户信息不能为空");
                return result.toJSONString();
            }

            // 校验订单商品信息
            JSONArray itemArray = paramJson.getJSONArray("item");
            if (itemArray == null || itemArray.isEmpty()) {
                result.put("code", 1);
                result.put("msg", "订单商品信息不能为空");
                return result.toJSONString();
            }

            buildOrderAndItem(paramJson, itemArray);

            // 返回成功结果
            result.put("code", 0);
            result.put("msg", "订单同步成功");
        } catch (Exception e) {
            logger.error("同步订单发生异常", e);
            result.put("code", 1);
            result.put("msg", "系统异常，请稍后重试");
        }
        return result.toJSONString();
    }

    private void buildOrderAndItem(JSONObject orderJson, JSONArray itemJsonArray) throws Exception {
        DepotHeadXsddRequestVO order = new DepotHeadXsddRequestVO();
        order.setType("其他");
        order.setSubType("销售订单");
        String orderSn = orderJson.getString("orderSn");

        String number = sequenceService.buildOnlyNumber();
        String defaultNumber = "XSDD" + number;
        order.setDefaultNumber(defaultNumber);
        order.setNumber(defaultNumber);
        order.setCreateTime(new Date());
        order.setOperTime(new Date());
        order.setOrganId(1L);// 供应商
        order.setCreator(1L);// 创建人
        order.setAccountId(1L);// 账户
        order.setChangeAmount(BigDecimal.ZERO);
        order.setBackAmount(BigDecimal.ZERO);
        order.setTotalPrice(orderJson.getBigDecimal("totalPrice"));
        order.setPayType("现付");
        order.setDiscount(BigDecimal.ZERO);
        order.setDiscountMoney(BigDecimal.ZERO);
        order.setDiscountLastMoney(orderJson.getBigDecimal("totalPrice"));
        order.setStatus("0");
        order.setPurchaseStatus("0");
        order.setSource("2");// 来源集采商城
        order.setTenantId(null);
        order.setDeleteFlag("0");

        List<DepotItemXsddRequestVO> itemList = new ArrayList<>();

        List<String> systemSkuList = itemJsonArray.stream().map(JSONObject.class::cast).map(json -> json.getString("erp_sku")).collect(Collectors.toList());

        Map<String, JSONObject> skuToJsonMap = itemJsonArray.stream().map(JSONObject.class::cast).collect(Collectors.toMap(json -> json.getString("erp_sku"), json -> json));

        List<MaterialVo4Unit> materialList = materialService.getMaterialBySystemSku(systemSkuList);

        Map<String, List<MaterialVo4Unit>> skuToMaterialMap = materialList.stream().collect(Collectors.groupingBy(MaterialVo4Unit::getSystemSku));

        for (Map.Entry<String, JSONObject> entry : skuToJsonMap.entrySet()) {
            String erpSku = entry.getKey(); // 获取 erp_sku
            JSONObject itemJson = entry.getValue(); // 获取对应的 JSONObject

            Integer quantity = itemJson.getInteger("quantity");
            BigDecimal unitPrice = itemJson.getBigDecimal("unitPrice");
            BigDecimal price = itemJson.getBigDecimal("price");

            if (quantity == null || unitPrice == null || price == null) {
                logger.warn("商品信息不完整，erp_sku: {}", erpSku);
                continue;
            }

            List<MaterialVo4Unit> materials = skuToMaterialMap.get(erpSku);

            if (materials != null && !materials.isEmpty()) {
                BigDecimal remainingQuantity = itemJson.getBigDecimal("quantity"); // 剩余数量
                for (MaterialVo4Unit material : materials) {
                    BigDecimal inventory = material.getInventory(); // 当前商品库存
                    if (inventory.compareTo(BigDecimal.ZERO) <= 0) {
                        continue; // 如果库存为0，跳过
                    }

                    DepotItemXsddRequestVO item = new DepotItemXsddRequestVO();
                    item.setHeaderId(order.getId());
                    item.setMaterialId(material.getId());
                    item.setMaterialExtendId(material.getMeId());
                    item.setMaterialUnit(material.getUnit());
                    item.setSku(material.getSku());
                    item.setDepotId(material.getDepotId());
                    item.setTaxRate(BigDecimal.ONE);
                    item.setTaxMoney(BigDecimal.ZERO);
                    item.setBatchNumber("");
                    item.setUnitPrice(unitPrice); // 设置单价
                    if (inventory.compareTo(remainingQuantity) >= 0) {
                        // 如果当前商品库存大于等于剩余数量，直接使用剩余数量
                        item.setOperNumber(remainingQuantity);
                        // 计算实付价格：单价 × 剩余数量
                        BigDecimal taxLastMoney = itemJson.getBigDecimal("unitPrice").multiply(remainingQuantity);
                        item.setTaxLastMoney(taxLastMoney);
                        item.setAllPrice(taxLastMoney);
                        itemList.add(item);
                        break; // 结束循环
                    } else {
                        // 如果当前商品库存小于剩余数量，使用当前商品库存
                        item.setOperNumber(inventory);
                        // 计算实付价格：单价 × 剩余数量
                        BigDecimal taxLastMoney = itemJson.getBigDecimal("unitPrice").multiply(remainingQuantity);
                        item.setTaxLastMoney(taxLastMoney);
                        item.setAllPrice(taxLastMoney);
                        itemList.add(item);
                        remainingQuantity = remainingQuantity.subtract(inventory); // 减少剩余数量
                    }
                }
            } else {
                // 如果未找到对应的 MaterialVo4Unit，可以记录日志或处理异常
                logger.warn("未找到 erp_sku: {} 对应的商品信息", erpSku);
            }
        }
        depotHeadService.syncOrderToXsdd(order, itemList);
    }




}