import React from "react";
import { inject, observer } from "mobx-react";
import { Button } from "antd";
import { toJS } from "mobx";
import { WeaSwitch } from "comsMobx";
import {
  WeaSearchGroup,
  WeaFormItem,
  WeaTools,
  WeaRightMenu,
  WeaDialog,
  WeaLocaleProvider,
  WeaCodeMirror
} from "ecCom";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import {checkTableFieldValueUnique}  from "../../apis/CommonService";
const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const store = ["workflowFlowStore"];

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

    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@hkz1ls@integrationWorkflowRegisterCustomOnlineButton${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 {newRegisterCustomOnlineForm} = workflowFlowStore;
        const { interfaceRegisterCustomOnlineFormHiddenFields } = toJS(workflowFlowStore.status);

        if(type == 'BTN_TEST'){
            IntegrationUtil.onCheck(newRegisterCustomOnlineForm,function () {
                let params = Object.assign(interfaceRegisterCustomOnlineFormHiddenFields, newRegisterCustomOnlineForm.getFormParams());
                params.dtinfo_CustomParameterData = [];
                params.submitstate = 'test';
                workflowFlowStore.getInterfaceRegisterCustomOperation(params);
            });

        }
        if(type == 'BTN_SAVE'){
            newRegisterCustomOnlineForm.validateForm().then(f=>{
                if(f.isValid){
                    //合并hiddenfield参数
                    let checkParams = {
                      tableName: 'actionsetting',
                      fieldName: 'actionshowname',
                      fieldValue: newRegisterCustomOnlineForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, ''),
                      idName: 'id',
                      idValue: interfaceRegisterCustomOnlineFormHiddenFields.id || ''
                    };
                    checkTableFieldValueUnique(checkParams).then(result => {
                      if(result&&result.isNotUnique) {
                        newRegisterCustomOnlineForm.showError('actionname',getLabel('129943','名称已存在'));
                      }else {
                        let params = Object.assign(interfaceRegisterCustomOnlineFormHiddenFields, newRegisterCustomOnlineForm.getFormParams());
                        // params.method = "add";
                        params.dtinfo_CustomParameterData = [];
                        workflowFlowStore.getInterfaceRegisterCustomOperation(params,saveCallBack);
                      }
                    });
                }else{
                    f.showErrors();
                    this.setState({date: new Date()});
                }
            });

        }

        if(type == 'BTN_DEL'){


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

        }

        if(type == 'BTN_EDIT'){
          workflowFlowStore.getInterfaceRegisterCustomAddForm({actionid: ""});
          workflowFlowStore.setState({
            showRegisterCustomOnlineDialog: false,
            showRegisterCustomDialog: true
          });
        }
    }

    getSearchs = () => {
        const {workflowFlowStore} = this.props;
        const {newRegisterCustomOnlineForm, status} = workflowFlowStore;
        const {interfaceRegisterCustomOnlineFormFields, interfaceRegisterCustomOnlineFormHiddenFields} = toJS(status);
        const {isFormInit} = newRegisterCustomOnlineForm;
        let group = [];
        const formParams = newRegisterCustomOnlineForm.getFormParams();
        isFormInit && interfaceRegisterCustomOnlineFormFields && interfaceRegisterCustomOnlineFormFields.map((c, index) =>{
          let items = [];

          if(index == 1) {
            c.items.map(fields => {
              items.push({
                com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vfetie@integrationWorkflowRegisterCustomOnlineForm${fields.domkey[0]}`}
                  label={`${fields.label}`}
                  labelCol={{span: `${fields.labelcol}`}}
                  wrapperCol={{span: `${fields.fieldcol}`}}
                  error={newRegisterCustomOnlineForm.getError(fields)}
                  tipPosition="bottom"
                >
                  <WeaCodeMirror ecId={`${this && this.props && this.props.ecId || ''}_WeaCodeMirror@u4us1q@integrationWorkflowRegisterCustomOnlineForm${index}${fields.domkey[0]}`} width={600} height={300} value={formParams.javaCode} onChange={v => newRegisterCustomOnlineForm.updateFields({javaCode: v})} />
                </WeaFormItem>)
              })
            })
          }else {
            c.items.map(fields => {
              items.push({
                com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@b3dqn3@integrationWorkflowRegisterCustomOnlineForm${index}${fields.domkey[0]}`}
                  label={`${fields.label}`}
                  labelCol={{span: `${fields.labelcol}`}}
                  wrapperCol={{span: `${fields.fieldcol}`}}
                  error={newRegisterCustomOnlineForm.getError(fields)}
                  tipPosition="bottom"
                >
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@secxo7@integrationWorkflowRegisterCustomOnlineForm${index}${fields.domkey[0]}`} fieldConfig={fields} form={newRegisterCustomOnlineForm} formParams={formParams}  onChange={v=> {
                    if(getKey(fields) === 'actionname') {
                      let checkParams = {
                        tableName: 'actionsetting',
                        fieldName: 'actionshowname',
                        fieldValue: newRegisterCustomOnlineForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, ''),
                        idName: 'id',
                        idValue: interfaceRegisterCustomOnlineFormHiddenFields.id || ''
                      };
                      checkTableFieldValueUnique(checkParams).then(result => {
                        if(result&&result.isNotUnique) {
                          newRegisterCustomOnlineForm.showError('actionname',getLabel('129943','名称已存在'));
                        }
                      });
                    }
                  }} />
                </WeaFormItem>),
                colSpan:1,
                hide: newRegisterCustomOnlineForm.isHide(fields, (keys, allParams) => {
                  let bool = false;
                  return bool;
                })
              });
            });
          }
    
          group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@q85djd@integrationWorkflowRegisterCustomOnlineForm${index}`} center  col={1}  needTigger={true} title={c.title}  showGroup={c.defaultshow} items={items}/>);
        });
        return group;
    }

    render() {
        const {workflowFlowStore} = this.props;
        const {showRegisterCustomOnlineDialog} = toJS(workflowFlowStore.status);
      const {interfaceRegisterCustomOnlineFormHiddenFields} = toJS(workflowFlowStore.status);
      let title = getLabel('31691,23685', '注册自定义接口');
      if(interfaceRegisterCustomOnlineFormHiddenFields&&interfaceRegisterCustomOnlineFormHiddenFields.id!="") {
        title = getLabel('26473,23685', '编辑自定义接口');
      }
        return (
            <div className='wea-integration-single'>
              <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@lc6bqa`}
                  title={ title }
                  icon='icon-coms-integration'
                  iconBgcolor='#1a57a0'
                  visible={showRegisterCustomOnlineDialog}
                  hasScroll={true}
                  style={{width: 900, height: 600}}
                  onCancel={()=> {
                      workflowFlowStore.setState({showRegisterCustomOnlineDialog : false});
                      workflowFlowStore.newRegisterCustomOnlineForm.reset();
                  }}
                  buttons={this.getBtns()}
                  moreBtn={{
                      datas :this.getRightMenu(),
                      collectParams: []
                  }}
              >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@8cdesa`}
                    datas={this.getRightMenu()}
                    collectParams={[]}
                >
                    {this.getSearchs()}
                </WeaRightMenu>
              </WeaDialog>
            </div>
        )
    }
}
