package com.malk.junengtai.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.junengtai.service.PurchaseService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDConf ddConf;

    @Override
    public McR synchronizedArchiveTable(String name,String date) throws JacksonException {
        if(name.equals("组件信息")){
            log.info("开始同步组件信息");
            ComponentInformation(date);
        } else if (name.equals("供应商信息")) {
            log.info("开始同步供应商信息");
            supplierInformation(date);
        }
        return McR.success();
    }

    @Override
    public McR ComponentInformation(String date) throws JacksonException {
        HashMap head = new HashMap();
        head.put("Authorization","ccd9220f-db1d-4aa1-aa1d-8a2c9180f801");

        HashMap<String,Object> body = new HashMap();
        List<Map<String, String>> partsList = new ArrayList<>();

        Map<String, String> part1 = new HashMap<>();
        part1.put("PartNumber", "SSF0009");
        partsList.add(part1);

        body.put("Parts", partsList);

        String dd = UtilHttp.doPost("http://192.168.3.80:10001/api/public/GetAllParts", head, null, body);

        ObjectMapper objectMapper  = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(dd);
        JsonNode partsNode = rootNode.get("parts");
        List<Map<String, String>> List = new ArrayList<>();
        Map<String, Map<String, String>> partsMap = new ConcurrentHashMap<>();
        if (partsNode != null && partsNode.isArray()) {
            for (JsonNode partNode : partsNode) {
                Map<String, String> partData = new HashMap<>();
                partData.put("partNumber", partNode.get("partNumber").asText());
                partData.put("description", partNode.get("description").asText());
                partData.put("unit", partNode.get("unit").asText());
                partData.put("module",partNode.get("module").isNull() ? "" : partNode.get("module").asText());
                partData.put("spec",partNode.get("spec").isNull() ? "" : partNode.get("spec").asText());
                partData.put("mark",partNode.get("mark").isNull() ? "" : partNode.get("mark").asText());
                partData.put("createDate",partNode.get("createDate").isNull() ? "" : partNode.get("createDate").asText());
                List.add(partData);
                partsMap.put(partNode.get("partNumber").asText(), partData);
            }
        }
        System.out.println("\n=== 遍历所有零件 ===个数："+List.size());
        int i = 0;
        for (Map<String, String> part : List) {
            i++;
            System.out.println(i +"/" + List.size() + "   零件编号: " + part.get("partNumber") +
                    ", 描述: " + part.get("description") +
                    ", 单位: " + part.get("unit") +", 型号: " + part.get("module") + ", 规格: " + part.get("spec") + ", 牌号:" + part.get("mark"));

            //传过来的date数据
            if(part.get("createDate").toString().equals(date)){
                //TODO:向宜搭插入数据
                String sc = "textField_logkj6a6, textField_logkj6ai, textField_logkj6aj, textField_mh4k26k6, textField_mh4k26k5, textField_mh4k26k7";//组件号 组件名称 单位 型号 规格 牌号
                String partNumber = part.get("partNumber").toString()!= null?part.get("partNumber").toString():"数据库此字段为空";
                String description = part.get("description").toString()!=null?part.get("description").toString():"数据库此字段为空";
                String unit = part.get("unit").toString()!=null?part.get("unit").toString():"数据库此字段为空";
                String module = part.get("module").toString()!=null?part.get("module").toString():"数据库此字段为空";
                String spec = part.get("spec").toString()!=null?part.get("spec").toString():"数据库此字段为空";
                String mark = part.get("mark").toString()!=null?part.get("mark").toString():"数据库此字段为空";
                List<Map> conditions = Arrays.asList(  YDConf.searchCondition_TextFiled("textField_logkj6a6", part.get("partNumber"), "eq"));
                List<Map> list  = (List<Map>) ydClient.queryData(YDParam.builder()
                                .formUuid("FORM-4D1B011EF0CC4CB8A5272BE0B5C4D073FKK8")
                                .searchCondition(JSONObject.toJSONString(conditions))
                                .build()
                        ,YDConf.FORM_QUERY.retrieve_list).getData();
                Map formData = UtilMap.map(sc,partNumber,description,unit,module,spec,mark);
                if(!list.isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstanceId(UtilMap.getString(list.get(0),"formInstanceId"))
                            .updateFormDataJson(JSONObject.toJSONString(formData))
                            .build(),YDConf.FORM_OPERATION.update);
                }else{
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-4D1B011EF0CC4CB8A5272BE0B5C4D073FKK8")
                            .formDataJson(JSONObject.toJSONString(formData))
                            .build(), YDConf.FORM_OPERATION.create).toString();
                }
            }


        }
        return McR.success();
    }

    @Override
    public McR supplierInformation(String dateString1) throws JacksonException {
        HashMap head = new HashMap();
        head.put("Authorization","ccd9220f-db1d-4aa1-aa1d-8a2c9180f801");

        HashMap<String,Object> body = new HashMap();
        ArrayList<Map<String,String>> partsList = new ArrayList<>();

        HashMap<String, Object> part1 = new HashMap<>();
        part1.put("supplierCode","");
        part1.put("name","");

        body.put("suppliers",partsList);

        String dd = UtilHttp.doPost("http://192.168.3.80:10001/api/public/GetAllSuppliers", head, null, body);

        ObjectMapper objectMapper  = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(dd);
        JsonNode partsNode = rootNode.get("suppliers");
        List<Map<String, String>> List = new ArrayList<>();
        Map<String, Map<String, String>> partsMap = new ConcurrentHashMap<>();
        if (partsNode != null && partsNode.isArray()) {
            for (JsonNode partNode : partsNode) {
                Map<String, String> partData = new HashMap<>();
                partData.put("supplierCode", partNode.get("supplierCode").asText());
                partData.put("name", partNode.get("name").asText());
                partData.put("createDate",partNode.get("createDate").isNull() ? "" : partNode.get("createDate").asText());
                List.add(partData);
                partsMap.put(partNode.get("supplierCode").asText(), partData);
            }
        }
        System.out.println("\n=== 遍历所有供应商 ===个数："+List.size());
        int i = 0;
        for (Map<String, String> part : List) {
            i++;
            System.out.println(i +"/" + List.size() + "   供应商编码: " + part.get("supplierCode") +
                    ", 供应商名称: " + part.get("name"));
            //TODO:向宜搭插入数据
            //传过来的date数据
            if(part.get("createDate").toString().equals(dateString1)){
                String sc = "textField_loggfrvk, textField_loggfrvp";//供应商编码 供应商名称
                String supplierCode = part.get("supplierCode").toString()!= null?part.get("supplierCode").toString():"数据库此字段为空";
                String name = part.get("name").toString()!=null?part.get("name").toString():"数据库此字段为空";
                List<Map> conditions = Arrays.asList(  YDConf.searchCondition_TextFiled("textField_loggfrvk", part.get("supplierCode"), "eq"));
                List<Map> list  = (List<Map>) ydClient.queryData(YDParam.builder()
                                .formUuid("FORM-A9A0154249F940268F7313DDEC33925CFNPI")
                                .searchCondition(JSONObject.toJSONString(conditions))
                                .build()
                        ,YDConf.FORM_QUERY.retrieve_list).getData();
                Map formData = UtilMap.map(sc,supplierCode,name);
                if(!list.isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstanceId(UtilMap.getString(list.get(0),"formInstanceId"))
                            .updateFormDataJson(JSONObject.toJSONString(formData))
                            .build(),YDConf.FORM_OPERATION.update);
                }else{
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-A9A0154249F940268F7313DDEC33925CFNPI")
                            .formDataJson(JSONObject.toJSONString(formData))
                            .build(), YDConf.FORM_OPERATION.create).toString();
                }
            }

        }

        return McR.success();
    }

    @Override
    public McR queryInventory(Map<String,String> boddy) throws JacksonException {
        HashMap header = new HashMap();
        header.put("Authorization","ccd9220f-db1d-4aa1-aa1d-8a2c9180f801");
        HashMap body = new HashMap();
        body.put("PartNumber",boddy.get("PartNumber").toString());
        String dd = UtilHttp.doPost("http://192.168.3.80:10001/api/public/GetPartLocationInfos", header, null, body);

        HashMap map = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(dd);
        JsonNode warehouses = rootNode.path("waresehouses");
        String warehouseName,partLocationName = "";//仓库:warehouseName   库位:partLocationName
        double partLocationBalance;//库存余额:partLocationBalance
        for (JsonNode warehouse : warehouses) {
            warehouseName = warehouse.path("warehouseName").asText();
            JsonNode partLocations = warehouse.path("partLocations");
            for (JsonNode location : partLocations) {
                partLocationName = location.path("partLocationName").asText();
                partLocationBalance = location.path("partLocationBalance").asDouble();
                map.put("warehouseName",warehouseName);
                map.put("partLocationName",partLocationName);
                map.put("partLocationBalance",partLocationBalance);
            }
        }
        return McR.success(map);
    }

    @Override
    public McR purchaseOrder(String instanceId) throws JacksonException {
        Map data = (Map) ydClient.queryData(YDParam.builder().formInstId(instanceId)
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        System.out.println(data);
        HashMap header = new HashMap();
        header.put("Authorization","ccd9220f-db1d-4aa1-aa1d-8a2c9180f801");
        //创建主map
        HashMap purchaseOrder  = new HashMap();
        purchaseOrder.put("PurchaseOrderNumber",data.get("serialNumberField_mk21zzwk").toString());//采购订单编号
        purchaseOrder.put("SupplierCode",data.get("textField_mhd2mu8c").toString());//供应商编码
        purchaseOrder.put("OrderType",data.get("textField_mhd2mu8d").toString());//订单类型
        purchaseOrder.put("Warehouse",data.get("selectField_mhd3jyfb").toString());//仓库
        purchaseOrder.put("BusinessContactOrderNumber","");//采购合同编码
        purchaseOrder.put("OurReference","");//我方联系人
        purchaseOrder.put("GoodsLabel","");//行货物标签（不传）
        purchaseOrder.put("Currency","元");//货币
        // 创建Rows数组
        List<Map<String, Object>> rows = new ArrayList<>();
        List<Map> jsonString = (List<Map>)data.get("tableField_logke6sx");
        for (Map map : jsonString){
            HashMap rowItem = new HashMap();
            rowItem.put("PartNumber",map.get("textField_logkj6au").toString());//组件号

            String purchaseNum = new BigDecimal(map.get("numberField_logke6t1").toString())
                    .setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            rowItem.put("OrderedQuantity",purchaseNum);//采购数量

            String price = new BigDecimal(map.get("numberField_mh9x8r54").toString())
                    .setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            rowItem.put("Price",price);//单价

            rowItem.put("Unit",map.get("selectField_logkj6ak").toString().equals("") ? "" : map.get("selectField_logkj6ak").toString());//单位

            long time = (long)data.get("dateField_loglna5u");
            String utc = convertTimestampToDateString(time, "UTC", "yyyy-MM-dd");
            rowItem.put("RequirementDate",utc);//交货日期

            String vat = new BigDecimal(map.get("numberField_mhj15z8w").toString())
                    .setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            rowItem.put("Vat",vat);

            rows.add(rowItem);
        }
        purchaseOrder.put("Rows", rows);
        System.out.println(purchaseOrder);
        //调用接口
        String dd = UtilHttp.doPost("http://192.168.3.80:10001/api/public/CreatePurchaseOrder", header, null, purchaseOrder);
        System.out.println(dd);
        return McR.success(dd);
    }

    @Override
    public Map pickingList(Map<String,String> boddy) throws JacksonException {
        HashMap header = new HashMap();
        header.put("Authorization","ccd9220f-db1d-4aa1-aa1d-8a2c9180f801");
        HashMap body = new HashMap();
        body.put("PLNumber",boddy.get("PLNumber").toString());
        String dd = UtilHttp.doPost("http://192.168.3.80:10001/api/public/GetPickingListInfos", header, null, body);
        ObjectMapper mapper =new ObjectMapper();
        Map node =mapper.readValue(dd,Map.class);
        System.out.println("返回值："+node);
        return node;
    }

    public  String convertTimestampToDateString(long timestamp, String timeZone, String pattern) {
        // 将时间戳转换为Instant
        Instant instant = Instant.ofEpochMilli(timestamp);
        // 将Instant转换为指定时区的日期
        LocalDate date = instant.atZone(ZoneId.of(timeZone)).toLocalDate();
        date = date.plusDays(1);
        // 创建一个DateTimeFormatter来格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        // 格式化LocalDate为字符串
        String formattedDate = date.format(formatter);
        // 返回格式化后的日期字符串
        return formattedDate;
    }

}
