package com.yem;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.WSContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.CodeEdit;
import kd.bos.form.control.events.UploadEvent;
import kd.bos.form.control.events.UploadListener;
import kd.bos.form.plugin.AbstractFormPlugin;

import java.text.SimpleDateFormat;
import java.util.*;

import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPHeaderElement;

import javax.xml.namespace.QName;

public class ImportOrder extends AbstractFormPlugin implements UploadListener {
    private final static String KEY_ATTACHMENTPANEL1 = "yem_attachmentpanelap";

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btnok");
        AttachmentPanel attachmentPanel = this.getView().getControl(KEY_ATTACHMENTPANEL1);
        attachmentPanel.addUploadListener(this);

    }
    @Override
    public void upload(UploadEvent evt) {
        List<String> fileUrls = new ArrayList<>();

        for(Object url : evt.getUrls()){
            fileUrls.add((String) ((Map<String,Object>)url).get("url"));
        }

        // 从临时目录，读取已上传文件内容
        for(String fileUrl : fileUrls){
//            String text = this.loadTextFileString(fileUrl);
//            CodeEdit codeEdit = this.getView().getControl(KEY_CODEEDIT1);
//            codeEdit.setText(text);
            System.out.println("1");
        }

    }

    @Override
    public void afterUpload(UploadEvent evt) {
        UploadListener.super.afterUpload(evt);
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = getJSON();
        jsonArray.add(json);

//        String service = getService(jsonArray.toJSONString());
//        System.out.println("同步数据" + service);
//        JSONObject parse = (JSONObject)JSON.parse(service);
//        System.out.println();
    }

    private JSONObject getJSON() {
        JSONObject json = new JSONObject();
        json.put("number", new Date().getTime());// 单据编号
        json.put("bizDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//业务日期
        json.put("bizType", setJson("number", "310"));//业务类型固定值 310
        json.put("issueCompanyOrgUnit", setJson("number", "010100"));// 供应财务组织
        json.put("issueStorageOrgUnit", setJson("number", "010101"));//供应库存组织
        json.put("receiptCompanyOrgUnit", setJson("number", "010163"));// 需求财务组织

        json.put("receiptStorageOrgUnit", setJson("number", "010163"));//需求库存组织
        json.put("currency", setJson("number", "BB01"));//币别
        json.put("exchangeRate", 1);//汇率
        json.put("isInTax", false);//是否含税
        json.put("bizDirection", 1);//业务方向
        JSONArray entry = getEntry();
        json.put("entry", entry);
        return json;
    }

    private JSONArray getEntry() {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("material", setJson("number", "TCS471B200002"));//物料
        json.put("unit", setJson("number", "PCS"));// 计量单位
        json.put("qty", 1);// 数量
        json.put("receiptPlanDate", "2023-08-21");//计划调入日期
        json.put("price", 1.000000);// 单价
        json.put("amount", 1.00);// 金额
        json.put("isPresent", true);// 赠品
        json.put("taxRate", 0.00);// 税率
        json.put("tax", 0.00);// 税额
        json.put("taxPrice", 1.000000);//  含税单价
        json.put("taxAmount", 1.00);// 价税合计
        json.put("issueStorageOrgUnit", setJson("number", "010101"));// 发货库存组织
        json.put("issueSaleOrgUnit", setJson("number", "010163"));//  发货方销售组织
        json.put("receiveStorageOrgUnit", setJson("number", "010101"));//  收货库存组织

        json.put("actualPrice", 1.000000);// 实际单价
        json.put("actualTaxPrice", 1.000000);// 实际含税单价
        json.put("notControlQty", true);// “不控制数量”默认为选中
        json.put("issuePlanDate", "2023-08-23");// 计划调出日期
        jsonArray.add(json);

        return jsonArray;
    }

    public String getService(String json) {
        String aa = null;
        DynamicObject connObj = QueryServiceHelper.queryOne("isc_database_link", "server_ip,server_port,data_center,user,newpwd,http_protocal", new QFilter[]{new QFilter("number", QCP.equals, "eas")});
        if (connObj == null) {
            throw new KDException("未获取到EAS链接配置，请联系系统管理员");
        } else {
            String server_ip = connObj.getString("server_ip");
            String server_port = connObj.getString("server_port");
            String http_protocal = connObj.getString("http_protocal");
            String data_center = connObj.getString("data_center");
            String user = connObj.getString("user");
            String newpwd = connObj.getString("newpwd");


            try {
                Service s = new Service();
                Call call = (Call) s.createCall();

                call.setOperationName("login");
                call.setTargetEndpointAddress(http_protocal + "://" + server_ip + ":" + server_port + "/ormrpc/services/EASLogin?wsdl");
                call.setReturnType(new QName("urn:client", "WSContext"));
                call.setReturnClass(WSContext.class);

                call.setReturnQName(new QName("", "loginReturn"));
                //超时
                call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
                call.setMaintainSession(true);

                //登陆接口参数
                WSContext rs = (WSContext) call.invoke(new Object[]{user, newpwd, "eas", data_center, "l2", Integer.valueOf(1)});
                if (rs.getSessionId() == null) {
                    throw new Exception("login fail");
                }
                System.out.println(rs.getSessionId());
                //清理
                call.clearOperation();
                //调用业务接口
                call.setOperationName("importBill");

                call.setTargetEndpointAddress(http_protocal + "://" + server_ip + ":" + server_port + "/ormrpc/services/WSSCMWebServiceFacade?wsdl");//改
//                call.setTargetEndpointAddress(http_protocal + "://" + server_ip + ":" + server_port + "/ormrpc/services/WSSCMWebServiceExtFacade?wsdl");//改
                call.setReturnQName(new QName("", "importBill"));
                call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
                call.setMaintainSession(true);
                //设置登录返回的session在soap头 "http://login.webservice.bos.kingdee.com"是固定的
                SOAPHeaderElement header = new SOAPHeaderElement(http_protocal + "://login.webservice.bos.kingdee.com", "SessionId", rs.getSessionId());
                call.addHeader(header);
                aa = (String) call.invoke(new Object[]{"004", json, 1});

                call.setOperationName("logout");
                call.setTargetEndpointAddress(http_protocal + "://" + server_ip + ":" + server_port + "/ormrpc/services/EASLogin?wsdl");//ip改
                //		call.setReturnType(new QName("urn:client","WSContext"));//改
                //		call.setReturnClass(WSContext.class);//改

                call.setReturnQName(new QName("", "logoutReturn"));//改
                //超时
                call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
                call.setMaintainSession(true);
                //登出接口参数
                call.invoke(new Object[]{user, "eas", data_center, "l2"});//根据实际调整

                System.out.println("登出成功");
                //清理
                call.clearOperation();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.getMessage();
            }
        }
        return aa;
    }


    private JSONObject setJson(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject;
    }
}
