package com.yem.tws.aip;

import com.yem.tws.common1.ApilogUtils;
import com.yem.tws.common1.StringUtils;
//import json.JSONArray;
//import json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.IBillWebApiPlugin;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.api.ApiResult;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.util.*;

/**
 * 同步海关商品编码接口
 *
 * @author zhouc
 */
public class SynHsCode implements IBillWebApiPlugin {

    @Override
    public ApiResult doCustomService(Map<String, Object> params) {
        List<Object> resultlist = Collections.synchronizedList(new ArrayList<>());
        boolean BollISSucces = false;
        String ErrMassage = StringUtils.getEmpty();
        String FID = StringUtils.getEmpty();
        String Hscode = StringUtils.getEmpty();
        JSONObject jsonData = null;
        try {
            jsonData = JSONObject.parseObject(JSONObject.toJSONString(params));
            if (null != jsonData) {
                JSONArray Rows = JSONObject.parseArray(jsonData.getString("jsion"));
                for (int j = 0; j < Rows.size(); j++) {
                    JSONObject RowsData = Rows.getJSONObject(j);
                    Hscode = RowsData.getString("hscode");
                    QFilter filter1 = new QFilter("number", QCP.equals, Hscode);
                    DynamicObject date = BusinessDataServiceHelper.loadSingle("yem_bd_hscode", "id", new QFilter[]{filter1});
                    if (date == null) {
                        DynamicObject bill = BusinessDataServiceHelper.newDynamicObject("yem_bd_hscode");
                        //组织
                        QFilter filter2 = new QFilter("id", QCP.equals, 100000);
                        DynamicObject simpleBill1 = BusinessDataServiceHelper.loadSingle("bos_org", "id,name,number", new QFilter[]{filter2});
                        if (simpleBill1 != null) {
                            bill.set("createorg", simpleBill1);
                            bill.set("useorg", simpleBill1);
                        }
                        bill.set("status", "C");
                        bill.set("enable", "1");
                        bill.set("number", Hscode);
                        bill.set("name", RowsData.getString("cn_name"));
                        bill.set("yem_namecn", RowsData.getString("en_name"));
                        bill.set("yem_note_s", RowsData.getString("note_s"));
                        String unit = RowsData.getString("unit");
                        bill.set("yem_unit", unit);//文本
                        QFilter unitfilter = new QFilter("name", QCP.equals, unit);
                        DynamicObject unitsimpleBill1 = BusinessDataServiceHelper.loadSingle("bd_measureunits", "id,name,number", new QFilter[]{unitfilter});
                        if (simpleBill1 != null) {
                            bill.set("yem_unitbase", unitsimpleBill1);//标准计量单位
                        }
                        DynamicObject hsunitsimpleBill1 = BusinessDataServiceHelper.loadSingle("yem_uom_code_hs", "id,name,number", new QFilter[]{unitfilter});
                        if (simpleBill1 != null) {
                            bill.set("yem_unitbase_hs", hsunitsimpleBill1);//法定第一单位（海关）
                        }
                        String unit2 = RowsData.getString("unit2");
                        bill.set("yem_unit2", unit2);//文本
                        QFilter unit2filter = new QFilter("name", QCP.equals, unit);
                        DynamicObject unit2simpleBill1 = BusinessDataServiceHelper.loadSingle("bd_measureunits", "id,name,number", new QFilter[]{unit2filter});
                        if (simpleBill1 != null) {
                            bill.set("yem_unit2base", unit2simpleBill1);//标准计量单位
                        }
                        DynamicObject hsun2itsimpleBill1 = BusinessDataServiceHelper.loadSingle("yem_uom_code_hs", "id,name,number", new QFilter[]{unit2filter});
                        if (simpleBill1 != null) {
                            bill.set("yem_unit2base_hs", hsun2itsimpleBill1);//法定第二单位（海关）
                        }
                        bill.set("yem_control_ma", RowsData.getString("control_ma"));
                        bill.set("yem_ciq_ma", RowsData.getString("ciq_ma"));
                        bill.set("yem_g_model", RowsData.getString("g_model"));
                        bill.set("yem_g_model_required", RowsData.getString("g_model_required"));
                        bill.set("yem_im_low_rate", RowsData.getIntValue("im_low_rate"));
                        bill.set("yem_im_normal_rate", RowsData.getString("im_normal_rate"));
                        bill.set("yem_im_temp_rate", RowsData.getIntValue("im_temp_rate"));
                        bill.set("yem_im_tax_rate", RowsData.getString("im_tax_rate"));
                        bill.set("yem_im_consume_rate", RowsData.getIntValue("im_consume_rate"));
                        bill.set("yem_ex_return_rate", RowsData.getString("ex_return_rate"));
                        bill.set("yem_ex_normal_rate", RowsData.getIntValue("ex_normal_rate"));
                        bill.set("yem_ex_temp_rate", RowsData.getString("ex_temp_rate"));
                        bill.set("yem_ex_special_rate", RowsData.getIntValue("ex_special_rate"));
                        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                bill.getDynamicObjectType().getName(), new DynamicObject[]{bill},
                                OperateOption.create());
                        if (Operate.isSuccess()) {//保存成功
                            ErrMassage = "同步成功，单据编号为：" + Hscode;
                            BollISSucces = true;
                            FID = bill.getString("id");
                        } else {
                            //保存失败
                            BollISSucces = false;
                            ErrMassage = "海关编码保存失败！";
                        }
                    } else {
                        ErrMassage = "海关编码【" + Hscode + "】,已存在禁止新增！";
                    }
                    ProcessingResult(ErrMassage, BollISSucces, Hscode, FID, jsonData, resultlist);
                }
            } else {
                ErrMassage = "获取到Json为空，获取失败";
                ProcessingResult(ErrMassage, BollISSucces, Hscode, FID, jsonData, resultlist);
            }
        } catch (Exception e) {
            //获取到错误，记录错误日志
            ErrMassage = e.getMessage();
            ProcessingResult(ErrMassage, BollISSucces, Hscode, FID, jsonData, resultlist);
        }
        return ApiResult.success(resultlist);
    }

    public void ProcessingResult(String ErrMassage, boolean BollISSucces, String Hscode, String FID, JSONObject jsonData, List<Object> resultlist) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("description", ErrMassage);
        resultMap.put("result", BollISSucces);
        resultMap.put("billno", Hscode);
        resultMap.put("FID", FID);
        resultlist.add(resultMap);
        String opdesc = "同步海关编码之ERP系统";
        ApilogUtils.Createlog(resultMap, Hscode, "单一窗口报关单", opdesc, "AddHsCode", jsonData);
    }
}
