package com.malk.zhiwei.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import com.malk.zhiwei.service.ZwService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.rmi.CORBA.Util;
import java.util.*;

@Service
@Slf4j
public class ZwServiceImpl implements ZwService {

    private static String ERP_URL="http://10.0.0.208:80";
    private static String ERP_NAME="064";
    private static String ERP_PASSWORD="";
    private static String ERP_PILOT="PILOT2001";

    // http://10.0.0.208:30104/MobileService.asmx?op=GETPILOTLIST
    // {"PILOTLIST":[
    // {"NAME":"PILOT2001","ZTNAME":"2001测试"},
    // {"NAME":"PILOT2002","ZTNAME":"2002CS-BYD"},
    // {"NAME":"PILOT2023","ZTNAME":"20232023"},
    // {"NAME":"PILOT2024","ZTNAME":"20242024"}]}
    private static String ERP_LOGIN_KEY="2025062710430311152101098";

    private static String ERP_OP_PRODUCT="Anyv_View_PRODUCT";
    private static String ERP_OP_PRODCLAS="Anyv_View_PRODCLAS";
    private static String ERP_OP_CUSTOMER="Anyv_View_CUSTOMER";

    public static void main(String[] args) {
        // {"CODE":"CP000201","clasName":"成品","CNAME":"MPP-20P","SPEC":"600*500*1.8±0.3"},{"CODE":"CP000809","clasName":"成品","CNAME":"阻燃MPP-25P-灰色","SPEC":"1400*1100*3+1-0.5"},{"CODE":"CP001362","clasName":"成品","CNAME":"阻燃MPP-15P","SPEC":"2480*222*3.5±0.2"},{"CODE":"TCP000023","clasName":"成品","CNAME":"POE05灰(李宁)","SPEC":"1850*800*6"}
        JSONObject jsonObject = queryData(ERP_OP_PRODUCT,"clasName = '成品'",ERP_PILOT);
        // {"CODE":"KH0681","CNAME":"耐玛体育","ABBR":"耐玛体育"},{"CODE":"KH0022","CNAME":"上海浩魁材料科技有限公司","ABBR":"浩魁"}
//        JSONObject jsonObject = queryData(ERP_OP_CUSTOMER,"");
//        saveSaleOrder("{\"CODE\":\"KH0681\",\"SUPP\":\"KH0681\",\"STAFFCODE\":\"admin\",\"VERIFICATION\":\"False\",\"PRODLIST\":[{\"ERI\":\"0GZ29ZUKV401HCBI\",\"CODE\":\"O220902002\",\"CODE1\":\"\",\"PROD\":\"CP000201\",\"GWN\":\"WXYL\",\"VPNO\":\"X220703\",\"QTY\":1,\"confirm\":0}]}");

//        saveDeliveryOrder("{\"CODE\":\"KH0681\",\"STAFFCODE\":\"admin\",\"VERIFICATION\":\"False\",\"PRODLIST\":[{\"ERI\":\"\",\"CODE\":\"O250627010\",\"PROD\":\"CP000201\",\"GWN\":\"WXYL\",\"VPNO\":\"X220703\",\"QTY\":1,\"confirm\":0}]}");
    }

    private static String erpLogin(String erpPilot){
        String xmlResponse=HttpUtil.get(ERP_URL+"/MobileService.asmx/login?name="+ERP_NAME+"&password="+ERP_PASSWORD+"&pilot="+erpPilot);
        int jsonStart = xmlResponse.indexOf("{");
        int jsonEnd = xmlResponse.lastIndexOf("}");
        String jsonStr = xmlResponse.substring(jsonStart, jsonEnd + 1);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        log.info("登录结果：{}",jsonObject);
        return jsonObject.getJSONObject("USER").getString("Key");
    }

    private static JSONObject queryData(String op,String where,String erpPilot){
        String xmlResponse=HttpUtil.get(ERP_URL+"/MobileService.asmx/"+op+"?KEY="+erpLogin(erpPilot)+"&field=&userid="+ERP_NAME+"&where="+where+"&pilot="+erpPilot);
        int jsonStart = xmlResponse.indexOf("{");
        int jsonEnd = xmlResponse.lastIndexOf("}");
        String jsonStr = xmlResponse.substring(jsonStart, jsonEnd + 1);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        log.info("查询结果：{}",jsonObject);
        return jsonObject;
    }

    private static JSONObject saveSaleOrder(String data,String erpPilot){
        String xmlResponse=HttpUtil.get(ERP_URL+"/MobileService.asmx/Anyv_GenForm_ORDCORD1?KEY="+erpLogin(erpPilot)+"&userid="+ERP_NAME+"&Data="+data+"&pilot="+erpPilot);
        System.out.println(xmlResponse);
        int jsonStart = xmlResponse.indexOf("{");
        int jsonEnd = xmlResponse.lastIndexOf("}");
        String jsonStr = xmlResponse.substring(jsonStart, jsonEnd + 1);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        log.info("保存结果：{}",jsonObject);
        return jsonObject;
    }

    @Override
    public JSONObject saveSaleOrder(Map formData) {
        // 数据转换
        JSONObject dataObj = new JSONObject();
        dataObj.put("CODE", UtilMap.getString(formData,"textField_mcefftni"));// 单号
        dataObj.put("SUPP",UtilMap.getString(formData,"textField_mcefftni"));// 客户代码
        dataObj.put("STAFFCODE",UtilMap.getString(formData,"textField_mcefftnj"));
        dataObj.put("VERIFICATION","False");
        List<Map> list=UtilMap.getList(formData,"tableField_mcefftnk");
        List<Map> dataList=new ArrayList<>();
        for (Map map : list) {
            Map tempMap=new HashMap();
            tempMap.put("ERI",""); // 销售订单副档ERI或出货通知单副档ERI
            tempMap.put("CODE", UtilMap.getString(map,"textField_mcefftnl")); // 销售订单编号
            tempMap.put("CODE1", "");// 出货通知单编号
            tempMap.put("PROD", UtilMap.getString(map,"textField_mcefftnn"));// 产品代码
            tempMap.put("GWN", UtilMap.getString(map,"textField_mcefftno"));// 仓库代码
            tempMap.put("VPNO", UtilMap.getString(map,"textField_mcefftnp"));// 产品批号
            tempMap.put("QTY", UtilMap.getString(map,"numberField_mcefftnr"));// 产品数量
            tempMap.put("confirm", "0");
            dataList.add(tempMap);
        }
        dataObj.put("PRODLIST",dataList);
        String data=JSONObject.toJSONString(dataObj);
        log.info("入参：{}",data);
        // 调用接口
        JSONObject result=saveSaleOrder(UtilMap.getString(formData,"textField_mcefftni"),UtilMap.getString(formData,"textField_mdr1v1di"));
        JSONArray codes=result.getJSONArray("page");
        for (int i = 0; i < list.size(); i++) {
            Map tempMap=new HashMap();
            tempMap.put("textField_mdqsatd4",UtilMap.getString(list.get(i),"textField_mdqs9oqa"));
            tempMap.put("textField_mdwpe4m6","合同");
            if(codes.size() >= i){
                tempMap.put("textField_mdqsatd5",codes.getJSONObject(i).getString("CODE"));
            }
            ydClient.operateData(YDParam.builder().formUuid("FORM-E999482BC03547D89A435F5441A46F1ANR0R").formDataJson(JSONObject.toJSONString(tempMap)).build(), YDConf.FORM_OPERATION.create);
        }
        return result;
    }

    private static JSONObject saveDeliveryOrder(String data,String erpPilot){
        String xmlResponse=HttpUtil.get(ERP_URL+"/MobileService.asmx/Anyv_GenForm_STKSHIPNOTE1?KEY="+erpLogin(erpPilot)+"&userid="+ERP_NAME+"&Data="+data+"&pilot="+erpPilot);
        System.out.println(xmlResponse);
        int jsonStart = xmlResponse.indexOf("{");
        int jsonEnd = xmlResponse.lastIndexOf("}");
        String jsonStr = xmlResponse.substring(jsonStart, jsonEnd + 1);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        log.info("保存结果：{}",jsonObject);
        return jsonObject;
    }

    @Override
    public JSONObject saveDeliveryOrder(Map formData) {
        // 数据转换
        JSONObject dataObj = new JSONObject();
        dataObj.put("CODE", UtilMap.getString(formData,"textField_mcefftni"));// 客户代码
        dataObj.put("STAFFCODE",UtilMap.getString(formData,"textField_mcefftnj"));
        dataObj.put("VERIFICATION","False");
        List<Map> list=UtilMap.getList(formData,"tableField_mcefftnk");
        List<Map> dataList=new ArrayList<>();
        for (Map map : list) {
            Map tempMap=new HashMap();
            tempMap.put("ERI",""); // 销售订单副档ERI或出货通知单副档ERI
            tempMap.put("CODE", UtilMap.getString(map,"textField_mcefftnl")); // 销售订单编号
            tempMap.put("PROD", UtilMap.getString(map,"textField_mcefftnn"));// 产品代码
            tempMap.put("GWN", UtilMap.getString(map,"textField_mcefftno"));// 仓库代码
            tempMap.put("VPNO", UtilMap.getString(map,"textField_mcefftnp"));// 产品批号
            tempMap.put("QTY", UtilMap.getString(map,"numberField_mcefftnr"));// 产品数量
            tempMap.put("confirm", "0");
            dataList.add(tempMap);
        }
        dataObj.put("PRODLIST",dataList);
        String data=JSONObject.toJSONString(dataObj);
        log.info("入参：{}",data);
        JSONObject result=saveDeliveryOrder(data,UtilMap.getString(formData,"textField_mdr1v1di"));
        JSONArray codes=result.getJSONArray("page");
        for (int i = 0; i < list.size(); i++) {
            Map tempMap=new HashMap();
            tempMap.put("textField_mdqsatd4",UtilMap.getString(list.get(i),"textField_mdqs9oqa"));
            tempMap.put("textField_mdwpe4m6","发货");
            tempMap.put("textField_mdwpe4m7",UtilMap.getString(formData,"textField_mdwqclqh"));
            if(codes.size() >= i){
                tempMap.put("textField_mdqsatd5",codes.getJSONObject(i).getString("CODE"));
            }
            ydClient.operateData(YDParam.builder().formUuid("FORM-E999482BC03547D89A435F5441A46F1ANR0R").formDataJson(JSONObject.toJSONString(tempMap)).build(), YDConf.FORM_OPERATION.create);
        }
        return result;
        // 调用接口
    }

    @Autowired
    private YDClient ydClient;

    @Override
    public void syncProduct(String id,String erpPilot) {
        JSONObject jsonObject = queryData(ERP_OP_PRODUCT,"clasName = '成品'"+ (PublicUtil.isNull(id)?"":("and CODE = '"+id+"'")),erpPilot);
        JSONArray data = jsonObject.getJSONArray("data");
        log.info("data.size()：{}",data.size());
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObj = data.getJSONObject(i);
            String productId=UtilMap.getString(dataObj,"CODE");
            Map saveMap=UtilMap.map("textField_mcijetil, textField_l43jpnsf, textField_l43jpnsh",productId,dataObj.getString("CNAME"),dataObj.getString("SPEC"));
            ydClient.operateData(YDParam.builder().formUuid("FORM-4A7B1A62CCFC4D758AB98ADE3F97D40COYO2")
                    .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mcijetil", productId)))
                    .formDataJson(JSONObject.toJSONString(saveMap)).build(), YDConf.FORM_OPERATION.upsert);
        }
    }
}
