import React from 'react';
import {inject, observer} from 'mobx-react';
import {Button, Modal} from 'antd';
import {toJS} from 'mobx';
import {WeaSwitch} from 'comsMobx';
import {WeaSearchGroup, WeaRightMenu, WeaDialog, WeaFormItem, WeaLocaleProvider, WeaTools, WeaTableEditable} from 'ecCom';
import * as IntegrationUtil from "../../util/IntegrationUtil";
import {checkTableFieldValueUnique}  from "../../apis/CommonService";

const getLabel = WeaLocaleProvider.getLabel;
const {getKey} = WeaTools;
const store = ['workflowFlowStore']

@inject(...store)
@observer
export default class RegisterCustom extends React.Component {
  constructor (props) {
    super(props);
    this.table = null;
    this.state = {}
  }

  componentWillUnmount() {
    this.table = null;
  }
  

    getBtns = () => {
        const {workflowFlowStore} = this.props;
        const {menus=[], buttonLoading} = toJS(workflowFlowStore.status);
        return menus && menus.map(item => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7p1v0n@integrationWorkflowRegisterCustomButton${item.key}`} type="primary" disabled={buttonLoading} onClick={() => this.onRightMenuClick(item.key)}>
            {item.content}
        </Button>);
    }

    getRightMenu = () => {
        const {workflowFlowStore} = this.props;
        const {menus=[], buttonLoading} = toJS(workflowFlowStore.status);
        return menus && menus.map(item => {
            return {
              ...item,
              disabled: buttonLoading,
              icon: <i className="icon-coms-Preservation"/>,
              onClick: () => this.onRightMenuClick(item.key),
            }
        });
    }

    onRightMenuClick = (type) => {
        const {workflowFlowStore,saveCallBack} = this.props;
        const {newRegisterCustomForm, customEditIndex} = workflowFlowStore;
        const {interfaceRegisterCustomFormHiddenFields,WeaTableEdit_CustomParameterData} = toJS(workflowFlowStore.status);
        if(type == 'BTN_TEST'){
            IntegrationUtil.onCheck(newRegisterCustomForm,function () {
                let params = Object.assign(interfaceRegisterCustomFormHiddenFields, newRegisterCustomForm.getFormParams());
                params.dtinfo_CustomParameterData = JSON.stringify(WeaTableEdit_CustomParameterData);
                params.submitstate = 'test';
                workflowFlowStore.getInterfaceRegisterCustomOperation(params);
            });

        }
        if(type == 'BTN_SAVE'){
            let checkParams = {
                tableName: 'actionsetting',
                fieldName: 'actionshowname',
                fieldValue: newRegisterCustomForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, ''),
                idName: 'id',
                idValue: customEditIndex
            };
            checkTableFieldValueUnique(checkParams).then(result => {
                if(result&&result.isNotUnique) {
                    newRegisterCustomForm.showError('actionname',getLabel('129943','名称已存在'));
                }else {
                    let checkParams = {
                        tableName: 'actionsetting',
                        fieldName: 'actionname',
                        fieldValue: newRegisterCustomForm.getFormParams().actionid.replace(/^(\s*)|(\s*)$/g, ''),
                        idName: 'id',
                        idValue: customEditIndex
                    };
                    checkTableFieldValueUnique(checkParams).then(result => {
                        if(result&&result.isNotUnique) {
                            newRegisterCustomForm.showError('actionid',getLabel('387654','标识已存在'));
                        }else {
                            let flag = true;
                            if(this.table) {
                              flag = this.table.doValidate().pass;
                            }
                            if(flag) {
                                IntegrationUtil.onCheck(newRegisterCustomForm,function () {
                                    //合并hiddenfield参数
                                    let params = Object.assign(interfaceRegisterCustomFormHiddenFields, newRegisterCustomForm.getFormParams());
                                    params.dtinfo_CustomParameterData = JSON.stringify(WeaTableEdit_CustomParameterData);
                                    workflowFlowStore.getInterfaceRegisterCustomOperation(params,saveCallBack);
                                });
                            }
                        }
                    });
                }
            });
        }

        if(type == 'BTN_DEL'){
            let params = Object.assign(interfaceRegisterCustomFormHiddenFields, newRegisterCustomForm.getFormParams());
            params.method = "deletesingle1";
            workflowFlowStore.confirmModal(`${getLabel(15097, '确定要删除吗？')}`, workflowFlowStore.getInterfaceRegisterCustomOperation , params);

        }
        if(type == 'BTN_ONLINE_EDIT'){
            let workflowid = '';
            let nodeid = '';
            let nodelinkid = '';
            let ispreoperator = '';
            if(interfaceRegisterCustomFormHiddenFields.workflowid) {
                workflowid = interfaceRegisterCustomFormHiddenFields.workflowid;
                nodeid=interfaceRegisterCustomFormHiddenFields.nodeid;
                nodelinkid=interfaceRegisterCustomFormHiddenFields.nodelinkid;
                ispreoperator=interfaceRegisterCustomFormHiddenFields.ispreoperator;
            }
            workflowFlowStore.getInterfaceRegisterCustomAddFormOnline({actionid: '',workflowid:workflowid,nodeid:nodeid,nodelinkid:nodelinkid,ispreoperator:ispreoperator});
            workflowFlowStore.setState({showRegisterCustomDialog: false, showRegisterCustomOnlineDialog: true});
        }

    }

    getSearchs = () => {
        const {workflowFlowStore} = this.props;
        const {newRegisterCustomForm, status, customEditIndex} = workflowFlowStore;
        const {interfaceRegisterCustomFormFields,WeaTableEdit_CustomParameterSet,WeaTableEdit_CustomParameterData} = toJS(status);
        const {isFormInit} = newRegisterCustomForm;
        let group = [];
        let i = 0;
        
        isFormInit && interfaceRegisterCustomFormFields && interfaceRegisterCustomFormFields.map((c, idx) =>{
            let leftDis = (Number(idx) == 2) ? -20 : 0;
            let items = [];
            c.items.map((fields, index) => {
                let bottomDis = (Number(index) == 2 && Number(idx) == 0) ? 15 : 0;
                    items.push({
                        com:(
                            <div style={{marginBottom: bottomDis, marginLeft: leftDis}}>
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@53mm53@integrationWorkflowRegisterCustomForm${fields.domkey[0]}`}
                                label={`${fields.label}`}
                                labelCol={{span: `${fields.labelcol}`}}
                                wrapperCol={{span: `${fields.fieldcol}`}}
                                error={newRegisterCustomForm.getError(fields)}
                                tipPosition="bottom"
                            >
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rx936r@integrationWorkflowRegisterCustomForm${fields.domkey[0]}`} fieldConfig={fields} form={newRegisterCustomForm}
                                    onChange={ v => {
                                        if(getKey(fields) === 'actionname') {
                                            let checkParams = {
                                                tableName: 'actionsetting',
                                                fieldName: 'actionshowname',
                                                fieldValue: newRegisterCustomForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, ''),
                                                idName: 'id',
                                                idValue: customEditIndex
                                            };
                                            checkTableFieldValueUnique(checkParams).then(result => {
                                                if(result&&result.isNotUnique) {
                                                    newRegisterCustomForm.showError('actionname',getLabel('129943','名称已存在'));
                                                }
                                            });
                                        }else if(getKey(fields) === 'actionid') {
                                            let checkParams = {
                                                tableName: 'actionsetting',
                                                fieldName: 'actionname',
                                                fieldValue: newRegisterCustomForm.getFormParams().actionid.replace(/^(\s*)|(\s*)$/g, ''),
                                                idName: 'id',
                                                idValue: customEditIndex
                                            };
                                            checkTableFieldValueUnique(checkParams).then(result => {
                                                if(result&&result.isNotUnique) {
                                                    newRegisterCustomForm.showError('actionid',getLabel('387654','标识已存在'));
                                                }
                                            });
                                        }
                                    }}
                                />
                            </WeaFormItem></div>),
                        colSpan:1
                    })
            });

            if(i==1) {
                items.push({
                    com: (
                        <div style={{marginLeft: -30, marginRight: -10}}>
                            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@7m67yd@integrationWorkflowRegisterCustomForm${i}`}
                                ref={el => this.table = el}
                                title={getLabel('17632','参数设置')}
                                datas={WeaTableEdit_CustomParameterData}
                                columns={WeaTableEdit_CustomParameterSet}
                                tableProps={{showEmptyText: false}}
                                validator={{
                                  rules: {
                                    fieldname: "paramsUnique|required",
                                    fieldvalue: "required",
                                  },
                                  customRegister: [{
                                    name: "paramsUnique",
                                    rules: (value, requirement, attribute) => {
                                      return WeaTableEdit_CustomParameterData.filter(v => v.fieldname === value.trim()).length < 2;
                                    },
                                    errorMessage: getLabel('509498','参数名称重复')
                                  }]
                                }}
                                showCollapse={true}
                                deleteConfirm={true}
                                showAdd={true}
                                showDelete={true}
                                showCopy={false}
                                onChange={(datas) =>workflowFlowStore.setState({WeaTableEdit_CustomParameterData: datas})}
                            />
                        </div>
                    ),
                });
            }

            if(i!=1) {
              group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wo361x@integrationWorkflowRegisterCustomForm${i}`} center={i<1?true:false}  col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
            }else{
              group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@0z9ej0@integrationWorkflowRegisterCustomForm${i}`} center={false}  col={1} needTigger={false} title={''} showGroup={c.defaultshow} items={items}/>);
            }
            i++;
        });
        return group;
    }

    // 关闭弹窗
    closeDialog = () => {
        const {
            workflowFlowStore
        } = this.props;

        workflowFlowStore.setState({showRegisterCustomDialog : false});
        workflowFlowStore.newRegisterCustomForm.reset();
    }

    // 获取弹窗的标题
    getDialogTitle = () => {
        const {workflowFlowStore} = this.props;

        if(workflowFlowStore.customEditIndex && workflowFlowStore.customEditIndex != '') {
            return getLabel('26473,23685', '编辑自定义接口');
        } 
        return getLabel('31691,23685', '注册自定义接口');
    }
  
    render() {
      const {workflowFlowStore} = this.props;
      const {showRegisterCustomDialog} = toJS(workflowFlowStore.status);
      return (<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@0ogrl4`}
          title={this.getDialogTitle()}
          moduleName="integration"
          visible={showRegisterCustomDialog}
          hasScroll={true}
          style={{width: 900, height: 600}}
          onCancel={this.closeDialog}
          buttons={this.getBtns()}
          moreBtn={{
            datas :this.getRightMenu(),
            collectParams: []
          }}
        >
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@s7resx`}
          datas={this.getRightMenu()}
          collectParams={[]}
        >
            {this.getSearchs()}
        </WeaRightMenu>
      </WeaDialog>
    )
  }
}