package com.yem.wm.syn.eas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.RequestEAS;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.entity.validate.ValidationErrorInfo;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 涛
 * @date 2023/10/19
 * 订单产品需求单_整机外购计划-服务插件
 */
public class YemOrderproreqbillWGService   extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(YemOrderproreqbillWGService.class);
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("org");
        fieldKeys.add("yem_contremark");
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("creator");
        fieldKeys.add("yem_materiel");
        fieldKeys.add("yem_unit");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_billtype");
        fieldKeys.add("yem_dept");
        fieldKeys.add("yem_biztype");
        fieldKeys.add("yem_needtype");
        fieldKeys.add("yem_applyinventoryorg");
        fieldKeys.add("yem_remarks1");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_applyuser");
        fieldKeys.add("yem_iseas");
        fieldKeys.add("yem_synfalt");
    }
    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
//        try {
//            //提交
//            if("audit".equals(operationKey)||"syn_eas".equals(operationKey)){
//                DynamicObject[] dataEntities = e.getDataEntities();
//                for (DynamicObject dataEntitie: dataEntities) {
//                    Boolean aBoolean = isbillType(new DynamicObject[]{dataEntitie});
//                    if (!aBoolean){
//                        continue;
//                    }
//                    JSONArray json = getJSON(new DynamicObject[]{dataEntitie});
//                    String s = setWebService(json);
//                    if (s.length()>0){
//                        this.operationResult.addErrorInfo(
//                                new ValidationErrorInfo(
//                                        "",dataEntitie.getPkValue(), 0,0,"err","billtitle",dataEntitie.getString("billno")+"同步EAS失败:"+s, ErrorLevel.Error));
//                        dataEntitie.set("yem_synfalt",s);
//                        SaveServiceHelper.update(dataEntitie);
//                    }else {
//                        dataEntitie.set("yem_iseas",true);
//                        dataEntitie.set("yem_synfalt","同步EAS成功！");
//                        SaveServiceHelper.update(dataEntitie);
//                    }
//                }
//            }
//        }catch (Exception ex){
//            log.error("同步EAS异常请联系管理员:"+ex.getMessage());
//            throw new KDBizException("同步EAS异常:"+ex.getMessage());
//        }
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
            //提交
            if("audit".equals(operationKey)||"syn_eas".equals(operationKey)){
                ArrayList<DynamicObject> arrayList = new ArrayList<>();
                DynamicObject[] dataEntities = e.getDataEntities();
                for (DynamicObject dataEntitie: dataEntities) {
                    Boolean aBoolean = isbillType(new DynamicObject[]{dataEntitie});
                    if (!aBoolean){
                        arrayList.add(dataEntitie);
                        continue;
                    }
                    try {
                        JSONArray json = getJSON(new DynamicObject[]{dataEntitie});
                        String s = setWebService(json);
                        if (s.length()>0){
                            this.operationResult.addErrorInfo(
                                    new ValidationErrorInfo(
                                            "",dataEntitie.getPkValue(), 0,0,"err","billtitle",dataEntitie.getString("billno")+"同步EAS失败:"+s, ErrorLevel.Error));
                            dataEntitie.set("yem_synfalt",s);
                            SaveServiceHelper.update(dataEntitie);
                        }else {
                            dataEntitie.set("yem_iseas",true);
                            dataEntitie.set("yem_synfalt","同步EAS成功！");
                            SaveServiceHelper.update(dataEntitie);
                            arrayList.add(dataEntitie);
                        }
                    }catch (Exception ex){
                        log.error("同步EAS异常请联系管理员:"+ex.getMessage());
                        throw new KDBizException("同步EAS异常:"+ex.getMessage());
                    }
                }
//                e.getSelectedRows().clear();
                if (arrayList.size()==0){
                    e.setCancel(true);
                }
//                else {
//                    e.getSelectedRows();
//                }
            }
    }



    private Boolean isbillType(DynamicObject[] dataEntities){
        for (DynamicObject dataEntitie: dataEntities) {
            DynamicObject yemBilltype = dataEntitie.getDynamicObject("yem_billtype");

            //如果单据类型不等于整机外购计划
            if (yemBilltype!=null){
                if (!"yem_orderproreqbill_WG".equals(yemBilltype.getString("number"))){
                    return false;
                }
            }
        }
        return true;
    }

    private JSONArray getJSON(DynamicObject[] dataEntities) {
        JSONArray jsonArray = new JSONArray();
        for (DynamicObject dataEntitie: dataEntities) {

            JSONObject json = new JSONObject();
            //单据编号
            json.put("number",dataEntitie.getString("billno"));
            //申请日期
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            String yemBizdate = fmt.format(dataEntitie.getDate("yem_bizdate"));
            json.put("requestDate",yemBizdate);
            //财务组织
            DynamicObject yemDept = dataEntitie.getDynamicObject("yem_dept");
            if (yemDept!=null){
                json.put("companyOrgUnit",setJson("number",yemDept.getString("number")));
            }
            //业务类型
            DynamicObject yemBiztype = dataEntitie.getDynamicObject("yem_biztype");
            if (yemBiztype!=null){
                json.put("bizType",setJson("number",yemBiztype.getString("number")));
            }

            //需求类型
            DynamicObject yemNeedtype = dataEntitie.getDynamicObject("yem_needtype");
            if (yemNeedtype!=null){
                json.put("demandType",setJson("number",yemNeedtype.getString("number")));
            }

            //申请人
            DynamicObject creator = dataEntitie.getDynamicObject("yem_applyuser");
            if (creator!=null){
                String applynum = creator.getString("number");
                // json.put("person",setJson("number",creator.getString("number")));
                json.put("person",setJson("number",applynum));
                List<Long> deptList = UserServiceHelper.getUserDepartment(creator.getLong("id"), false);
                for (Long id: deptList) {
                    DynamicObject apply =
                            BusinessDataServiceHelper.loadSingle(id,"bos_adminorg");
                    if (apply!=null){
                        String number = apply.getString("number");
                        json.put("adminOrg",setJson("number",number));
                        break;
                    }
                }
            }
            //摘要
            json.put("description",dataEntitie.getString("yem_contremark"));
            //审核人
            DynamicObject auditor = dataEntitie.getDynamicObject("auditor");
            if (auditor!=null){
                //json.put("auditor",setJson("number",auditor.getString("number")));
            }
            json.put("auditor",setJson("number","COSMIC"));
            //创建人
            DynamicObject creators = dataEntitie.getDynamicObject("creator");
            if (creators!=null){
                json.put("creator",setJson("number",creators.getString("number")));
            }
            json.put("creator",setJson("number","COSMIC"));
            SimpleDateFormat fmtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //创建时间
            String createtime = fmtTime.format(dataEntitie.getDate("createtime"));
            json.put("createTime",createtime);
            //审核日期
            Date auditdate = dataEntitie.getDate("auditdate");
            if (auditdate!=null){
                String auditdates = fmtTime.format(auditdate);
                json.put("auditTime",auditdates);
            }

            //明细信息分录
            //收款明细
            DynamicObjectCollection yem_es_materialinfocoll = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
            JSONArray entry = getEntry(yem_es_materialinfocoll,dataEntitie);
            json.put("entries",entry);
            jsonArray.add(json);
            log.debug(dataEntitie.getString("billno")+"订单需求单同步EASjson"+jsonArray.toJSONString());
        }

        return jsonArray;
    }
    //明细信息分录
    private JSONArray getEntry(DynamicObjectCollection yem_es_materialinfocoll,DynamicObject dataEntitie) {
        JSONArray jsonArray = new JSONArray();

        for (DynamicObject yem_es_materialinfo: yem_es_materialinfocoll) {
            JSONObject json = new JSONObject();
            //苍穹分录ID
            json.put("plmeid",yem_es_materialinfo.getPkValue());
            //物料编码
            DynamicObject yemMateriel = yem_es_materialinfo.getDynamicObject("yem_materiel");
            if (yemMateriel!=null){
                json.put("material",setJson("number",yemMateriel.getString("number")));
            }

            //行类型
            DynamicObject yemNeedtype = dataEntitie.getDynamicObject("yem_needtype");
            if (yemNeedtype!=null){
                json.put("rowType",setJson("number",yemNeedtype.getString("number")));
            }
            //申请库存组织 采购组织 收货组织
            DynamicObject yemApplyinventoryorg = dataEntitie.getDynamicObject("yem_applyinventoryorg");
            if (yemApplyinventoryorg!=null){
                json.put("storageOrgUnit",setJson("number",yemApplyinventoryorg.getString("number")));
                json.put("purchaseOrgUnit",setJson("number",yemApplyinventoryorg.getString("number")));
                json.put("receivedOrgUnit",setJson("number",yemApplyinventoryorg.getString("number")));

            }

            //计量单位
            DynamicObject yemUnit = yem_es_materialinfo.getDynamicObject("yem_unit");
            json.put("unit",setJson("number",yemUnit.getString("number")));
            //申请数量 审批数量
            BigDecimal yemQty = yem_es_materialinfo.getBigDecimal("yem_qty");
            json.put("requestQty",yemQty);
            json.put("qty",yemQty);
            json.put("requestQty",yemQty);
            //需求日期
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            String yemBizdate = fmt.format(dataEntitie.getDate("yem_bizdate"));
            json.put("requirementDate",yemBizdate);
            json.put("proposeDeliveryDate",yemBizdate);
            json.put("proposePurchaseDate",yemBizdate);
            //币别
            DynamicObject yemCurrency = dataEntitie.getDynamicObject("yem_currency");
            if (yemCurrency!=null){
                // json.put("currency",setJson("number",yemCurrency.getString("number")));
                //end by zhouc 2024-03-13
                json.put("currency",setJson("number",yemCurrency.getString("description")));
            }
            //汇率
            json.put("exchangeRate",dataEntitie.getBigDecimal("yem_exrate"));
            //备注
            json.put("remark",yem_es_materialinfo.getString("yem_remarks1"));
            jsonArray.add(json);
        }
        return jsonArray;
    }

    private String setWebService(JSONArray json){
        String service = RequestEAS.getService(json.toJSONString(), "001");
        JSONObject jsonObject = JSON.parseObject(service);
        String status = jsonObject.getString("status");
        String msg = jsonObject.getString("msg");
        String errorMsgs = "";
        if (!"0".equals(status)){
            JSONArray billErrors = jsonObject.getJSONArray("billErrors");
            int i = 1;
            for (Object billError: billErrors) {
                JSONObject js = (JSONObject) billError;
                JSONArray errorMsg = js.getJSONArray("errorMsgs");
//                errorMsgs = errorMsg.getString(0);
                if (errorMsgs.length() > 0) {
                    errorMsgs = errorMsgs + "\n" + i+"、"+errorMsg.getString(0);
                } else {
                    errorMsgs = i+"、"+errorMsg.getString(0);
                }
                i++;
            }
            if (msg != null) {
                errorMsgs = msg + "\n" + errorMsgs;
            }
        }
        return errorMsgs;
    }

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

}
