package yem.wm.cm.htqs.form;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.OrmLocaleValue;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.AfterF7SelectEvent;
import kd.bos.form.field.events.AfterF7SelectListener;
import com.alibaba.fastjson.JSONObject;
//import com.enrobot.util.CommonUtils;
//import com.fasc.open.api.v5_1.client.OpenApiClient;
//import com.itopview.wm.sys.utils.NewVersionHelper;
//import com.itopview.wm.utils.ContractSignUtil;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.operate.FormOperate;
import kd.bos.ksql.util.StringUtil;
import kd.bos.form.FormShowParameter;


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 org.apache.commons.lang3.StringUtils;
import yem.base.common.module.version.helper.NewVersionHelper;

import java.util.EventObject;
import java.util.HashMap;
import java.util.Set;


public class ContractSign extends AbstractBillPlugIn implements AfterF7SelectListener {


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);

        //附件类型
        BasedataEdit taxrateid = this.getView().getControl("yem_attachmenttype");
        taxrateid.addAfterF7SelectListener(this);

    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
    }

    /**
     * 校验附件类型
     *
     * @param e
     */
    @Override
    public void afterF7Select(AfterF7SelectEvent e) {
        Control control = (Control) e.getSource();
        String key = control.getKey();
        if ("yem_attachmenttype".equals(key)) {

            int rowIndex = this.getModel().getEntryCurrentRowIndex("yem_attachmentdetail");
            DynamicObject obj = (DynamicObject) this.getView().getModel().getValue("yem_attachmenttype", rowIndex);
            String name = obj.getString("name");
            // 判断单据
            String pageId = this.getView().getFormShowParameter().getFormId();
//            NewVersionHelper newVersionHelper = new NewVersionHelper(pageId);
//            if (!newVersionHelper.isChanged()) {
            String templatetype = (String) this.getView().getModel().getValue("yem_templatetype");// 模板类型

            if (templatetype == null || StringUtil.isEmpty(templatetype)) {
                this.getView().getModel().setValue("yem_attachmenttype", null, rowIndex);
                this.getView().showErrorNotification("请先填写合同模板类型");
                return;
            }

            if ("A".equals(templatetype)) {
                // 我方模板    禁止手动上传合同、单签、双签
                if ("合同".equals(name) || "单签".equals(name) || "双签".equals(name)) {
                    this.getView().getModel().setValue("yem_attachmenttype", null, rowIndex);
                    this.getView().showErrorNotification(String.format("禁止上传类型为【%s】的附件!", name));
                }
            } else if ("B".equals(templatetype)) {
                // 对方模板  禁止手动上传双签
                if ("双签".equals(name)) {
                    this.getView().getModel().setValue("yem_attachmenttype", null, rowIndex);
                    this.getView().showErrorNotification("禁止上传类型为【双签】的附件!");
                }
                if ("单签".endsWith(name) || "合同".endsWith(name)) {
                    OrmLocaleValue filesName = (OrmLocaleValue) this.getView().getModel().getValue("yem_attachmentname", rowIndex);
                    if (filesName != null) {
                        String file = filesName.getLocaleValue();
                        String[] split = file.split("[.]");
                        if (!"pdf".equalsIgnoreCase(split[split.length - 1])) {
                            this.getView().getModel().setValue("yem_attachmenttype", null, rowIndex);
                            this.getView().showErrorNotification("注意：请上传PDF格式的文件进行用印，其余格式都无法用印！！");
                        }
                    }
                }
            }
//            }
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        //表单操作按钮
        FormOperate formOperate = (FormOperate) args.getSource();
        // 签定方向确认
        if (StringUtils.equals("signingconfirm", formOperate.getOperateKey())) {
            String pageId = this.getView().getFormShowParameter().getFormId();
            // 获取签定方向
            String signing = (String) this.getView().getModel().getValue("yem_signing");// 签定方向
            String type = "单签";


            //B	对方先签		A	我方先签
            if ("B".equals(signing)) {
                DynamicObject attchType = this.attachType(pageId, type);// 附件类型
                String yem_attachmentcon_tag = (String) this.getView().getModel().getValue("yem_attachmentcon"); // 附件类型存储内容

                JSONObject json = new JSONObject();
                if (!StringUtil.isEmpty(yem_attachmentcon_tag)) json = JSONObject.parseObject(yem_attachmentcon_tag);
                Set<String> s = json.keySet();
                String typeId = "00000-";
                if (attchType != null) typeId = attchType.getPkValue().toString(); // 附件类型内码
                boolean flag = false;
                for (String keys : s) {
                    if (json.getString(keys).equals(typeId)) flag = true;
                }
                if (flag) {
                    this.getView().showErrorNotification("已存在【" + type + "】附件，不允许修改签定方向!");
                } else {
                    this.showSigningConfirm();
                }
            } else {
                this.showSigningConfirm();
            }
        }

    }


    /**
     * 回填  合同签署方向确认
     */
    private void showSigningConfirm() {
        FormShowParameter showParameter = new FormShowParameter();// 创建弹出动态表单页面对象
        showParameter.setFormId("yem_cm_signingconfirm");// 设置弹出页面的标识
        showParameter.setStatus(OperationStatus.ADDNEW);// 状态
        String formId = this.getView().getFormShowParameter().getFormId();
        showParameter.setCloseCallBack(new CloseCallBack(this, formId));// 设置页面关闭回调方法
        showParameter.getOpenStyle().setShowType(ShowType.Modal);// 设置弹出页面打开方式
        this.getView().showForm(showParameter);    // 打开动态表单
    }


    /**
     * 动态表单关闭回调事件
     */
    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        Object returnData = closedCallBackEvent.getReturnData();
        String formId = this.getView().getFormShowParameter().getFormId();
        if (StringUtils.equals(closedCallBackEvent.getActionId(), formId) && null != closedCallBackEvent.getReturnData()) {
            HashMap<String, String> values = (HashMap<String, String>) returnData;
            String signning = (String) values.get("signing");
            String signings = "yem_signing";

            if ("ourside".equals(signning)) this.getView().getModel().setValue(signings, "A");
            if ("oppositeparty".equals(signning)) this.getView().getModel().setValue(signings, "B");
        }
    }


    /**
     * 获取附件类型
     *
     */
    private DynamicObject attachType(String formKey, String attachTypeName) {

        DynamicObject attachmenttypeSQ =
                BusinessDataServiceHelper.loadSingle("yem_bd_attachmenttype", "id,name", new QFilter[]{
                        new QFilter("name", QCP.equals, attachTypeName), new QFilter("tpv_bill.number", QCP.equals, formKey)
                });
        return attachmenttypeSQ;
    }


}
