package com.hw.jindie.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hw.common.core.utils.DateUtils;
import com.hw.common.core.utils.StringUtils;
import com.hw.jindie.domain.MesBaseMaterialInfo;
import com.hw.jindie.mapper.MesBaseMaterialInfoMapper;
import com.hw.jindie.service.IKingdeeErpSyncService;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @Description: 与金蝶ERP交互业务处理类
 * @ClassName: KingdeeErpSyncServiceImpl
 * @Author : xins
 * @Date :2024-01-08  14:38
 * @Version :1.0
 */
@Service
public class KingdeeErpSyncServiceImpl implements IKingdeeErpSyncService {
    @Autowired
    private MesBaseMaterialInfoMapper mesBaseMaterialInfoMapper;


    /**
     * @throws Exception
     * @Description:从金蝶ERP同步供应商信息
     */
    public static void syncSupplierInfoFromErp() throws Exception {
        K3CloudApi api = new K3CloudApi();
        //        "FormId": "BD_Supplier",
//                "FieldKeys": "FNumber ,FName,FCreateDate,FModifyDate,FAuditDate",
//                "FilterString": "FDocumentStatus='C' AND FCreateDate>'2022-01-01' ",
        JSONObject queryJson = new JSONObject();
        String formId = "BD_Supplier";
        String fieldKeys = "FSupplierId,FNumber,FName,FCreateDate,FModifyDate,FAuditDate";
        String orderString = "";
        int topRowCount = 0;
        int startRow = 0;
        int limit = 2000;
        queryJson.put("FormId", formId);
        queryJson.put("FieldKeys", fieldKeys);
        queryJson.put("OrderString", orderString);
        queryJson.put("TopRowCount", topRowCount);
        queryJson.put("StartRow", startRow);
        queryJson.put("Limit", limit);
        queryJson.put("SubSystemId", "");
        System.out.println(queryJson.toString());

//        "FieldKeys": "FNumber,FName,FBaseUnitId,FSpecification,FNETWEIGHT,FGROSSWEIGHT,FCreateDate,FModifyDate,FApproveDate",
//        "FilterString": "FDocumentStatus='C' AND FCreateDate>'2022-01-01' and FMaterialGroup.FNUMBER IN ('28')",


        String result = api.billQuery(queryJson.toString());
        JSONArray resultArray = JSONArray.parseArray(result);
        System.out.println(resultArray.size());
        System.out.println("供应商查询接口: " + result);
    }


    /**
     * @throws Exception
     * @Description:从金蝶ERP同步物料信息
     */
    @Override
    public int syncMaterialInfoFromErp() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String FDocumentStatus = "C";

        JSONObject queryJson = new JSONObject();
        String formId = "BD_Material";
        String fieldKeys = "FMaterialId,FNumber,FName,FBaseUnitId,FSpecification,FNETWEIGHT,FGROSSWEIGHT," +
                "FCreateDate,FModifyDate,FApproveDate,FCreateOrgId,FUseOrgId";
//        String filterString = "FNumber='98010102'";
        String filterString = "";
        String orderString = "";
        int topRowCount = 0;
        int startRow = 0;
        int limit = 23;
        queryJson.put("FormId", formId);
        queryJson.put("FieldKeys", fieldKeys);
        queryJson.put("FilterString", filterString);
        queryJson.put("OrderString", orderString);
        queryJson.put("TopRowCount", topRowCount);
        queryJson.put("StartRow", startRow);
        queryJson.put("Limit", limit);
        queryJson.put("SubSystemId", "");
        System.out.println(queryJson.toString());


        String result = api.billQuery(queryJson.toString());
        JSONArray resultArray = JSONArray.parseArray(result);
        System.out.println("物料单据查询接口: " + result);

        for (int i = 0; i < resultArray.size(); i++) {
            try {
                JSONObject resultObject = (JSONObject) resultArray.get(i);
                MesBaseMaterialInfo mesBaseMaterialInfo = new MesBaseMaterialInfo();
                Integer erpId = (Integer) resultObject.get("FMaterialId");
                String materialCode = (String) resultObject.get("FNumber");
                String materialName = (String) resultObject.get("FName");
                Integer materaialUnitId = resultObject.get("FBaseUnitId") == null ? null : (Integer) resultObject.get("FBaseUnitId");
                String materialSpec = resultObject.get("FSpecification") == null ? null : (String) resultObject.get("FSpecification");
                BigDecimal netWeight = resultObject.get("FNETWEIGHT") == null ? null : (BigDecimal) resultObject.get("FNETWEIGHT");
                BigDecimal grossWeight = resultObject.get("FGROSSWEIGHT") == null ? null : (BigDecimal) resultObject.get("FGROSSWEIGHT");
                String createDateStr = resultObject.get("FCreateDate") == null ? null : (String) resultObject.get("FCreateDate");
                String modifyDateStr = resultObject.get("FModifyDate") == null ? null : (String) resultObject.get("FModifyDate");
                String approveDateStr = resultObject.get("FApproveDate") == null ? null : (String) resultObject.get("FApproveDate");
                Integer createOrgId = resultObject.get("FCreateOrgId") == null ? null : (Integer) resultObject.get("FCreateOrgId");
                Integer useOrgId = resultObject.get("FUseOrgId") == null ? null : (Integer) resultObject.get("FUseOrgId");


//            2023-08-26T16:15:15.05

                mesBaseMaterialInfo.setErpId(Long.valueOf(erpId));
                mesBaseMaterialInfo.setMaterialCode(materialCode);
                mesBaseMaterialInfo.setMaterialName(materialName);
                mesBaseMaterialInfo.setMaterialUnitId(Long.valueOf(materaialUnitId));
                mesBaseMaterialInfo.setMaterialSpec(materialSpec);
                mesBaseMaterialInfo.setNetWeight(netWeight);
                mesBaseMaterialInfo.setGrossWeight(grossWeight);
                mesBaseMaterialInfo.setCreateOrgId(Long.valueOf(createOrgId));
                mesBaseMaterialInfo.setUseOrgId(Long.valueOf(useOrgId));

                if (StringUtils.isNotEmpty(createDateStr)) {
                    createDateStr = createDateStr.replace("T", " ");
                    Date createDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", createDateStr);
                    mesBaseMaterialInfo.setCreateTime(createDate);
                }

                if (StringUtils.isNotEmpty(modifyDateStr)) {
                    modifyDateStr = modifyDateStr.replace("T", " ");
                    Date modifyDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", modifyDateStr);
                    mesBaseMaterialInfo.setErpModifyDate(modifyDate);
                }

                if (StringUtils.isNotEmpty(approveDateStr)) {
                    approveDateStr = approveDateStr.replace("T", " ");
                    Date approveDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", approveDateStr);
                    mesBaseMaterialInfo.setApproveDate(approveDate);
                }

                mesBaseMaterialInfoMapper.insertMesBaseMaterialInfo(mesBaseMaterialInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        System.out.println(resultArray.size());


        return 1;
    }


    /**
     * @throws Exception
     * @Descrption：从金蝶ERP同步销售订单
     */
    public static void syncSaleOrderFromErp() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String FDocumentStatus = "C";
        String json = "{\n" +
                "    \"FormId\": \"SAL_SaleOrder\",\n" +
                "    \"FieldKeys\": \"FID,FBillNo,FApproveDate,FSaleOrderEntry_FEntryID,FMaterialId.FNumber,FMaterialName,FQty ,FMinPlanDeliveryDate,\",\n" +
//               "    \"FilterString\": \"FDocumentStatus=\'" + FDocumentStatus + "\' and FMaterialGroup.FNUMBER IN ('28') \",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";

        JSONObject queryJson = new JSONObject();
        String formId = "SAL_SaleOrder";
        String fieldKeys = "FID,FBillNo,FApproveDate,FSaleOrderEntry_FEntryID,FMaterialId.FNumber,FMaterialName,FQty,FModifyDate,FMinPlanDeliveryDate";
        String filterString = "FNumber='98010102'";
        String orderString = "";
        int topRowCount = 0;
        int startRow = 0;
        int limit = 2000;
        queryJson.put("FormId", formId);
        queryJson.put("FieldKeys", fieldKeys);
        queryJson.put("FilterString", filterString);
        queryJson.put("OrderString", orderString);
        queryJson.put("TopRowCount", topRowCount);
        queryJson.put("StartRow", startRow);
        queryJson.put("Limit", limit);
        queryJson.put("SubSystemId", "");
        System.out.println(queryJson.toString());

        String result = api.billQuery(queryJson.toString());
        JSONArray resultArray = JSONArray.parseArray(result);
        System.out.println(resultArray.size());
        System.out.println("销售订单单据查询接口: " + result);
    }


    /**
     * @throws Exception
     * @Descrption：从金蝶ERP同步项目信息
     */
    public static void syncProjectInfoFromErp() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String FDocumentStatus = "C";


        JSONObject queryJson = new JSONObject();
        String formId = "TOND_ProjectFile";
        String fieldKeys = "FID,FNumber,FName,FPlanDate,FDocumentStatus,FForbidStatus,FCreateDate,FModifyDate,FAuditDate";
        String filterString = "";
        String orderString = "";
        int topRowCount = 0;
        int startRow = 0;
        int limit = 2;
        queryJson.put("FormId", formId);
        queryJson.put("FieldKeys", fieldKeys);
        queryJson.put("FilterString", filterString);
        queryJson.put("OrderString", orderString);
        queryJson.put("TopRowCount", topRowCount);
        queryJson.put("StartRow", startRow);
        queryJson.put("Limit", limit);
        queryJson.put("SubSystemId", "");
        System.out.println(queryJson.toString());

        String result = api.billQuery(queryJson.toString());
        JSONArray resultArray = JSONArray.parseArray(result);
        System.out.println(resultArray.size());
        System.out.println("项目信息单据查询接口: " + result);
    }

    /**
     * @throws Exception
     * @Descrption：从金蝶ERP同步采购订单
     */
    public static void syncPurchaseOrderFromErp() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String FDocumentStatus = "C";


        JSONObject queryJson = new JSONObject();
        String formId = "PUR_PurchaseOrder";
        String fieldKeys = "FID,FBillNo,FApproveDate,FDocumentStatus,FPOOrderEntry_FEntryID,FMaterialId.FNumber,FMaterialId.FName,FQty,FDeliveryDate";
        String filterString = "";
        String orderString = "";
        int topRowCount = 0;
        int startRow = 0;
        int limit = 200;
        queryJson.put("FormId", formId);
        queryJson.put("FieldKeys", fieldKeys);
        queryJson.put("FilterString", filterString);
        queryJson.put("OrderString", orderString);
        queryJson.put("TopRowCount", topRowCount);
        queryJson.put("StartRow", startRow);
        queryJson.put("Limit", limit);
        queryJson.put("SubSystemId", "");
        System.out.println(queryJson.toString());

        String result = api.billQuery(queryJson.toString());
        JSONArray resultArray = JSONArray.parseArray(result);
        System.out.println(resultArray.size());
        System.out.println("采购订单单据查询接口: " + result);
    }

    public static void main(String[] args) throws Exception {
//        syncSupplierInfoFromErp();
//        syncMaterialInfoFromErp();
//        syncSaleOrderFromErp();
//        syncPurchaseOrderFromErp();
//        syncProjectInfoFromErp();
    }

}
