package weaver.interfaces.workflow.action;

import com.api.doc.util.DocWKNonStandardUtil;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocComInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.soa.workflow.request.*;
import java.util.ArrayList;
import java.util.List;

/**
* @Desc   更新流程表单字段到自定义字段或系统字段中
 * 流程主表支持 系统字段和自定义字段
 * 流程明细表  仅支持关联文档的系统字段
* @Author b-r
* @Date 2023/6/7 16:51
**/
public class WKUpdateCusFieldAction extends BaseBean implements Action {

    private String wd;  //文档
    private String glwd; //明细表，关联文档

    @Override
    public String execute(RequestInfo requestInfo) {
        if(!DocWKNonStandardUtil.open()){
            return Action.FAILURE_AND_CONTINUE;
        }
        String workflowid = Util.null2String(requestInfo.getWorkflowid());
        String requestid = Util.null2String(requestInfo.getRequestid());
        RecordSet rs = new RecordSet();

        int docid = -1;
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] property = mainTableInfo.getProperty();
        for (Property pro : property) {
            if(this.wd.equalsIgnoreCase(pro.getName())){
                docid = Util.getIntValue(Util.null2String(pro.getValue()));
            }
        }
        //根据文档id获取目录id。目录id根据文档id获取，如果传目录的话，目录是新目录，但是文档还是在原目录下，cus_fielddata表中会多一条数据
        DocComInfo dci = new DocComInfo();
        int secid = dci.getDocSecCategory(docid + "");
        if(secid <= 0){
            rs.executeQuery("select seccategory from docdetail where id=?",docid);
            if(rs.next()){
                secid = Util.getIntValue(rs.getString(1));
            }
        }
        writeLog("WKUpdateCusFieldAction------->docid:"+docid+"---->secid:"+secid+"--->workflowid:"+workflowid+"---->requestid:"+requestid);

        //secid = secid.contains("_") ? secid.substring(secid.lastIndexOf("_")+1) : secid;
        /**校验参数start*/
        if(docid <=0 || Util.getIntValue(secid) <=0){
            writeLog("WKUpdateCusFieldAction------->docid:"+docid+"---->secid:"+secid);
            return Action.FAILURE_AND_CONTINUE;
        }
        /**校验参数end*/

        String customColumns = "";
        String systemColumns = "";
        List<String> versionList = new ArrayList<>();

        RecordSet formRs = new RecordSet();
        rs.executeQuery("select activeversionid from workflow_base where id =?",workflowid);
        if(rs.next()){
            int activeversionid = Util.getIntValue(rs.getString("activeversionid"));
            writeLog("WKUpdateCusFieldAction------->workflowid:"+workflowid+"---->activeversionid:"+activeversionid);
            if(activeversionid > 0){
                //根据活动版本找到所有的历史版本，看谁配置在了建模表中
                rs.executeQuery("select id from workflow_base where activeversionid =?",activeversionid);
                while (rs.next()){
                    versionList.add(Util.null2String(rs.getString(1)));
                }
            }else {
                versionList.add(workflowid);
            }
        }
        String workflowIds = String.join(",", versionList);
        rs.executeQuery("select * from uf_wfAndDoc where lclj in ("+workflowIds+")");
        //根据流程id查主表，如果有值，说明设置了对应关系
        if(rs.next()){
            int mainId = Util.getIntValue(rs.getString("id"));
            writeLog("WKUpdateCusFieldAction------->建模主表mainId:"+mainId);

            /**自定义表数据，下面全部用update*/
            boolean customAdd = true;
            rs.executeQuery("select 1 from cus_fielddata where id=" + docid + " and scope='DocCustomFieldBySecCategory' and scopeid='" + secid + "'");
            if (rs.next()) {
                customAdd = false;
            }
            writeLog("WKUpdateCusFieldAction------->customAdd:"+customAdd);
            if (customAdd) {
                String _customColumns = "scope,scopeid,id";
                String _customValues = "'DocCustomFieldBySecCategory'," + secid + "," + docid;
                String customSql = "insert into cus_fielddata(" + _customColumns + ") values(" + _customValues + ")";
                RecordSet customRs = new RecordSet();
                customRs.setNoAutoEncrypt(true);
                customRs.executeUpdate(customSql);
            }
            /**自定义表数据，下面全部用update*/

            RecordSet typeRs = new RecordSet();
            RecordSet detailRs = new RecordSet();

            /** 根据流程id 获取表单id，并根据请求id查询表单字段的值*/
            rs.executeQuery("select formid from workflow_base where id=?",workflowid);
            if(rs.next()) {
                int formid = Util.getIntValue(rs.getString(1));
                String table = "formtable_main_" + (-formid);
                writeLog("WKUpdateCusFieldAction------->流程表名table:"+table);

                /**根据流程id 获取 建模明细表 表单字段和文档字段的对应*/
                rs.executeQuery("select lczdbs,wdzd,mxbm from uf_wfAndDoc_dt1 where mainid=? and wdzd !='' ", mainId);
                while (rs.next()) {
                    String formField = Util.null2String(rs.getString(1));
                    String docField = Util.null2String(rs.getString(2));
                    String detailTable = Util.null2String(rs.getString(3));
                    writeLog("WKUpdateCusFieldAction------->字段对应---->formField:"+formField+"---->docField:"+docField+"---->detailTable:"+detailTable);
                    if (!"".equals(docField)) {
                        int fieldType = 1;  //1-自定义字段  2-系统字段
                        //判断是标准字段还是自定义字段
                        typeRs.executeQuery("select fieldtype from (SELECT fieldlabel,fieldname,'1' fieldtype FROM cus_formdict WHERE scope='DocCustomFieldBySecCategory'" +
                                "union select zdmc fieldlabel,zdbs fieldname,'2' fieldtype from uf_doc_sec_field) t1 where fieldname ='" + docField + "'");
                        if (typeRs.next()) {
                            fieldType = Util.getIntValue(typeRs.getString(1));
                        }
                        writeLog("WKUpdateCusFieldAction------->自定义字段还是系统字段:" + fieldType);
                        if(!"".equals(detailTable)){  //明细表对应
                            if(!"".equals(Util.null2String(this.glwd))) {  //根据关联文档 更新明细关联文档的属性
                                formRs.executeQuery("select " + this.glwd+","+formField + " from " + detailTable + " where mainid=(select id from " + table + " where requestid=?)", requestid);
                                while (formRs.next()) {
                                    String column = "";
                                    int _glwd = Util.getIntValue(formRs.getString(1));
                                    String value = Util.null2String(formRs.getString(2));
                                    if (fieldType == 1) {
                                        if (value.isEmpty()) {
                                            column = docField + "=null";
                                        } else {
                                            column = docField + "='" + value.replace("'", "''") + "'";
                                        }
                                        String customSql = "update cus_fielddata set " + column +
                                                " where id=" + _glwd + " and scope='DocCustomFieldBySecCategory' and scopeid='" + secid + "'";
                                        detailRs.executeUpdate(customSql);
                                    } else {
                                        if (value.isEmpty()) {
                                            column = docField + "=null";
                                        } else {
                                            column = docField + "='" + value.replace("'", "''") + "'";
                                        }
                                        String systemSql = "update docdetail set " + column + " where id=?";
                                        detailRs.executeUpdate(systemSql, _glwd);
                                    }
                                }
                            }
                        }else {  //流程表单 主表对应
                            formRs.executeQuery("select " + formField + " from " + table + " where requestid=?",requestid);
                            if (formRs.next()) {
                                String value = Util.null2String(formRs.getString(1));
                                if (fieldType == 1) {
                                    if (value.isEmpty()) {
                                        customColumns += "," + docField + "=null";
                                    } else {
                                        customColumns += "," + docField + "='" + value.replace("'", "''") + "'";
                                    }
                                } else {
                                    if (value.isEmpty()) {
                                        systemColumns += "," + docField + "=null";
                                    } else {
                                        systemColumns += "," + docField + "='" + value.replace("'", "''") + "'";
                                    }
                                }
                            }
                        }
                    }
                }
            }
            writeLog("WKUpdateCusFieldAction------>customColumns:"+customColumns);
            String customSql = "";
            //根据docid更新自定义表的字段值
            if (!customColumns.isEmpty()) {
                customColumns = customColumns.substring(1);
                customSql = "update cus_fielddata set " + customColumns +
                        " where id=" + docid + " and scope='DocCustomFieldBySecCategory' and scopeid='" + secid + "'";
            }
            writeLog("WKUpdateCusFieldAction------>customSql:" + customSql);
            if (!customSql.isEmpty()) {
                RecordSet customRs = new RecordSet();
                customRs.setNoAutoEncrypt(true);
                customRs.executeUpdate(customSql);
            }

            writeLog("WKUpdateCusFieldAction------>systemColumns:"+systemColumns);
            if(!"".equals(systemColumns)){
                systemColumns = systemColumns.substring(1);
                String systemSql = "update docdetail set " + systemColumns + " where id=?";
                rs.executeUpdate(systemSql,docid);
            }
        }
        return Action.SUCCESS;
    }

}