package com.jwipc.order.logic.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResponse;
import com.jwipc.exception.DaoException;
import com.jwipc.order.constant.PoMesClient;
import com.jwipc.order.dto.DeliveryOrderToMesDTO;
import com.jwipc.order.entity.DeliveryOrder;
import com.jwipc.order.entity.DeliveryOrderDetail;
import com.jwipc.order.entity.PurchaseOrder;
import com.jwipc.order.entity.PurchaseOrderDetail;
import com.jwipc.order.logic.DeliveryOrderPushMesLogic;
import com.jwipc.order.service.IPurchaseOrderDetailService;
import com.jwipc.order.service.IPurchaseOrderService;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.dto.LogThirdPartyCallDTO;
import com.jwipc.sys.logic.ThirdLogLogic;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class DeliveryOrderPushMesLogicImpl implements DeliveryOrderPushMesLogic {
    private final PoMesClient poMesClient;
    private final IPurchaseOrderService purchaseOrderService;
    private final IPurchaseOrderDetailService purchaseOrderDetailService;
    private final SupplierClient supplierClient;
    private final ThirdLogLogic thirdLogLogic;

    @Override
    public void processor(List<DeliveryOrderDetail> details, List<DeliveryOrder> deliveryOrders, String state) {
        final PurchaseOrder purchaseOrder = purchaseOrderService.getOne(new LambdaQueryWrapper<PurchaseOrder>()
                .eq(PurchaseOrder::getOrderCode, details.get(0).getPurchaseOrderCode()));//取采购员
        final DeliveryOrderToMesDTO deliveryOrderToMesDTO = new DeliveryOrderToMesDTO();
        final DeliveryOrderToMesDTO.IT_HEAD head = new DeliveryOrderToMesDTO.IT_HEAD();
        List<DeliveryOrderToMesDTO.IT_HEAD_Item> headItems = Lists.newArrayList();
        for (DeliveryOrder deliveryOrder : deliveryOrders) {
            final DeliveryOrderToMesDTO.IT_HEAD_Item itHeadItem = new DeliveryOrderToMesDTO.IT_HEAD_Item();
            itHeadItem.setRCV_NO(deliveryOrder.getOrderCode());//预约单号
            itHeadItem.setVcode(deliveryOrder.getSupplierErpCode());//供应商代码
            itHeadItem.setVname(deliveryOrder.getSupplierName());//供应商名称
            itHeadItem.setBuyer(purchaseOrder.getCreateName());//采购员姓名
            itHeadItem.setDeliveryTime(deliveryOrder.getDeliveryDate());//送货时间（YYMMDD）
            itHeadItem.setDeliveryTimeHH("00");//送货时间（HH）
            itHeadItem.setReceivingAddress(deliveryOrder.getReceiverAddress());
            itHeadItem.setDeliveryMan(deliveryOrder.getOrderCode());//送货人
            itHeadItem.setContract_No(deliveryOrder.getOrderCode());//合同号
            headItems.add(itHeadItem);
        }
        head.setItem(headItems);
        deliveryOrderToMesDTO.setIT_HEAD(head);
        List<DeliveryOrderToMesDTO.IT_ITEM_Item> itLists = Lists.newArrayList();
        final DeliveryOrderToMesDTO.IT_ITEM itItem = new DeliveryOrderToMesDTO.IT_ITEM();

        for (DeliveryOrderDetail detail : details) {
            final PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetailService.getOne(
                    new LambdaQueryWrapper<PurchaseOrderDetail>()
                            .eq(PurchaseOrderDetail::getOrderCode, detail.getPurchaseOrderCode())
                            .eq(PurchaseOrderDetail::getOrderRow, detail.getPurchaseOrderRow()));
            if (Objects.isNull(purchaseOrderDetail)) {
                throw new DaoException(StrUtil.format("采购订单不存在:{}-{}", detail.getPurchaseOrderCode(),
                        detail.getPurchaseOrderRow()));
            }
            final DeliveryOrderToMesDTO.IT_ITEM_Item itItemItem = new DeliveryOrderToMesDTO.IT_ITEM_Item();
            itItemItem.setRCV_NO(detail.getOrderCode());//预约单号
            itItemItem.setPO_No(detail.getPurchaseOrderCode());//采购订单
            itItemItem.setPO_Line(detail.getPurchaseOrderRow());//采购订单行号
            itItemItem.setPartNo(detail.getMaterialCode());//物料代码
            itItemItem.setDescription(detail.getMaterialName());//物料描述
            itItemItem.setMaterialType("");//物料类型
            itItemItem.setUnit(detail.getUnitCode());//单位
            itItemItem.setPrice(detail.getPrice().toString());//单价
            itItemItem.setNeedTime(DateUtils.formatYYYYMMDD(detail.getRequireDate()));//需求时间（YYMMDD）
            itItemItem.setPO_Qty(detail.getPurchaseOrderNum().toString());//采购订单数量
            itItemItem.setRCVD_Qty(purchaseOrderDetail.getReceivedNum());//已交量
            itItemItem.setSHP_Qty(detail.getNum().toString());//本次预约量
            itItemItem.setVendorCode(detail.getSupplierCode());//供应商代码
            final SupplierDTO supplierByCode = supplierClient.getSupplierByCode(detail.getSupplierCode());
            itItemItem.setVendorName(supplierByCode.getSupplierName());//供应商名称
            itItemItem.setReserve1(detail.getOrderRow());//增加了送货单明细的行号传入mes
            itItemItem.setState(state);//状态  if (FlagConst.Y.equals(deleteFlag)) {
            itLists.add(itItemItem);
        }
        itItem.setItem(itLists);
        deliveryOrderToMesDTO.setIT_ITEM(itItem);
        deliveryOrderToMesDTO.getIS_REQ().NOTE1=deliveryOrders.get(0).getFactoryCode();
        final ApiResponse apiResponse = poMesClient.pushDeliveryOrder(deliveryOrderToMesDTO);
        if (!apiResponse.getCode().equals(RestCode.MES_SUCCESS.getCode())) {
            throw new DaoException(StrUtil.format("送货单创建错误:{}", apiResponse.getMsg()));
        }
    }

    @Override
    public void reDeliveryNote(String id) {
        //调用日志记录获取到请求json
        //讲请求json格式化请求投添加几个参数
        //调用请求mes接口
        //记录日志
        LogThirdPartyCallDTO dto = thirdLogLogic.getCallById(id);
        if (ObjectUtil.isNull(dto)){
            throw new DaoException("未查下到送货单日志信息!");
        }
        String infRequestParams = dto.getInfRequestParams();
        JSONObject jsonObject = JSON.parseObject(infRequestParams);
        // 提取 IS_REQ, IT_HEAD, IT_ITEM 对象
        JSONObject isReq = jsonObject.getJSONObject("IS_REQ");
        JSONObject itHead = jsonObject.getJSONObject("IT_HEAD");
        JSONObject itItemData = jsonObject.getJSONObject("IT_ITEM");

        final DeliveryOrderToMesDTO deliveryOrderToMesDTO = new DeliveryOrderToMesDTO();
        final DeliveryOrderToMesDTO.IT_HEAD head = new DeliveryOrderToMesDTO.IT_HEAD();
        List<DeliveryOrderToMesDTO.IT_HEAD_Item> headItems = Lists.newArrayList();
        // 遍历 IT_HEAD 的 item list
        JSONArray itHeadItems = itHead.getJSONArray("item");
        for (int i = 0; i < itHeadItems.size(); i++) {
            final DeliveryOrderToMesDTO.IT_HEAD_Item itHeadItem = new DeliveryOrderToMesDTO.IT_HEAD_Item();
            JSONObject item = itHeadItems.getJSONObject(i);
            itHeadItem.setRCV_NO(item.getString("RCV_NO"));//预约单号
            itHeadItem.setVcode(item.getString("vcode"));//供应商代码
            itHeadItem.setVname(item.getString("vname"));//供应商名称
            itHeadItem.setBuyer(item.getString("buyer"));//采购员姓名
            itHeadItem.setDeliveryTime(item.getString("deliveryTime"));//送货时间（YYMMDD）
            itHeadItem.setDeliveryTimeHH("00");//送货时间（HH）
            itHeadItem.setReceivingAddress(item.getString("receivingAddress"));
            itHeadItem.setDeliveryMan(item.getString("deliveryMan"));//送货人
            itHeadItem.setContract_No(item.getString("contract_No"));//合同号
            headItems.add(itHeadItem);
        }
        head.setItem(headItems);
        deliveryOrderToMesDTO.setIT_HEAD(head);
        List<DeliveryOrderToMesDTO.IT_ITEM_Item> itLists = Lists.newArrayList();
        final DeliveryOrderToMesDTO.IT_ITEM itItem = new DeliveryOrderToMesDTO.IT_ITEM();
        // 遍历 IT_ITEM 的 item list
        JSONArray itItemItems = itItemData.getJSONArray("item");
        for (int i = 0; i < itItemItems.size(); i++) {
            JSONObject item = itItemItems.getJSONObject(i);
            final DeliveryOrderToMesDTO.IT_ITEM_Item itItemItem = new DeliveryOrderToMesDTO.IT_ITEM_Item();
            itItemItem.setRCV_NO(item.getString("RCV_NO"));//预约单号
            itItemItem.setPO_No(item.getString("PO_No"));//采购订单
            itItemItem.setPO_Line(item.getString("PO_Line"));//采购订单行号
            itItemItem.setPartNo(item.getString("partNo"));//物料代码
            itItemItem.setDescription(item.getString("description"));//物料描述
            itItemItem.setMaterialType("materialType");//物料类型
            itItemItem.setUnit(item.getString("unit"));//单位
            itItemItem.setPrice(item.getString("price"));//单价
            itItemItem.setNeedTime(item.getString("needTime"));//需求时间（YYMMDD）
            itItemItem.setPO_Qty(item.getString("PO_Qty"));//采购订单数量
            itItemItem.setRCVD_Qty(item.getString("RCVD_Qty"));//已交量
            itItemItem.setSHP_Qty(item.getString("SHP_Qty"));//本次预约量
            itItemItem.setVendorCode(item.getString("vendorCode"));//供应商代码
            itItemItem.setVendorName(item.getString("vendorName"));//供应商名称
            itItemItem.setReserve1(item.getString("reserve1"));//增加了送货单明细的行号传入mes
            itItemItem.setState(item.getString("state"));//状态  if (FlagConst.Y.equals(deleteFlag)) {
            itLists.add(itItemItem);

        }
        itItem.setItem(itLists);
        deliveryOrderToMesDTO.setIT_ITEM(itItem);
        deliveryOrderToMesDTO.getIS_REQ().NOTE1=isReq.getString("NOTE1");
        final ApiResponse apiResponse = poMesClient.pushDeliveryOrder(deliveryOrderToMesDTO);
        if (!apiResponse.getCode().equals(RestCode.MES_SUCCESS.getCode())) {
            throw new DaoException(StrUtil.format("送货单创建错误:{}", apiResponse.getMsg()));
        }
    }




}