import React from "react";
import { inject, observer } from "mobx-react";
import { Button, message } from "antd";
import { toJS } from "mobx";
import { WeaDialog, WeaLocaleProvider, WeaRightMenu } from "ecCom";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import OfsInfoBaseInfoContent from './OfsInfoBaseInfoContent';

const getLabel = WeaLocaleProvider.getLabel;

@inject("todoCenterStore")
@observer
export default class OfsInfoAddFormDialog extends React.Component {

  closeDialog = () => {
    const { todoCenterStore } = this.props;
    todoCenterStore.setState({ ofsInfoAddFormDialogVisible: false });
  }

  getFooterButton = () => {
    return [
      <Button
        ecId={`${this && this.props && this.props.ecId || ''}_Button@7bs3n8@integrationTodoCenterAddFormButtonSave`}
        type="primary"
        onClick={() => this.onRightMenuClick('BTN_SAVE')}
      >{getLabel('86', '保存')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rjtqsg@integrationTodoCenterAddFormButtonSaveAndSetting`} type='primary' onClick={() => this.onRightMenuClick('BTN_SAVE_AND_OPEN')}>{getLabel(32159, '保存并进入详细设置')}</Button>
    ];
  }

  getRightMenu = () => {
    return [{
      key: 'BTN_SAVE',
      icon: <i className='icon-coms-Preservation' />,
      content: `${getLabel(86, '保存')}`,
      onClick: () => this.onRightMenuClick('BTN_SAVE')
    }, {
      key: 'BTN_SAVE_AND_OPEN',
      icon: <i className='icon-coms-Preservation' />,
      content: `${getLabel(125540, '保存后详细设置')}`,
      onClick: () => this.onRightMenuClick('BTN_SAVE_AND_OPEN')
    }];
  }

  onRightMenuClick = (type) => {
    const { todoCenterStore } = this.props;
    const { ofsInfoAddForm, status } = todoCenterStore;
    const { ofsInfoAddFormHiddenFields, networkIPData } = toJS(status);

    if (['BTN_SAVE', 'BTN_TEST', 'BTN_SAVE_AND_OPEN'].includes(type)) {
      let saveCallBack = null;
      if (type == 'BTN_SAVE') {
        saveCallBack = (params) => {
          todoCenterStore.getOfsInfoOperation(params, (result) => {
            if (result.errorMsg) {
              message.error(result.errorMsg);
            }
          });
        }
      } else if (type == 'BTN_SAVE_AND_OPEN') {
        saveCallBack = (params) => {
          todoCenterStore.getOfsInfoOperation(params, (result) => {
            if (result && result.id) {
              params.operation = "edit";
              params.id = result.id;
              this.doEditDetailById(params);
            }
          });
        }
      }

      // QC1248320、QC1248316 必填项提示的优化
      const formParams = ofsInfoAddForm.getFormParams();
      window.e9HideFormFieldKeys = [];
      if('1' != formParams.iscustom || '1' != formParams.isuse) {
        // 如果 【自定义提醒】 关闭 或者 【启用提醒】 关闭，则 【自定义提醒接口实现类】 非必填
        window.e9HideFormFieldKeys.push('customclass');
      }
      if('1' != formParams.ismonitor) {
        // 如果 【监控】 未开启，则 【被提醒人员】 非必填
        window.e9HideFormFieldKeys.push('reminder');
      }


      IntegrationUtil.onCheck(ofsInfoAddForm, () => {
        let checkParams1 = {
          tableName: 'ofs_sysinfo',
          fieldName: 'syscode',
          fieldValue: formParams.syscode.replace(/^(\s*)|(\s*)$/g, ''),
        };
        IntegrationUtil.checkUnique(checkParams1, ofsInfoAddForm, "syscode", "2", "", () => {
          let checkParams2 = {
            tableName: 'ofs_sysinfo',
            fieldName: 'sysshortname',
            fieldValue: formParams.sysshortname.replace(/^(\s*)|(\s*)$/g, ''),
          };
          IntegrationUtil.checkUnique(checkParams2, ofsInfoAddForm, "sysshortname", "5", "", () => {
            let checkParams3 = {
              tableName: 'ofs_sysinfo',
              fieldName: 'sysfullname',
              fieldValue: formParams.sysfullname.replace(/^(\s*)|(\s*)$/g, ''),
            };
            IntegrationUtil.checkUnique(checkParams3, ofsInfoAddForm, "sysfullname", "6", "", () => {
              let params = Object.assign(ofsInfoAddFormHiddenFields, formParams);
              let httpRegExp = /^http(s){0,1}:\/\/[^\s]*/;
              if (params.pcprefixurl != '') {
                if (!httpRegExp.test(params.pcprefixurl)) {
                  message.warning(getLabel('532054', 'PC地址不合法'));
                  ofsInfoAddForm.showError('pcprefixurl', getLabel('390458', "前缀需要以http://或https://开头"));
                  return;
                }
              }
              if (params.pcouterfixurl != '') {
                if (!httpRegExp.test(params.pcouterfixurl)) {
                  message.warning(getLabel('532054', 'PC地址不合法'));
                  ofsInfoAddForm.showError('pcouterfixurl', getLabel('390458', "前缀需要以http://或https://开头"));
                  return;
                }
              }
              if (params.securityip != '') {
                let vilidflag = 0;
                let regipv4 = /^(\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]|(\*))$/;
                function isIPv6 (str) {
                  return str.match(/:/g).length <= 7 && /^\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*$/i.test(str);
                }
                let valdata = params.securityip.split(',')
                for (let i = 0; i < valdata.length; i++) {
                  if (/\:/ig.test(valdata[i])) {
                    if (isIPv6(valdata[i]) == false) {
                      vilidflag = 1;
                      break;
                    } else {
                      vilidflag = 0;
                    }
                  } else {
                    if (regipv4.test(valdata[i]) == true) {
                      vilidflag = 0;
                    } else {
                      vilidflag = 1; break;
                    }
                  }
                }

                if (vilidflag == 1) {
                  ofsInfoAddForm.showError('securityip', getLabel('531149', "ip格式不合法"));
                  message.warning(getLabel('532055', '接口安全ip不合法'));
                  return;
                }
              }
              if (params.appprefixurl != '') {
                if (!httpRegExp.test(params.appprefixurl)) {
                  ofsInfoAddForm.showError('appprefixurl', getLabel('390458', "前缀需要以http://或https://开头"));
                  return;
                }
              }
              params.dtinfo_networkIPData = JSON.stringify(networkIPData);
              if (saveCallBack && typeof (saveCallBack) === "function") {
                saveCallBack(params);
              }
            })
          })
        })
      });
    }
  }

  doEditDetailById = (record) => {
    const { todoCenterStore } = this.props;
    todoCenterStore.setOperateRecordIndex(record.id);
    todoCenterStore.getOfsInfoAddForm({ sysid: record.id });
    todoCenterStore.setState({ ofsInfoEditDetailDialogVisible: true });
  }

  render () {
    const {
      todoCenterStore,
    } = this.props, {
      status,
    } = todoCenterStore, {
      ofsInfoAddFormDialogVisible,
    } = status;

    return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zj5ecr`}
      title={getLabel('31691,31694', '注册异构系统')}
      onCancel={this.closeDialog}
      visible={ofsInfoAddFormDialogVisible}
      style={{ width: 800, height: 600 }}
      hasScroll
      moduleName="integration"
      buttons={this.getFooterButton()}
      moreBtn={{
        datas: this.getRightMenu(),
        collectParams: []
      }}
    >
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ufuqgp`}
        datas={this.getRightMenu()}
        collectParams={[]}
      >
        <OfsInfoBaseInfoContent ecId={`${this && this.props && this.props.ecId || ''}_OfsInfoBaseInfoContent@vts2nb`} />
      </WeaRightMenu>
    </WeaDialog>;
  }
}
