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

const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const { GeneralTitleColor } = IntegrationUtil;

@inject("webservice")
@observer
export default class Main extends React.Component {
  onCancel = () => {
    const { webservice } = this.props;
    webservice.doInitCreate();
  }

  getOtherCom = () => {
    const { webservice } = this.props;
    const { parseWSDL, formCreate } = webservice;
    const allParams = formCreate.getFormParams();
    const com = <div style={{ position: 'absolute' }}>
      <a className='webservicecreate-btn' onClick={() => parseWSDL({ webserviceurl: allParams.webserviceurl, type: '1' }, 'wsdl')}>{getLabel(32395,'解析')}WSDL</a>
      <a className='webservicecreate-btn' onClick={() => parseWSDL({ webserviceurl: allParams.webserviceurl, type: '2' }, 'checked')}>{getLabel(32396,'检查更新')}</a>
    </div>;
    return com;
  }

  onChange = (datas) => {
    const { webservice } = this.props;
    const { setState } = webservice;
    setState({wsdlParamData:datas});
  }

  save = () => {
    const { webservice } = this.props;
    let { status: { wsdlParamData }, formCreate, doSave } = webservice;
    wsdlParamData = toJS(wsdlParamData);
    const result = this.refs.serviceRegister.doValidate();
    formCreate.validateForm().then(f => {
      if (f.isValid) {
        if (result.pass) {
          wsdlParamData.forEach((v, l) => {
            if (v.methodid.indexOf('$') > -1) {
              wsdlParamData[l].methodid = '0';
            }
          });
          doSave(wsdlParamData);
        }
      } else {
        f.showErrors();
      }
    })
  }

  del = () => {
    const { webservice } = this.props;
    const { delList, status: { webserviceid } } = webservice;
    delList({ pointid: webserviceid }, false);
  }

  onClick = type => {
    const { webservice } = this.props;
    const { formCreate, status } = webservice;
    let checkParams = {
      tableName: 'wsregiste',
      fieldName: 'customname',
      fieldValue: formCreate.getFormParams().customname.replace(/^(\s*)|(\s*)$/g, ''),
      idName: 'id',
      idValue: webservice.editRecordId
    };
    switch (type) {
      case 'BTN_Save': 
        checkTableFieldValueUnique(checkParams).then(result => {
            if(result&&result.isNotUnique) {
              formCreate.showError('customname',getLabel('129943','名称已存在'));
            }else {
              this.save();
            }
        });
      break;
      case 'BTN_Delete': this.del(); break;
    }
  }

  getSearchs = (form, datas, needTigger = true, center = true, lableCol, fieldcol, otherCom = null) => {
    const { webservice } = this.props;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.map((c, index) => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@dfs0fs@integrationWebserviceCreateForm${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: lableCol ? lableCol : `${fields.labelcol}` }}
              wrapperCol={{ span: fieldcol ? fieldcol : `${fields.fieldcol}` }}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@xp7e9w@integrationWebserviceCreateForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} 
                onChange={v => {
                  if(getKey(fields) === 'customname') {
                    let checkParams = {
                        tableName: 'wsregiste',
                        fieldName: 'customname',
                        fieldValue: form.getFormParams().customname.replace(/^(\s*)|(\s*)$/g, ''),
                        idName: 'id',
                        idValue: webservice.editRecordId
                    };
                    checkTableFieldValueUnique(checkParams).then(result => {
                        if(result&&result.isNotUnique) {
                            form.showError('customname',getLabel('129943','名称已存在'));
                        }
                    });
                  }
                }}
              />
              {fields.showOtherCom && otherCom}
            </WeaFormItem>),
          colSpan: 1
        })
      });
      if (needTigger) {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ulfcmo@integrationWebserviceCreateForm${index}`}
          center={center} col={1} needTigger={needTigger} title={c.title}
          showGroup={c.defaultshow || true} items={items} />)
      } else {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@gwxjln@integrationWebserviceCreateForm${index}`} center={center} col={1} needTigger={needTigger}
          showGroup={c.defaultshow || true} items={items} />)
      }
    });
    return group;
  }

  getBtn = () => {
    const { webservice } = this.props;
    const { rightMenuForm } = webservice.status;
    let btnArr = [];

    rightMenuForm && rightMenuForm.map( v => {
      if(v.type == 'BTN_Save') {
        btnArr.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rz25oc@integrationWebserviceCreateButton${v.type}`} type='primary' onClick={() => this.onClick(v.type)}>{v.menuName}</Button>
        )
      }  
    })
    
    return btnArr;
  }

  getRightMenu = () => {
    const { webservice } = this.props;
    const { rightMenuForm } = webservice.status;
    let btnArr = [];

    rightMenuForm && rightMenuForm.map( v => {
      if(v.type == 'BTN_Save') {
        btnArr.push({
          key: v.type,
          content: v.menuName,
          icon: <span className={v.menuIcon} />,
          onClick: () => this.onClick(v.type),
        })
      }
    })

    return btnArr;
  }

  render() {
    const { 
      webservice, 
    } = this.props, { 
      status: { 
        type, 
        visible, 
        conditionCreate, 
        loadingCreate, 
        columns, 
        showRegister, 
        analysisWSDL, 
        selectedRowKeys, 
        wsdlParamData, 
        wsdlParamPass, 
      }, 
      formCreate, 
      setState, 
      addRegister, 
      delRegister, 
    } = webservice;
    const validator = {
      rules: {
        methodname: 'required',
      },
      errorMessage: {
        required: getLabel(385869,'此项必填'),
      },
    }, collectParams = {
      favname: getLabel(33717, "WebService注册"),
      favouritetype: 2,
      objid: 0,
      importantlevel: 1,
      link: 'wui/engine.html#/main/integration/webservice',
    };
    const title = type === 'create' ? getLabel('365,33717','新建WebService注册') : getLabel('26473,33717','编辑WebService注册');
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zaf8rw`}
        title={title}
        className='wea-integration-webservicecreate'
        visible={visible}
        style={{ width: 1000, height: 500 }}
        icon={GeneralTitleColor.icon}
        iconBgcolor={GeneralTitleColor.iconBgcolor}
        onCancel={this.onCancel}
        hasScroll={true}
        moreBtn={{
          datas: this.getRightMenu(),
          collectParams: collectParams,
        }}
        buttons={this.getBtn()}>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@pj50mo`}
          datas={this.getRightMenu()}
          collectParams={collectParams}>
          {this.getSearchs(formCreate, toJS(conditionCreate), true, true, 7, 16, this.getOtherCom())}
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@ytxvrr`} spinning={loadingCreate}>
            <div className='register'>
              <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@reiai8`}
                title={getLabel(32397,'注册方法')}
                showGroup={showRegister}
                onVisibleChange={(showRegister) => setState({ showRegister })}
                customComponent={[
                  <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@5qijhn@integrationWebserviceCreateButtonadd`} buttonType='add' type="primary" disabled={analysisWSDL} onClick={addRegister} />,
                  <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@t8nsyk@integrationWebserviceCreateButtondel`} buttonType='del' type="primary" disabled={isEmpty(toJS(selectedRowKeys))} onClick={delRegister} />,
                ]}><WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@6bhl87`}
                  ref='serviceRegister'
                  tableProps={{showEmptyText:false}}
                  rowKey='methodid'
                  validator={validator}
                  showTitle={false}
                  showAdd={false}
                  showDelete={false}
                  showCopy={false}
                  showMove={false}
                  datas={!analysisWSDL && wsdlParamPass ? toJS(wsdlParamData) : []}
                  selectedRowKeys={toJS(selectedRowKeys)}
                  onRowSelect={selectedRowKeys => setState({ selectedRowKeys })}
                  columns={toJS(columns)}
                  onChange={this.onChange} />
              </WeaSearchGroup>
            </div>
          </Spin>
        </WeaRightMenu>
      </WeaDialog>
    );
  }
}
