import React from "react";
import { inject, observer } from "mobx-react";
import { Button, message, Alert } from "antd";
import { toJS } from "mobx";
import { WeaForm, WeaSwitch } from "comsMobx";
import {
    WeaBrowser,
    WeaDialog,
    WeaFormItem,
    WeaInput,
    WeaLocaleProvider,
    WeaRightMenu,
    WeaSearchGroup,
    WeaTableEdit,
    WeaTools,
    WeaTab,
    WeaCheckbox,
    WeaNewScroll,
    WeaHelpfulTip,
} from "ecCom";
import {checkTableFieldValueUnique}  from "../../apis/CommonService";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import transformRulesPlugin from '../../public/integrationPlugin/workflowtrigger/transformRules';

const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const store = ["triggerStore"];

@inject(...store)
@observer
export default class NewDetailForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            marginLeftDis: -390,
            bottomDis: 7,
            styleSheet: 'labeldeyangshi',
        };
    }
    componentDidMount() {
        const {triggerStore} = this.props;
        triggerStore.setState({ newDetailFormSelectedKey : 0 });
    }

    getBtns = () => {
      const {
        loading,
        menus=[],
      } = toJS(this.props.triggerStore.status);
      return menus && menus.map(v => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v6uc1b@integrationWorkflowTriggerButton${v.key}`} type='primary' disabled={loading} onClick={() => this.onRightMenuClick(v.key)}>{v.content}</Button>);;
    }

    getRightMenu = () => {
      const {
        loading,
        menus=[],
      } = toJS(this.props.triggerStore.status);
      return menus && menus.forEach(v => {
        return {
          key: v.key,
          icon: <i className='icon-coms-Preservation'/>,
          content: v.content,
          disabled: loading,
          onClick: () => this.onRightMenuClick(v.key)
        }     
      });
    }
    
    onRightMenuClick = (type) => {
        const { triggerStore } = this.props;
        const { newForm, triggerIntervalFormDt, status} = triggerStore;
        const { TriggerFormHiddenFields, mainFieldListColumnsSetData, TriggerDetailFormFields, TriggerDetailFormHiddenFields, transformRulesInstance } = toJS(triggerStore.status);
        let { newDetailFormSelectedKey } = toJS(triggerStore.status);
        const formParams = newForm.getFormParams();

        if (type == 'BTN_SAVE') {
            if (newDetailFormSelectedKey == 0) {
                //基本信息页保存
                let checkParams = {
                    tableName: 'outerdatawfset',
                    fieldName: 'setname',
                    fieldValue: newForm.getFormParams().setname.replace(/^(\s*)|(\s*)$/g, ''),
                    idName: 'id',
                    idValue: triggerStore.settingRegisterID
                };
                checkTableFieldValueUnique(checkParams).then(result => {
                    if(result&&result.isNotUnique) {
                        newForm.showError('setname',getLabel('129943','名称已存在'));
                        return;
                    }
                    newForm.validateForm().then(f => {
                        if (f.isValid) {
                            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
                            let IPV6 = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
          
                            var valdata = formParams.whitelist.split(',');

                            for(let i=0;i<valdata.length;i++){
                                if(valdata[i].trim()) {
                                    if(!(reg.test(valdata[i].trim()) || IPV6.test(valdata[i].trim()))){
                                        newForm.showError('whitelist', getLabel('390589',"Ip格式不正确"));
                                        return;
                                    }
                                }
                            }
                            
                            let params = Object.assign({}, TriggerFormHiddenFields, newForm.getFormParams());
                            triggerStore.getTriggerOperation({ setname: newForm.getFormParams().setname, operate: 'checkShowName', viewid: params.viewid }, (result) => {
                                if (result && result.errorMsg) {
                                    message.error(result.errorMsg);
                                    return;
                                } else {
                                    //合并hiddenfield参数
                                    let params = Object.assign({}, TriggerFormHiddenFields, newForm.getFormParams());
                                    params.operate = "edit";
                                    triggerStore.getTriggerOperation(params, (result) => {
                                        message.success(getLabel('22619', '保存成功'));
                                        triggerStore.setState({ showNewDetailFormDialog: false })
                                    });
                                }
                            });
    
    
                        } else {
                            f.showErrors();
                            this.setState({ date: new Date() });
                        }
                    });
                    
                });
               
            }else if (newDetailFormSelectedKey == 2) {
              //触发周期保存
              IntegrationUtil.onCheck(triggerIntervalFormDt,()=>{
                let p = triggerIntervalFormDt.getFormParams().periodvalue;
                if(p[0] && p[0] != '') {
                    switch(p[0]) {
                        case '1': 
                          let minutes = p[1] || '';
                          if(!(/^[1-5]\d{0,1}$/.test(Number(minutes)) || /^[1-9]$/.test(Number(minutes)) )) {
                              triggerIntervalFormDt.showError('periodvalue', getLabel('390590',"有效范围为1-59的整数 "));
                              return;
                          };
                          break;
                        case '2':
                          let hours = p[1] || '';
                          if(!(/^(1\d?)$/.test(Number(hours)) || /^(2[0-3])$/.test(Number(hours)) || /^[1-9]$/.test(Number(hours)))) {
                            triggerIntervalFormDt.showError('periodvalue', getLabel('390591',"有效范围为1-23的整数 "));
                            return;
                          }
                          break;
                        case '3':
                          if(!p[1]) {
                            triggerIntervalFormDt.showError('periodvalue', getLabel('391056','"请选择时间"未填写'));
                            return;
                          }
                          break;
                        case '4':
                          if(!p[2]) {
                            triggerIntervalFormDt.showError('periodvalue', getLabel('391056','"请选择时间"未填写'));
                            return;
                          }
                          break;
                        case '5':
                          let days = p[2] || '';
                          if(!(/^(1\d?)$/.test(Number(days)) || /^2[0-7]$/.test(Number(days)) || /^[1-9]$/.test(Number(days)))) {
                              triggerIntervalFormDt.showError('periodvalue', getLabel('390592',"有效范围为1-27的整数 "));
                              return;
                          }
                          if(!p[3]) {
                            triggerIntervalFormDt.showError('periodvalue', getLabel('391056','"请选择时间"未填写'));
                            return;
                          }
                    }
                }
                triggerStore.getTriggerOperation({
                  operate: 'INTERVAL_SAVE',
                  scope: triggerStore.settingRegisterID,
                  periodvalue: p[1] || "",
                  type: p[0] || "",
                  value2: p[2] || "",
                  value3: p[3] || ""
                },(result)=>{
                  let msg = `${getLabel('22619', '保存成功')}`;
                  message.success(msg);
                  triggerStore.setState({ showNewDetailFormDialog: false })
                });
              })


            }else {
                if(transformRulesInstance) {
                    let instanceArrs = [];

                    try{
                        instanceArrs = Object.keys(transformRulesInstance);    
                    } catch(err){}
                    
                    if(instanceArrs) {
                        for(let i = 0; i < instanceArrs.length; i++) {
                            let key = instanceArrs[i];
                            let item = transformRulesInstance[key];

                            if(item && item.onSave) {
                                // 如果onsave方法返回false，则不向下执行
                                if(!item.onSave()) {
                                    return;
                                }
                            }
                        }
                    }
                }

                let params = Object.assign({}, TriggerDetailFormHiddenFields);
                let dtInfo = [];
                for(let i = 1; i < TriggerDetailFormFields.length - 1; i++) {
                  dtInfo = dtInfo.concat(toJS(status)[`detailFieldListColumnsSetData${i}`])
                }
               
                params.dtinfo_detailFieldData = JSON.stringify(dtInfo);
                params.operate = "adddetail";
                params.dtinfo_mainFieldData = JSON.stringify(mainFieldListColumnsSetData);
                triggerStore.getTriggerOperation(params, () => {
                    message.success(getLabel('22619', '保存成功'));
                    triggerStore.setState({ 
                        showNewDetailFormDialog: false,
                        transformRulesInstance: {},
                    })
                });
            }
        }
    }

    /**
     * 初始渲染明细表
     * @param type 标识,区分主表还是明细表
     * @param mainFieldListColumnsSet 明细表的配置数据
     * @param newForm
     */
    initColumsSet = (type, mainFieldListColumnsSet, newForm, mainFieldListColumnsSetData, storeKey) => {
      const { triggerStore } = this.props;

      mainFieldListColumnsSet && mainFieldListColumnsSet.forEach((item={}, index) => {
        if(["customsql", "iswriteback", "outerfieldname"].includes(item.dataIndex)) {
          mainFieldListColumnsSet[index].com[0].type = 'custom';
          mainFieldListColumnsSet[index].com[0].render = (text, record, index, onEdit) => {
            if("customsql" === item.dataIndex) {
                if(record.jsname && transformRulesPlugin && transformRulesPlugin[record.jsname]) {
                    const TransformRuleComp = transformRulesPlugin[record.jsname];

                    return <TransformRuleComp 
                      ecId={`${this && this.props && this.props.ecId || ''}_TransformRuleComp@p84i7p`} 
                      record={record}
                      fieldid={record.fieldid}
                      datas={mainFieldListColumnsSetData}
                      otherParams={{
                        id: triggerStore.settingRegisterID
                      }}
                      getInstance={table => {
                        triggerStore.setState({
                          transformRulesInstance: Object.assign({}, triggerStore.status.transformRulesInstance || {}, {[record.fieldid]: table}),
                        })
                      }}
                      onChange={datas => triggerStore.setState({[storeKey]: datas})}
                    />
                } else {
                    return <input style={{width: 200, visibility: "hidden"}} />;
                }
            } else if("iswriteback" === item.dataIndex) {
              if (type == "mainTable") {
                let formParams = newForm.getFormParams();
                let no_iswriteback = (record.fieldname == "requestname" || record.fieldname == "creater" || record.fieldhtmltype == '6');
                if (formParams.datarecordtype == 2 && (!no_iswriteback)) {
                  return <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@1apnqy`} {...mainFieldListColumnsSet[4].com[0]} value={record.iswriteback} onChange={(value) => { let key = 'iswriteback'; onEdit({ record, index, key, value }) }} />
                } else {
                  return null;
                }
              } else {
                return null;
              }
            } else if("outerfieldname" === item.dataIndex) {
              if(["5", "7", "8"].includes(record.rulesopt)) {
                return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@jipc33`} viewAttr={1} hasBorder />
              } else {
                return <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@04wnpq`} 
                {...item.com[0].browserConditionParam} 
                replaceDatas={[mainFieldListColumnsSetData[index] ? {id: mainFieldListColumnsSetData[index].outerfieldname || "", name: mainFieldListColumnsSetData[index].outerfieldnamespan || ""} : {id: "", name: ""}]}
                onChange={(ids, names) => {
                    record.outerfieldname = ids || "";
                    record.outerfieldnamespan = names || "";
                    mainFieldListColumnsSetData[index] = record;
                    triggerStore.setState({ [storeKey]: mainFieldListColumnsSetData });
                }}/>
              }
            }
          }
        }
      })
    }
                                                                                                                                                                              
    setColumns = (datas) => {
        let group = [];

        datas && datas.forEach(data => {
            if(data.key == 'outerfieldname') {
                data.title = <nobr><label style={{marginRight:5}}>{data.title}</label><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@8b8c25@integrationWorkflowTriggercolumns${data.key}`} width={196} title={`${getLabel('501191,501192,501193', '外部字段数据类型要和流程主字段类型保持关系对应，否则会出现转换错误，最终导致触发流程失败！')}`} /></nobr>
                group.push(data)
            }else if(data.key == 'rulesopt') {
                data.title = <nobr><label style={{marginRight:5}}>{data.title}</label><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@qv7as3@integrationWorkflowTriggercolumns${data.key}`} title={`${getLabel('500368', '如果转换规则为固定值，可设置自定义值或者使用系统变量，系统变量取的是流程创建人属性值，设置如下：人员id，格式为{?userid}；登陆账号，格式为{?loginid}；姓名，格式为{?username}；编号，格式为{?workcode}；密码(MD5格式)，格式为{?password}；部门id，格式为{?departmentid}；部门编码，格式为{?departmentcode}；部门名称，格式为{?departmentname}；分部id，格式为{?subcompanyid}；分部编码，格式为{?subcompanycode}；分部名称，格式为{?subcompanyname} 如果转换规则为自定义sql，此设置查询的是当前系统，格式为：select 最终字段 from tablename where 条件字段={? currentvalue}，{?currentvalue}为固定格式')}`} /></nobr>
                group.push(data)
            }else if(data.key == 'iswriteback') {
                data.title = <nobr><label style={{marginRight:5}}>{data.title}</label><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@zsf3tv@integrationWorkflowTriggercolumns${data.key}`} width={280} title={`${getLabel('509036',' 需“回写标志到外部主表”为“是”，归档回写check框才能设置')}`} /></nobr>
                group.push(data)
            }else {
                group.push(data);
            }
        })
        return group;
    }

    getSearchs3 = () => {
        const {triggerStore} = this.props;
        const {triggerIntervalFormDt, status} = triggerStore;
        const {TriggerIntervalFormFieldsDt} = toJS(status);
        const {isFormInit} = triggerIntervalFormDt;
        let group = [];
        let i = 0;
        const formParams = triggerIntervalFormDt.getFormParams();

        isFormInit && TriggerIntervalFormFieldsDt && TriggerIntervalFormFieldsDt.map(c =>{
        let items = [];

        c.items.map(fields => {

            items.push({
            com:(
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@httoiy@integrationWorkflowTriggerForm${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{span: `${fields.labelcol}`}}
                wrapperCol={{span: `${fields.fieldcol}`}}
                error={triggerIntervalFormDt.getError(fields)}
                tipPosition="bottom"
                >

                <nobr>
                  <div className={this.state.styleSheet}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3s7hyw@integrationWorkflowTriggerForm${fields.domkey[0]}`} fieldConfig={fields} form={triggerIntervalFormDt} formParams={formParams}  onChange={v=> {
                        if(getKey(fields) == 'periodvalue') {
                            let timer = triggerIntervalFormDt.getFormParams().periodvalue;
                            if(timer[0] == '1' || timer[0] == '2') {
                                this.setState({marginLeftDis: -350, bottomDis: 7, styleSheet: 'labeldeyangshi'})
                            }else if(timer[0] == '3') {
                                this.setState({marginLeftDis: -290, bottomDis: 10, styleSheet: 'meitiandeyangshi'})
                            }else if(timer[0] == '4') {
                                this.setState({marginLeftDis: -210, bottomDis: 7, styleSheet: 'meizhoudeyangshi'})
                            }else if(timer[0] == '5') {
                                this.setState({marginLeftDis: 0, bottomDis: 8, styleSheet: 'meiyuedeyangshi'})
                            }else if(timer[0] == '0') {
                                this.setState({marginLeftDis: -500, bottomDis: 8, styleSheet: 'buchufayangshi'})
                            }
                        }
                    }} />
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@9ii15d@integrationWorkflowTriggerForm${fields.domkey[0]}`} style={{marginLeft: this.state.marginLeftDis, position: 'absolute', bottom: this.state.bottomDis}}
                        width={170}
                        title={getLabel('519108','更改后立即生效；为空，意为按照总周期。')}
                    />
                  </div>
                </nobr>
                </WeaFormItem>),
            colSpan:1,
            hide: triggerIntervalFormDt.isHide(fields, (keys, allParams) => {
                let bool = false;
                return bool;
            })
            });

        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@woomqn@integrationWorkflowTriggerForm${i}`} center  col={1}  needTigger={true} title={c.title}  showGroup={c.defaultshow} items={items}/>);
        i++;
        });
        return group;
    }

    onEdit = (tableName, ds, key, datas=[]) => {
      const { triggerStore } = this.props;

      if(key == "rulesopt") {
        let editRow = ds[0],
          rulesopt = editRow.rulesopt,
          index = datas.findIndex(item => item.fieldid === editRow.fieldid),
          jsname = '',
          convertclass = '';
        
        if(index != -1) {
          try {
            if(["5", "7", "8"].includes(rulesopt) || ["5", "7", "8"].includes(datas[index].rulesopt)) {
              datas[index] = {
                ...datas[index],
                outerfieldname: "",
                outerfieldnamespan: "",
              }
            }
          } catch(err){}

          // 获取转换规则插件的js名称   
          if(editRow && editRow.com && editRow.com.rulesopt && editRow.com.rulesopt.length) {
            let items = editRow.com.rulesopt[0] ? editRow.com.rulesopt[0].options : [];

            if(items && items.length) {
                let item = items.find(item => item.key === rulesopt);

                if(item) {
                    jsname = item.jsname || '';
                    convertclass = item.convertclass || '';
                }
            }
          }

          datas[index] = {
            ...datas[index],
            rulesopt,
            customsql: "",
            hrmid: "",
            hrmidspan: "",
            datasourceid: "",
            jsname,
            convertclass,
            attachment_settings: '',   // 转换规则切换同时清空附件的值
          }
          triggerStore.setState({[tableName]: [...datas]});

          // 设置instance
          triggerStore.setState({
            transformRulesInstance: Object.assign({}, triggerStore.status.transformRulesInstance || {}, {[editRow.fieldid]: null}),
          })
        }
      } 
    }

    getSearchs2 = () => {
        const { triggerStore } = this.props;
        const { newForm, newDetailForm, status } = triggerStore;
        const { TriggerDetailFormFields, mainFieldListColumnsSet, mainFieldListColumnsSetData } = toJS(status);
        const { isFormInit } = newDetailForm;
        let group = [];
        let i = 0;
        //初始化明细表组件数据

        this.initColumsSet("mainTable", mainFieldListColumnsSet, newForm, mainFieldListColumnsSetData, 'mainFieldListColumnsSetData');
        let columnsDatas = this.setColumns(mainFieldListColumnsSet);
        
        let groupNum = TriggerDetailFormFields && TriggerDetailFormFields.length;

        isFormInit && TriggerDetailFormFields && TriggerDetailFormFields.forEach(c => {
            let items = [];

            if (i == 0) {
                items.push({
                    com: (
                        <div className='liuchengchufaxiangxishezhi' style={{marginLeft: -25}}>
                            <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@fknk36@integrationWorkflowTriggerForm${i}`}
                                showTitle={false}
                                pushTitleIntoHeader={false}
                                tableProps={{showEmptyText: false, scroll: {x: 1000}}}
                                ref={el => { this.tableEdit = el }}
                                columns={columnsDatas}
                                datas={mainFieldListColumnsSetData}
                                draggable={false}
                                showAdd={false}
                                showDelete={false}
                                showCopy={false}
                                getRowSelection={a => { return false }}
                                onEdit={(ks, ds, bdata, key) => this.onEdit("mainFieldListColumnsSetData", ds, key, mainFieldListColumnsSetData)}
                                onChange={(datas) => triggerStore.setState({ mainFieldListColumnsSetData: datas })}
                            />
                        </div>
                    ),
                });
            }
            if (i > 0 && i < groupNum - 1) {
                let detailColumnsDatas = [];
                let detailDatas = [];
                if (toJS(status)[`detailFieldListColumnsSetData${i}`] && toJS(status)[`detailFieldListColumnsSetData${i}`].length) {
                    let firstData = [{...toJS(status)[`detailFieldListColumnsSetData${i}`][0], seqNum: i}];
                    let otherData = toJS(status)[`detailFieldListColumnsSetData${i}`].slice(1);
                    detailDatas[i] = firstData.concat(otherData);
                    detailColumnsDatas[i] = [...toJS(status)[`detailFieldListColumnsSet${i}`]];
                    this.initColumsSet("detailTable", detailColumnsDatas[i], newForm, detailDatas[i], `detailFieldListColumnsSetData${i}`);
                    detailColumnsDatas[i] = this.setColumns(detailColumnsDatas[i]);
                }
                items.push({
                    com: (
                        <div className='liuchengchufamingxibiao' style={{marginLeft: -25}}>
                            <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@wkxi73@integrationWorkflowTriggerForm${i}`}
                                showTitle={false}
                                pushTitleIntoHeader={false}
                                columns={detailColumnsDatas[i]}
                                datas={detailDatas[i]}
                                tableProps={{showEmptyText: false, scroll: {x: 1000}}}
                                showAdd={false}
                                showDelete={false}
                                showCopy={false}
                                getRowSelection={a => { return false }}
                                onEdit={(ks, ds, dbdata, key) => this.onEdit(`detailFieldListColumnsSetData${ds[0].detailIndex}`, ds, key, detailDatas[ds[0].detailIndex])}
                                onChange={(datas) => triggerStore.setState({[`detailFieldListColumnsSetData${datas[0].detailIndex}`]: datas})}
                            />
                        </div>
                    ),
                    hide: newDetailForm.isHide(newDetailForm, (keys, allParams) => {
                        return (false);
                    })
                });
            }

            if (i == groupNum - 1) {
                //说明
                c && c.items && c.items.forEach(fields => {
                    items.push({
                        com: (<div style={{margin: "0px -20px"}}>
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@sgw0k3@${fields.domkey[0]}`}
                                label={fields.lable}
                                lableCol={{span: 0}}
                                fieldCol={{span: 24}}
                            >
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tiq3wo@${fields.domkey[0]}`} form={newDetailForm} fieldConfig={fields} />
                            </WeaFormItem>
                        </div>),
                    });
                })

            }

            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@hieia7@integrationWorkflowTriggerForm${i}`} center={false} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
            i++;
        });
        return group;
    }

    /**
     * todo 冗余代码,和NewForm一致, 待处理
     * @returns {Array}
     */
    getSearchs = () => {
        const { triggerStore } = this.props;
        const { newForm, status } = triggerStore;
        const { TriggerFormFields } = toJS(status);
        const { isFormInit } = newForm;
        let group = [];
        let i = 0;
        const formParams = newForm.getFormParams();
        isFormInit && TriggerFormFields && TriggerFormFields.map(c => {
            let items = [];

            c.items.map(fields => {

                items.push({
                    com: (
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@2368e0@integrationWorkflowTriggerForm${fields.domkey[0]}`}
                            label={`${fields.label}`}
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 16 }}
                            error={newForm.getError(fields)}
                            tipPosition="bottom"
                        >

                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@jqua9c@integrationWorkflowTriggerForm${fields.domkey[0]}`} fieldConfig={fields} form={newForm} formParams={formParams} onChange={v => {
                                if (getKey(fields) === 'workFlowId') {
                                    triggerStore.newForm = new WeaForm();
                                    let params = newForm.getFormParams();
                                    params.from = 'detailedit';
                                    triggerStore.getTriggerAddForm(params);
                                    this.setState({ TriggerFormFields: TriggerFormFields });
                                } else if (getKey(fields) === 'outermaintable') {
                                  try{
                                    let outermaintable = newForm.getFormParams().outermaintable;
                                    let datasourceid = newForm.getFormParams().datasourceid;
                                    TriggerFormFields[0] && TriggerFormFields[0].items && TriggerFormFields[0].items.find(field => field.domkey[0] == 'keyfield') && (TriggerFormFields[0].items.find(field => field.domkey[0] == 'keyfield').browserConditionParam.dataParams={dmltablename:outermaintable,datasourceid:datasourceid});
                                    TriggerFormFields[0] && TriggerFormFields[0].items && TriggerFormFields[0].items.find(field => field.domkey[0] == 'requestid') && (TriggerFormFields[0].items.find(field => field.domkey[0] == 'requestid').browserConditionParam.dataParams={dmltablename:outermaintable,datasourceid:datasourceid});
                                    TriggerFormFields[0] && TriggerFormFields[0].items && TriggerFormFields[0].items.find(field => field.domkey[0] == 'FTriggerFlag') && (TriggerFormFields[0].items.find(field => field.domkey[0] == 'FTriggerFlag').browserConditionParam.dataParams={dmltablename:outermaintable,datasourceid:datasourceid});
                                    TriggerFormFields[0] && TriggerFormFields[0].items && TriggerFormFields[0].items.find(field => field.domkey[0] == 'isupdatewfdataField') && (TriggerFormFields[0].items.find(field => field.domkey[0] == 'isupdatewfdataField').browserConditionParam.dataParams={dmltablename:outermaintable,datasourceid:datasourceid});
                                    triggerStore.setState({ TriggerFormFields: TriggerFormFields });
                                  }catch (e){}


                                } else if (getKey(fields) === 'isview') {
                                    if (newForm.getFormParams().isview == "1") {
                                        newForm.updateFields({ datarecordtype: "1", isupdatewfdata: "1" });

                                        TriggerFormFields[0] && TriggerFormFields[0].items && TriggerFormFields[0].items.forEach(field => {
                                            if(['datarecordtype', 'isupdatewfdata'].includes(field.domkey[0])) {
                                                field.viewAttr = 1;
                                                field.hasBorder = true;
                                            }
                                        });

                                        // TriggerFormFields[0].items[8].options[0].selected = true;
                                        // TriggerFormFields[0].items[8].options[1].selected = false;
                                        // TriggerFormFields[0].items[8].viewAttr = "1";
                                        // TriggerFormFields[0].items[8].hasBorder = true;

                                        // TriggerFormFields[0].items[13].options[0].selected = true;
                                        // TriggerFormFields[0].items[13].options[1].selected = false;
                                        // TriggerFormFields[0].items[13].viewAttr = "1";
                                        // TriggerFormFields[0].items[13].hasBorder = true;
                                    } else {
                                        // if(newForm.getFormParams().isalways != "1") {
                                        //     TriggerFormFields[0].items[13].viewAttr = "2";
                                        //     TriggerFormFields[0].items[13].hasBorder = false;
                                        // }
                                        // TriggerFormFields[0].items[8].viewAttr = "2";
                                        // TriggerFormFields[0].items[8].hasBorder = false;

                                        TriggerFormFields[0] && TriggerFormFields[0].items && TriggerFormFields[0].items.forEach(field => {
                                            if(('isupdatewfdata' === field.domkey[0] && newForm.getFormParams().isalways != "1") || 'datarecordtype' === field.domkey[0]) {
                                                field.viewAttr = 2;
                                                field.hasBorder = true;
                                            }
                                        });
                                    }
                                    triggerStore.setState({ TriggerFormFields: TriggerFormFields });
                                } else if(getKey(fields) === 'setname') {
                                    let checkParams = {
                                        tableName: 'outerdatawfset',
                                        fieldName: 'setname',
                                        fieldValue: newForm.getFormParams().setname.replace(/^(\s*)|(\s*)$/g, ''),
                                        idName: 'id',
                                        idValue: triggerStore.settingRegisterID
                                    };
                                    checkTableFieldValueUnique(checkParams).then(result => {
                                        if(result&&result.isNotUnique) {
                                            newForm.showError('setname',getLabel('129943','名称已存在'));
                                        }
                                    });
                                } else if(getKey(fields) === 'isalways') {
                                    if(newForm.getFormParams().isalways=="1") {
                                        newForm.updateFields({isupdatewfdata:"1"});
                                        TriggerFormFields[0].items && TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata') && (TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata').options[0].selected = true);
                                        TriggerFormFields[0].items && TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata') && (TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata').options[1].selected = false);
                                        TriggerFormFields[0].items && TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata') && (TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata').viewAttr = 1);
                                        TriggerFormFields[0].items && TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata') && (TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata').hasBorder = true);
                                    }else {
                                        if(newForm.getFormParams().isview != "1") {
                                            TriggerFormFields[0].items && TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata') && (TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata').viewAttr = 2);
                                            TriggerFormFields[0].items && TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata') && (TriggerFormFields[0].items.find(v => v.domkey[0]=='isupdatewfdata').hasBorder = false);
                                        }
                                    }
                                    triggerStore.setState({ TriggerFormFields: TriggerFormFields });
                                }
                            }} />
                        </WeaFormItem>),
                    colSpan: 1,
                    hide: newForm.isHide(fields, (keys, allParams) => {
                        let bool = false;
                        if (allParams.isview == "1") {
                            if (getKey(fields) === 'requestid' || getKey(fields) === 'FTriggerFlag'
                                || getKey(fields) === 'FTriggerFlagValue' || getKey(fields) === 'isupdatewfdataField') {
                                bool = true;
                            }
                        }
                        getKey(fields) === 'updateisnextnode' && allParams.isupdatewfdata == '1' && (bool = true);
                        getKey(fields) === 'requestid' && allParams.datarecordtype == '1' && (bool = true);
                        getKey(fields) === 'FTriggerFlag' && allParams.datarecordtype == '1' && (bool = true);
                        getKey(fields) === 'FTriggerFlagValue' && allParams.datarecordtype == '1' && (bool = true);
                        getKey(fields) === 'successback' && allParams.datarecordtype == '1' && (bool = true);
                        getKey(fields) === 'failback' && allParams.datarecordtype == '1' && (bool = true);

                        getKey(fields) === 'isupdatewfdataField' && allParams.isupdatewfdata == '1' && (bool = true);
                        return bool;
                    })
                });

            });

            if (i == 1) {
                //说明
                items.push({
                    com: (
                        <div style={{marginLeft: -50}} >
                            <div class='badge' style={{ paddingLeft: 30, paddingBottom: 10 }}>1. {getLabel('386907','该流程自动触发时，将根据外部主表条件搜索外部主表，有多少条记录即触发多少条流程；流程主字段的值来源于外部主表，而每条流程的各明细值将分别根据明细表条件搜索明细表得到的结果进行赋值；主表中必须包含主键(默认为id)')}</div>
                            <div class='badge' style={{ paddingLeft: 30, paddingBottom: 10 }}>2. {`${getLabel('524053','条件以“where”开头，如：')}“where fieldname1=1 and fieldname2=\'value2\'”；${getLabel('524054','回写设置以“set”开头，如：')}“set flag=1,isok=true”，${getLabel('524055','触发回写流程ID字段和触发回写标志字段自动更新，不能在此设置')}`}</div>
                            {/* <div class='badge' style={{ paddingLeft: 30, paddingBottom: 10 }}>3. {getLabel(391069,'流程触发时如果需要回写外部主表，需要设置是否回写、流程ID字段、标志字段、标志字段需要回写的值(字符型)，回写数据时，默认标志字段=1：表示已触发，流程ID字段=0：表示流程创建人对应的外部字段值为空，流程ID字段=-1：表示外部字段保存的人员信息在oa中不存在')}</div> */}
                            <div class='badge' style={{ paddingLeft: 30, paddingBottom: 10 }}>3. {getLabel('512895','外部明细表数据如需与主表数据关联，可将外部明细表条件设置为“where 明细表.字段=主表.字段”')}</div>
                        </div>
                    ),
                    hide: newForm.isHide(newForm, (keys, allParams) => {
                        return (false);
                    })
                });

            }

            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@5gtx1c@integrationWorkflowTriggerForm${i}`} center={i < 1 ? true : false} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
            i++;
        });
        return group;
    }

    reloadFlowInfo = () => {
        const { triggerStore } = this.props;
        const { settingRegisterID, getTriggerResetFormFieldMapping } = triggerStore;

        getTriggerResetFormFieldMapping({viewid: settingRegisterID}, () => {
          triggerStore.setState({hasChangedWorkflowForm: false})
        });
    }

    // tab切换
    handleChangeTab = (v) => {
        const {
            triggerStore
        } = this.props, {
            status,
        } = triggerStore, {
            TriggerFormHiddenFields,
        } = toJS(status);
        if(v == 0) {
            triggerStore.getTriggerAddForm({viewid: TriggerFormHiddenFields.viewid});
        } else if(v == 1) {
            triggerStore.getTriggerAddForm({viewid: TriggerFormHiddenFields.viewid}, () => {
                triggerStore.getTriggerEditDetailForm({viewid: TriggerFormHiddenFields.viewid});
            });
        } else if(v == 2) {
            triggerStore.getTriggerIntervalSetFormDt({scopeid: TriggerFormHiddenFields.viewid});
        }
        triggerStore.setState({newDetailFormSelectedKey : v});
    }

    // 渲染表变化后的提示弹窗
    renderTableChangeAlert = () => {
        const { 
            triggerStore 
        } = this.props, { 
            hasChangedWorkflowForm,
        } = triggerStore.status;

        return hasChangedWorkflowForm 
            ? <Alert ecId={`${this && this.props && this.props.ecId || ''}_Alert@fscon9`} 
                message={getLabel('510369','数据表单已被修改')}
                description={
                    <p>
                        <span 
                            style={{color: 'blue', cursor: 'pointer'}} 
                            onClick={this.reloadFlowInfo}
                        >
                            {getLabel('126175','点击此处')}
                        </span>
                        {getLabel('510370','重新加载流程信息')}
                    </p>
                }
                showIcon
                type="warning"
              />
            : null;
    }

    // 关闭弹窗
    closeEditDialog = () => {
        const {triggerStore} = this.props;
        
        triggerStore.setState({ 
            showNewDetailFormDialog: false, 
            newDetailFormSelectedKey: 0 
        })
    }

    render() {
        const { 
            triggerStore 
        } = this.props, { 
            status,
        } = triggerStore, { 
            loading, 
            topTab,
            showNewDetailFormDialog, 
            newDetailFormSelectedKey, 
        } = status;
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@kcyu75`}
                title={`${getLabel('26473,33720', '编辑流程触发集成')}`}
                moduleName="integration"
                visible={showNewDetailFormDialog}
                hasScroll={true}
                style={{ width: 1200, height: 800 }}
                onCancel={this.closeEditDialog}
                loading={loading}
                buttons={this.getBtns()}
                moreBtn={{
                    datas: this.getRightMenu(),
                    collectParams: []
                }}
            >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@52hasc`}
                    datas={this.getRightMenu()}
                    collectParams={[]}
                >
                    {this.renderTableChangeAlert()}
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@z3qh6g`}
                        keyParam="viewcondition_dt" //主键
                        datas={topTab}
                        selectedKey={newDetailFormSelectedKey}
                        onChange={this.handleChangeTab}
                    />
                    <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@whiklb`} height={750}>
                        {
                        newDetailFormSelectedKey == 0 
                            ? this.getSearchs()
                            : newDetailFormSelectedKey == 1
                            ? this.getSearchs2()
                            : this.getSearchs3()
                        }
                    </WeaNewScroll>
                </WeaRightMenu>
            </WeaDialog>
        )
    }
}
