import React, { Component } from 'react';
import {toJS} from "mobx";
import {Button, Spin} from "antd";
import {observer, inject} from "mobx-react";
import {WeaDialog, WeaLocaleProvider, WeaRightMenu} from 'ecCom';
import {getForm, onCheck, checkUnique, doConfirm} from '../../util/IntegrationUtil';

const {getLabel} = WeaLocaleProvider;

@inject("alyMail")
@observer
class AddOrEdit extends Component {

    componentWillUnmount() {
      const {alyMail} = this.props;
      alyMail.closeDialog();
    }
    
    getButtons = () => {
      const {status: {formLoading, buttonDisabled}} = this.props.alyMail;
      return [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f0uefe@integrationIntemailAddDialogButtonSave`} type="primary" disabled={formLoading || buttonDisabled} onClick={() => this.onMenuClick("BTN_SAVE")}>{getLabel(30986, "保存")}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rql2zx@integrationIntemailAddDialogButtonTest`} type="primary" disabled={formLoading || buttonDisabled} onClick={() => this.onMenuClick("BTN_TEST")}>{getLabel(25496, "测试")}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3uhgdp@integrationIntemailAddDialogButtonInit`} type="primary" disabled={formLoading || buttonDisabled} onClick={() => this.onMenuClick("BTN_INIT")}>{getLabel(20873, "初始化")}</Button>,
      ];  
    }

    getRightMenus = () => {
      const {status: {formLoading, buttonDisabled}} = this.props.alyMail;
      return [{
        key: "BTN_SAVE",
        icon: <i className="icon-coms-Preservation"/>,
        content: getLabel(30986, "保存"),
        disabled: formLoading || buttonDisabled,
        onClick: () => this.onMenuClick("BTN_SAVE"),
      }, {
        key: "BTN_TEST",
        icon: <i className="icon-coms-currency-Task"/>,
        content: getLabel(25496, "测试"),
        disabled: formLoading || buttonDisabled,
        onClick: () => this.onMenuClick("BTN_TEST"),
      }, {
        key: "BTN_INIT",
        icon: <i className="icon-coms-operation"/>,
        content: getLabel(20873, "初始化"),
        disabled: formLoading || buttonDisabled,
        onClick: () => this.onMenuClick("BTN_INIT"),
      }]
    }

    handleMenuClick = (type) => {
      const {alyMail} = this.props;
      const {form, mailForm, getMailSaveOperation, getMailAddSetForm, status: {operateIndex}} = alyMail; 
      let params = {}
      if(type === "BTN_TEST") {
        params = {operate: "test", mailMasterId: operateIndex};
      }else if(type === "BTN_INIT") {
        params = {operate: "init", mailMasterId: operateIndex};
      } else if ("BTN_SAVE" === type) {
        params = {operate: "save", mailMasterId: operateIndex};
      }
      let saveCallBack = (callback) => checkUnique({
        tableName: 'Mail_master',
        fieldName: 'syscode',
        fieldValue: form.getFormParams().syscode.replace(/^(\s*)|(\s*)$/g, ''),
        idName: 'id',
        idValue: operateIndex
      }, form, "syscode", "2", operateIndex, callback);
      onCheck(form, () => {
        if(operateIndex == "") {
          if("BTN_TEST" === type || "BTN_INIT" === type) {
            onCheck(mailForm, () => {
              saveCallBack(() => {
                getMailSaveOperation({...params, operate: "save"}, (result) => {
                  alyMail.setState({operateIndex: result.maxId});
                  getMailAddSetForm({mailMasterId: result.maxId}, () => getMailSaveOperation({...params, mailMasterId: result.maxId}));
                })
              })
            });
          } else {
            onCheck(mailForm, () => saveCallBack(() => getMailSaveOperation(params)));
          }
        }else {
          if("BTN_TEST" === type || "BTN_INIT" === type) {
            saveCallBack(() => {
              getMailSaveOperation({...params, operate: "save"}, () => {
                getMailAddSetForm({mailMasterId: operateIndex}, () => getMailSaveOperation(params));
              })
            })
          } else {
            saveCallBack(() => getMailSaveOperation(params));
          }
        }
      });
    }

    onMenuClick = (type) => {
      if("BTN_INIT" === type) {
        doConfirm(getLabel('519656','确定要初始化吗？'), () => {
          this.handleMenuClick(type);
        });
      } else {
        this.handleMenuClick(type);
      }
    }

    handleChange = (form, formParams, fields) => {
      const {alyMail} = this.props;
      const {status: {operateIndex}} = alyMail;
      const key = fields.domkey[0];
      if(key === "mailtype") {
        alyMail.getMailSelectSetForm(form.getFormParams());
      }else if(key === "syscode") {
        const value = form.getFormParams()[key].replace(/^(\s*)|(\s*)$/g, '');
        if(value) {
          checkUnique({
            tableName: 'Mail_master',
            fieldName: 'syscode',
            fieldValue: form.getFormParams()[key].replace(/^(\s*)|(\s*)$/g, ''),
            idName: 'id',
            idValue: operateIndex
          }, form, key, "2", operateIndex);
        }
      }
    }

    otherDom = (form, fields) => {
      const key = fields.domkey[0];
      if(key === "email163_pubkey") {
        return <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7jpdjd`} style={{position: 'absolute', marginLeft: 30, marginTop: 25}} onClick={this.props.alyMail.createSecretKey}>{getLabel('503390','生成公私钥')}</Button>
      }else {
        return null;
      }
    }

    render() {
        const {alyMail} = this.props;
        const {status: {baseDialogVisible, condition, operateIndex, formLoading, mailFormCondition, mailFormLoading, buttonDisabled}, form, mailForm} = alyMail;
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@g4kuwb`} 
              title={operateIndex ? getLabel('521921','编辑邮箱') : getLabel('521922','新建邮箱')}
              visible={baseDialogVisible}
              style={{width: 800, height: 600}}
              onCancel={alyMail.closeDialog}
              hasScroll
              buttons={this.getButtons()}
              moreBtn={{
                datas: this.getRightMenus(),
                collection: []
              }}
            >
              <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@r84m7d`}
                datas={this.getRightMenus()}
                collection={[]}
              >
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@wo4ork`} spinning={buttonDisabled}>
                  {
                    operateIndex 
                      ? (!formLoading) && getForm(form, toJS(condition), true, this.handleChange, this.otherDom)
                      : <div>
                          {(!formLoading) && getForm(form, toJS(condition), false, this.handleChange)}
                          <div style={{marginTop: -25}}>
                            {(!mailFormLoading) && getForm(mailForm, toJS(mailFormCondition), false, null, this.otherDom)}
                          </div>
                      </div>
                  }
                </Spin>
              </WeaRightMenu>
            </WeaDialog>
        );
    }
}

export default AddOrEdit;