package com.yem.wm.bc.bill.from;

import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YunzhijiaUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.validate.ValidateResult;
import kd.bos.entity.validate.ValidateResultCollection;
import kd.bos.exception.KDBizException;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.EventObject;
import java.util.List;

/**
 * @author 夜子
 * @ClassName YemBillPlugInBaseFrom
 * @description: TODO
 * @date 2023年08月11日
 * @version: 1.0
 */
public class YemBillPlugInBaseFrom extends AbstractBillPlugIn {

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);
//        FormShowParameter fsp=  e.getFormShowParameter();
//        String billtype  = fsp.getFormConfig().getEntityTypeId();
//        if(ChangeModelHelper.getChangeModel5SrcBill(billtype)!=null){
//            fsp.addCustPlugin("com.yem.wm.bc.change.from.SrcBillChangePlugin");
//        }
//        if(ChangeModelHelper.getChangeModel5XBill(billtype)!=null){
//            fsp.addCustPlugin("com.yem.wm.bc.change.from.XBillChangePlugin");
//        }

    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
//        DynamicObject yemBilltype = (DynamicObject) this.getModel().getValue("yem_billtype");
//        if(yemBilltype==null){
//            this.getView().showErrorNotification("请添加/选择单据类型！");
//            return;
//        }
//        Object billno = this.getModel().getValue("billno");
//        this.getModel().setValue("yem_title",yemBilltype.getString("name")+"-"+billno);
//        String billtype  =  this.getModel().getDataEntityType().getName();
//        this.getView().setVisible(ChangeModelHelper.getChangeModel5SrcBill(billtype) != null,"bar_change");
//        this.getView().setVisible(ChangeModelHelper.getChangeModel5XBill(billtype) != null,"bar_bizvalid");
//        this.getView().setVisible(ChangeModelHelper.getChangeModel5SrcBill(billtype) != null || ChangeModelHelper.getChangeModel5XBill(billtype) != null,"bar_bizchangeresume");

    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate formOperate = (FormOperate) e.getSource();
        String operateKey = formOperate.getOperateKey();
        IDataModel model = getModel();
        //撤销前先判断有没有智能审批
        if ("unsubmit".equals(operateKey) || "audit".equals(operateKey)) {
            DynamicObject obj = this.getModel().getDataEntity(true);
//            //根据单据标识获取单据注册信息
//            QFilter qFilter = new QFilter("yem_isdisable", QCP.equals, false);
//            qFilter.and(new QFilter("yem_formid.number", QCP.equals, obj.getDynamicObjectType().getName()));
//            if(obj.containsProperty("yem_billtype")){
//                qFilter.and(new QFilter("yem_billtype.fbasedataid.number", QCP.in, obj.getString("yem_billtype.number")));
//            }
//            if("yem_orderproreqbill".equals(obj.getDynamicObjectType().getName())){
//                qFilter.and(new QFilter("yem_isvmi", QCP.equals, obj.get("yem_isvmi")));
//            }
//            if("yem_placeexamine".equals(obj.getDynamicObjectType().getName())){
//                qFilter.and(new QFilter("yem_salesordertype",QCP.equals,obj.getString("yem_salesordertype")));
//            }
//            boolean b = QueryServiceHelper.exists("yem_ia_intebilllogon", qFilter.toArray());
            String yem_forminstid = obj.getString("yem_forminstid");
            String yem_flowinstid = obj.getString("yem_flowinstid");
            if (!StringUtils.isBlank(yem_forminstid) || !StringUtils.isBlank(yem_flowinstid)) {
                e.setCancel(true);
                if ("unsubmit".equals(operateKey)) {
                    getView().showErrorNotification("本单存在智能审批无法进行手工撤销，请在云之家进行驳回处理！");
                } else {
                    getView().showErrorNotification("本单存在智能审批无法进行手工审核，请在云之家进行审批处理！");
                }
            }
        }
        if ("save".equals(operateKey) || "submit".equals(operateKey)) {
            DynamicObject dynamicObject = this.getModel().getDataEntity(true);
            if (dynamicObject.containsProperty("yem_billtype")) {
                String typename = dynamicObject.getString("yem_billtype.name");
                Object billno = dynamicObject.get("billno");
                dynamicObject.set("yem_title", typename + "-" + billno);
                model.setValue("yem_title", typename + "-" + billno);
            }
        }

    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        if ("submit".equals(operateKey)) {
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            this.getView().updateView("yem_forminstid");
            this.getView().updateView("yem_flowinstid");
            this.getView().updateView("yem_isyzjreject");
            this.getView().invokeOperation("refresh");
        }
        if ("cloudhomeacquisition".equals(operateKey)) {
            String data = (String) this.getModel().getValue("yem_flowinstid");
            if (!data.isEmpty()) {

                DynamicObject ialog = BusinessDataServiceHelper.loadSingle("yem_ialog"
                        , new QFilter[]{new QFilter("yem_forminstid", QCP.equals, data)});
                if (ialog!=null) {
                    ialog.set("yem_writeback", data);
                    SaveServiceHelper.save(new DynamicObject[]{ialog});
                }
                //TODO 调用云之家获取审批结果接口
                JSONObject reqjson = new JSONObject();
                reqjson.put("flowInstId", data);
                String retStr = null;
                try {
                    retStr = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl + "/gateway/yun/common/approve", reqjson.toString());
                } catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
                    throw new RuntimeException(ex);
                }
                JSONObject retJson = JSONObject.parseObject(retStr);
                if ("DISAGREE".equals(retJson.getString("data"))) {
                    OperationResult result =   OperationServiceHelper.executeOperate("unsubmit", this.getModel().getDataEntityType().getName()
                            , new Object[]{this.getModel().getValue("id")}, OperateOption.create());
                    if (result.isSuccess()) {
                        this.getModel().setValue("yem_isyzjreject", true);
                    }
                    else{
                        List<IOperateInfo> allErrorOrValidateInfo = result.getAllErrorOrValidateInfo();
                        String message = result.getMessage();
                        if(allErrorOrValidateInfo.size()>0){
                            throw new KDBizException("撤销失败！" + message + ":\r\n" + allErrorOrValidateInfo);
                        }
                        else{
                            throw new KDBizException("撤销失败！" + message);
                        }
                    }
                }
                if ("FINISH".equals(retJson.getString("data"))) {
                    OperationResult result = OperationServiceHelper.executeOperate("audit", this.getModel().getDataEntityType().getName()
                            , new Object[]{this.getModel().getValue("id")}, OperateOption.create());
                    String audit = result(result, "audit");
                    if (audit != null) {
                        this.getView().showMessage("同步失败,失败原因:" + audit);
//                        OperationServiceHelper.executeOperate("unsubmit", this.getModel().getDataEntityType().getName()
//                                , new Object[]{this.getModel().getValue("id")}, OperateOption.create());
                    }else {
                        this.getView().showMessage("同步成功:");
                        this.getModel().setValue("yem_synfalt", "同步成功");
                    }
                }
            }
            this.getView().invokeOperation("save");
            this.getView().updateView();
        }
    }
    private String result(OperationResult result, String operation) {
        if (!result.isSuccess()) {
            ValidateResultCollection validateResult = result.getValidateResult();
            List<ValidateResult> validateErrors = validateResult.getValidateErrors();
            StringBuilder stringBuilder = new StringBuilder();
            if (result.getMessage() != null) {
                stringBuilder.append(result.getMessage());
            }
            for (ValidateResult validateError : validateErrors) {
                List<OperateErrorInfo> allErrorInfos = validateError.getAllErrorInfo();
                for (OperateErrorInfo allErrorInfo : allErrorInfos) {

                    String message = allErrorInfo.getMessage();
                    stringBuilder.append(message + ";");
                }
            }
            List<OperateErrorInfo> allErrorInfos = result.getAllErrorInfo();
            for (OperateErrorInfo allErrorInfo : allErrorInfos) {
                String message = allErrorInfo.getMessage();
                stringBuilder.append(message);
            }
            return operation + stringBuilder;
            //throw new KDBizException(operation+stringBuilder);
        }
        return null;
    }
}

