import React from "react";
import { inject, observer } from "mobx-react";
import { message, Button } from "antd";
import { toJS } from "mobx";
import { WeaSwitch, WeaTableNew } from "comsMobx";
import { WeaDialog, WeaLocaleProvider, WeaSearchGroup, WeaFormItem, WeaRightMenu, WeaTab, WeaNewScroll, WeaButtonIcon, WeaPopoverHrm } from "ecCom";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import AppDataMappingEditDialog from "./AppDataMappingEditDialog";
import AppDataMappingImportDialog from "./AppDataMappingImportDialog";
import AppDataMappingImportResultDialog from "./AppDataMappingImportResultDialog";
import uuid from 'uuid';
import { checkTableFieldValueUnique } from "../../apis/CommonService";
import NewShare from "./NewShare";
import UploadPic from '../../public/UploadPic';
import copy from 'copy-to-clipboard';

const getLabel = WeaLocaleProvider.getLabel;
const { WeaTable } = WeaTableNew;
const store = ["authenticationCenterStore"];

@inject(...store)
@observer
export default class AppEditDetailDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showSearchAd: false,
      tokenTopTab: [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(81711, "基本信息")}`,
          viewcondition_dt: 0
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(131274, "运行日志")}`,
          viewcondition_dt: 3
        }
      ],
      tokenTopTabAll: [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(81711, "基本信息")}`,
          viewcondition_dt: 0
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(381943, "数据映射")}`,
          viewcondition_dt: 2
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(131274, "运行日志")}`,
          viewcondition_dt: 3
        }
      ],
      topTab: [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(81711, "基本信息")}`,
          viewcondition_dt: 0
        }, {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: getLabel('501806', '授权设置'),
          viewcondition_dt: 1
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(131274, "运行日志")}`,
          viewcondition_dt: 3
        }
      ],
      topTabAll: [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(81711, "基本信息")}`,
          viewcondition_dt: 0
        }, {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: getLabel('501806', '授权设置'),
          viewcondition_dt: 1
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(381943, "数据映射")}`,
          viewcondition_dt: 2
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(131274, "运行日志")}`,
          viewcondition_dt: 3
        }
      ],
      collectParams: {
        favname: `${getLabel(381908, "统一认证中心")}`,
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/AuthenticationCenter",
        importantlevel: 1
      }
    }
  }

  componentWillMount () {
    this.setState({
      showSearchAd: false,
    })
  }

  render () {
    const {
      authenticationCenterStore,
    } = this.props, {
      status,
      registerAppEditForm,
      tableStore2,
      tableStore3,
    } = authenticationCenterStore, {
      registerAppEditFormCodition,
      appEditFormDetailDialogVisible,
      registerAppId = "",
      editDetailDialogSelectedKey = "0",
    } = status, {
      collectParams,
    } = this.state;

    return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@rjbz1d`}
      title={registerAppId ? getLabel('82178', '编辑应用') : getLabel('382079', '注册应用')}
      onCancel={this.closeEditDialog}
      visible={appEditFormDetailDialogVisible}
      style={{ width: 900, height: 600 }}
      hasScroll
      moduleName="integration"
      buttons={this.getBtns()}
      moreBtn={{
        datas: this.getRightMenu(),
        collectParams
      }}
    >
      <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@c59gv2`} />
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@djmodb`}
        datas={this.getRightMenu()}
        collectParams={collectParams}
      >
        {this.getTabComp()}
        <WeaNewScroll
          ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@r3diqa`}
          height={registerAppId ? 550 : 600}
        >
          {
            (registerAppId && editDetailDialogSelectedKey == 0) || (registerAppId == "")
              ? this.getForm(registerAppEditForm, toJS(registerAppEditFormCodition))
              : <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@f5hg54`}
                key={editDetailDialogSelectedKey}
                comsWeaTableStore={editDetailDialogSelectedKey == 2 ? tableStore2 : tableStore3}
                hasOrder={true}
                needScroll={true}
                getColumns={this.getColumns}
                onOperatesClick={this.onOperatesClick}
              />
          }
        </WeaNewScroll>
        <NewShare ecId={`${this && this.props && this.props.ecId || ''}_NewShare@7nf5dj`} />
        <AppDataMappingEditDialog ecId={`${this && this.props && this.props.ecId || ''}_AppDataMappingEditDialog@g8l0r6`} />
        <AppDataMappingImportDialog ecId={`${this && this.props && this.props.ecId || ''}_AppDataMappingImportDialog@h123gt`} />
        <AppDataMappingImportResultDialog ecId={`${this && this.props && this.props.ecId || ''}_AppDataMappingImportResultDialog@ado7jj`} />
      </WeaRightMenu>
    </WeaDialog>
  }

  /**
   * 关闭弹窗
   */
  closeEditDialog = () => {
    const { authenticationCenterStore } = this.props;

    authenticationCenterStore.setState({
      appEditFormDetailDialogVisible: false,
      registerAppId: "",
      editDetailDialogSelectedKey: "0",
    });

    this.setState({
      showSearchAd: false,
    })
  }

  /**
   * 是否渲染weatab组件
   */
  getTabComp = () => {
    const {
      authenticationCenterStore,
    } = this.props, {
      status,
    } = authenticationCenterStore, {
      registerAppId,
      editDetailDialogSelectedKey,
    } = status, {
      showSearchAd,
    } = this.state;

    return registerAppId
      ? <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@3u8rej`}
        datas={this.getTabDatas()}
        keyParam="viewcondition_dt"
        selectedKey={editDetailDialogSelectedKey}
        searchType={editDetailDialogSelectedKey == 2 ? ['advanced'] : []}
        advanceHeight={80}
        buttons={this.getTabButton()}
        searchsAd={this.getAdvancedSearch()}
        showSearchAd={showSearchAd}
        buttonsAd={this.getTabButtonsAd()}
        setShowSearchAd={this.setShowSearchAd}
        hideSearchAd={this.hideSearchAd}
        onChange={this.onTabChange}
      />
      : null;
  }

  /**
   * 编辑的时候获取weatab的datas数据
   */
  getTabDatas = () => {
    const {
      authenticationCenterStore,
    } = this.props, {
      registerAppEditFormOrg,
    } = authenticationCenterStore, {
      topTab,
      topTabAll,
      tokenTopTab,
      tokenTopTabAll,
    } = this.state, {
      account_rules,
      auth_type_,
    } = registerAppEditFormOrg.getFormParams();

    if (['6', '7'].includes(account_rules)) {
      return (auth_type_ === "TOKEN" ? tokenTopTabAll : topTabAll);
    } else {
      return (auth_type_ === "TOKEN" ? tokenTopTab : topTab);
    }
  }

  /**
   * weatab高级搜索的方法
   */
  showSearchAd = bool => this.setState({ showSearchAd: bool });

  hideSearchAd = () => this.setState({ showSearchAd: false });

  /**
   * 高级搜索
   */
  getAdvancedSearch = () => {
    const {
      authenticationCenterStore
    } = this.props, {
      searchForm2,
      status,
    } = authenticationCenterStore, {
      condition2 = [],
    } = status;

    return IntegrationUtil.getAdvancedItem(
      searchForm2,
      condition2,
      this.onSearch,
      false,
      this && this.props && this.props.ecId || '',
      "IntegrationAuthAppEditDetail",
    );
  };

  onSearch = () => {
    const {
      authenticationCenterStore
    } = this.props, {
      status,
    } = authenticationCenterStore;

    authenticationCenterStore.getRegisterAppDataMappingList({ id: status.registerAppId });
    this.setState({ showSearchAd: false });
  }

  getTabButtonsAd () {
    const {
      authenticationCenterStore,
    } = this.props;

    return IntegrationUtil.getSearchBtns(
      this.onSearch,
      () => authenticationCenterStore.searchForm2.reset(),
      () => this.setState({ showSearchAd: false }),
      this && this.props && this.props.ecId || '',
      "IntegrationAuthAppEditDetail",
    );
  }

  /**
   * weatab切换tab时调用的接口
   */
  onTabChange = v => {
    const {
      authenticationCenterStore,
    } = this.props, {
      registerAppId,
    } = authenticationCenterStore.status;

    if (v == 2) {
      authenticationCenterStore.getRegisterAppDataMappingCondition({}, () => {
        authenticationCenterStore.getRegisterAppDataMappingInfo({ id: registerAppId });
      });
    } else if (v == 3) {
      authenticationCenterStore.getRegisterAppLoginLogList({ id: registerAppId });
    } else if (v == 0) {
      authenticationCenterStore.getRegisterAppEditForm({ id: registerAppId });
    } else if (v == 1) {
      authenticationCenterStore.getRegisterAppShareList({ sysid: registerAppId });
    }
    authenticationCenterStore.setState({
      editDetailDialogSelectedKey: v,
    });
  }

  /**
   * weatab的右侧按钮
   */
  getTabButton = () => {
    const {
      authenticationCenterStore
    } = this.props, {
      status,
      tableStore3,
      tableStore2,
    } = authenticationCenterStore, {
      rightMenus2 = [],
      editDetailDialogSelectedKey,
    } = status;

    if (editDetailDialogSelectedKey == 2) {
      return rightMenus2 && rightMenus2.map((m, index) => (
        <Button
          ecId={`${this && this.props && this.props.ecId || ''}_Button@t4v3r6@AuthAppEditDetailSaveBtn`}
          style={{ marginRight: index == 2 ? 10 : 0 }}
          type="primary"
          disabled={m.menuIcon === 'icon-coms-delete' && tableStore2.selectedRowKeys.length === 0}
          onClick={() => this.onRightMenuClick(m.type)}
        >{m.menuName}</Button>
      ));
    } else if (editDetailDialogSelectedKey == "1") {
      return [
        <WeaButtonIcon
          ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@undkwa@AuthAppEditDetailaddBtn`}
          buttonType='add'
          type="primary"
          onClick={() => this.onRightMenuClick("share_add")}
        />,
        <WeaButtonIcon
          ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@qi5djj@AuthAppEditDetaildelBtn`}
          buttonType='del'
          type="primary"
          disabled={tableStore3.selectedRowKeys.length == 0}
          onClick={() => this.onRightMenuClick("share_delete")}
        />
      ];
    }
    return [];
  };

  getIconSize = (form) => {
    const {
      authenticationCenterStore
    } = this.props, {
      logoItems = [],
    } = toJS(authenticationCenterStore);
    return (
      <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@q6o4qs`}
        label={getLabel('125422', '图标大小')}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        {logoItems.map((field, index) => {
          return (
            <div style={{ width: "45%", display: "inline-block", marginLeft: (index == 1) ? "10%" : 0 }}>
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@s9wq9g@integrationauthAppEditDetail${field.domkey}`}
                label={`${field.label}`}
                labelCol={{ span: 9 }}
                wrapperCol={{ span: 15 }}
                error={form.getError(field)}
                tipPosition="bottom"
                style={{ padding: 0 }}
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@c6ixnu@integrationauthAppEditDetail${field.domkey}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />
              </WeaFormItem>
            </div>
          )
        })}
      </WeaFormItem>
    )
  }

  getForm = (form, datas) => {
    const {
      authenticationCenterStore,
    } = this.props, {
      urllinkimagid = "",
      showPic,
      registerAppId,
    } = authenticationCenterStore.status;
    const formParams = form.getFormParams();
    const { isFormInit } = form;
    let group = [];
    isFormInit && datas && datas.forEach((c, groupI) => {
      let items = [];
      c.items && c.items.map(fields => {
        let domkey = fields.domkey[0];
        if ("logo_width" === domkey) {
          return;
        } else if (["logo_height"].includes(domkey) && form.getFormParams().auth_type_ != "" && form.getFormParams().auth_type_ != "TOKEN") {
          items.push({
            com: this.getIconSize(form),
            colSpan: 1,
          })
        } else {
          if ("service_id" === domkey) {
            fields.viewAttr = form.getFormParams().auth_type_ === "OAUTH2" ? 3 : 2;
          }
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6673rh@integrationauthAppEditDetail${fields.domkey}`}
                label={`${fields.label}`}
                labelCol={{ span: `${fields.labelcol}` }}
                wrapperCol={{ span: `${fields.fieldcol}` }}
                error={form.getError(fields)}
                tipPosition="bottom"
              >
                {
                  domkey === "logo_pic"
                    ? <UploadPic ecId={`${this && this.props && this.props.ecId || ''}_UploadPic@k202au@integrationauthAppEditDetail${fields.domkey}`}
                      fields={fields}
                      urllinkimagid={urllinkimagid}
                      showPic={showPic}
                      editRegister={registerAppId ? true : false}
                      onChange={id => authenticationCenterStore.setState({ urllinkimagid: id, showPic: false })}
                      onDel={() => authenticationCenterStore.setState({ urllinkimagid: "", showPic: false })}
                    />
                    : <div style={{ position: "relative" }}>
                      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ydq4xd@integrationauthAppEditDetail${fields.domkey}`} fieldConfig={fields} form={form} formParams={formParams} onChange={v => {
                        if (domkey === 'appid') {
                          let checkParams = {
                            tableName: 'weaver_sso_app',
                            fieldName: 'appid',
                            fieldValue: form.getFormParams().appid.replace(/^(\s*)|(\s*)$/g, ''),
                            idName: 'id',
                            idValue: ''
                          };
                          checkTableFieldValueUnique(checkParams).then(result => {
                            if (result && result.isNotUnique) {
                              form.showError('appid', getLabel('387654', '标识已存在'));
                            }
                          });
                        }
                      }} />
                      <div style={{ position: "absolute", top: "0px", right: "-100px" }}>
                        {this.getFormOtherComp(domkey, fields, form)}
                      </div>
                    </div>
                }
              </WeaFormItem>),
            colSpan: 1,
            hide: form.isHide(fields, (key, allParams) => {
              return this.getFormHiddenFields(domkey, allParams);
            })
          })
        }
      })
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@nolt7s@integrationauthAppEditDetail${groupI}`} center={true} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
    })
    return group;
  }

  /**
   * form按钮的渲染
   */
  getFormOtherComp = (domkey, fields, form) => {
    if (domkey === "appid") {
      return (<Button
        ecId={`${this && this.props && this.props.ecId || ''}_Button@mnxq4b@integrationauthAppEditDetailCreateAppId`}
        type="primary"
        disabled={fields.viewAttr == 1}
        onClick={v => form.updateFields({ appid: uuid() })}
      >{getLabel('15413', '生成')}</Button>);
    } else if (domkey === "app_secret_") {
      return (<Button
        ecId={`${this && this.props && this.props.ecId || ''}_Button@0shdyl@integrationauthAppEditDetailCreateAppSecret`}
        type="primary"
        disabled={fields.viewAttr == 1}
        onClick={v => form.updateFields({ app_secret_: IntegrationUtil.getAppSecret(false, 24) })}
      >{getLabel('15413', '生成')}</Button>);
    } else if (domkey === "pub_key") {
      return (<Button
        ecId={`${this && this.props && this.props.ecId || ''}_Button@0shdyl@integrationauthAppEditDetailCopypublickey`}
        type="primary"
        onClick={v => {
          if (copy(`${form.getFormParams()[domkey]}`)) {
            message.success(getLabel('527609', '应用公钥已经复制成功，您可以使用Ctrl+v粘贴'));
          }
        }}
      >{getLabel('77', '复制')}</Button>);
    }
  }

  /**
   * form表单显隐控制
   */
  getFormHiddenFields = (domkey, allParams) => {
    const {
      authenticationCenterStore,
    } = this.props, {
      registerAppId,
    } = authenticationCenterStore.status;
    let hide = false;

    !["isuse", "auth_type_"].includes(domkey) && allParams.auth_type_ == '' && (hide = true);
    'app_secret_' == domkey && allParams.auth_type_ == "CAS" && (hide = true);
    ['service_id', "logo_pic", "logo_height", "logo_width"].includes(domkey) && allParams.auth_type_ == "TOKEN" && (hide = true);
    ["app_secret_"].includes(domkey) && allParams.auth_type_ == "DELEGATE" && (hide = true);
    ['pub_key'].includes(domkey) && ((!registerAppId) || (registerAppId && allParams.auth_type_ != "DELEGATE")) && (hide = true);
    'definebroswerType' == domkey && allParams.account_rules !== '7' && (hide = true);

    return hide;
  }

  getBtns = () => {
    const {
      authenticationCenterStore,
    } = this.props, {
      status,
      registerAppEditForm,
    } = authenticationCenterStore, {
      editDetailDialogSelectedKey,
      registerAppId = "",
    } = status;
    if (!registerAppId) {
      if (registerAppEditForm.getFormParams().auth_type_ === "TOKEN") {
        return [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@37za1h@integrationauthAppEditDetailSaveBtn`} type="primary" onClick={() => this.onRightMenuClick('BTN_SAVE')}>{getLabel(86, '保存')}</Button>,
        ];
      } else {
        return [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oeeq8w@integrationauthAppEditDetailSaveBtn`} type="primary" onClick={() => this.onRightMenuClick('BTN_SAVE')}>{getLabel(86, '保存')}</Button>,
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@e3khcb@integrationauthAppEditDetailSaveAndOpenBtn`} type="primary" onClick={() => this.onRightMenuClick('BTN_SAVE_OPEN_SHARE')}>{getLabel('521924', '保存并进入授权设置')}</Button>,
        ];
      }
    } else {
      if (editDetailDialogSelectedKey == 0) {
        return [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@de97t1@integrationauthAppEditDetailSave`} type="primary" onClick={() => this.onRightMenuClick('BTN_SAVE')}>{getLabel(86, '保存')}</Button>,
        ];
      }
    }
    return [];
  }

  getRightMenu = () => {
    const {
      authenticationCenterStore,
    } = this.props, {
      status,
      registerAppEditForm,
    } = authenticationCenterStore, {
      rightMenus2,
      rowSelectIds2,
      registerAppId,
      editDetailDialogSelectedKey,
    } = status;

    let btnArr = [];
    if (editDetailDialogSelectedKey == 0) {
      btnArr = [{
        key: 'BTN_SAVE',
        icon: <i className='icon-coms-Preservation' />,
        content: `${getLabel(86, '保存')}`,
        onClick: () => { this.onRightMenuClick('BTN_SAVE') }
      }];
      if ((!registerAppId) && registerAppEditForm.getFormParams().auth_type_ != "TOKEN") {
        btnArr.push({
          key: 'BTN_SAVE_OPEN_SHARE',
          icon: <i className='icon-coms-Preservation' />,
          content: getLabel('521924', '保存并进入授权设置'),
          onClick: () => this.onRightMenuClick('BTN_SAVE_OPEN_SHARE')
        })
      }
    } else if (editDetailDialogSelectedKey == 2) {
      rightMenus2 && rightMenus2.forEach(m => {
        btnArr.push({
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          onClick: () => this.onRightMenuClick(m.type),
          disabled: m.menuIcon === 'icon-coms-delete' && rowSelectIds2.length === 0
        });
      });
      btnArr.push({
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom" />,
        content: `${getLabel(32535, "显示列定制")}`,
        onClick: () => this.onRightMenuClick("BTN_COLUMN")
      });
    }
    return btnArr;
  }

  ipv6Test = (value) => {
    let reg = /^\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*$/;
    let regV4 = /^(\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]|(\*))$/

    let datas = value.split(',');
    for (let i = 0; i < datas.length; i++) {
      if (!reg.test(datas[i].trim()) && (!regV4.test(datas[i].trim()))) {
        return false;
      }
    }
    return true;
  }

  onBaseInfoSave = (type) => {
    const { authenticationCenterStore } = this.props;
    const { registerAppEditForm, status } = authenticationCenterStore;
    const { registerAppId, urllinkimagid = "" } = status;
    const formParams = registerAppEditForm.getFormParams();

    if (formParams.auth_type_ != "OAUTH2") {
      let hideFieldsKey = ["service_id"];
      if (["CAS", "DELEGATE"].includes(formParams.auth_type_)) {
        hideFieldsKey.push("app_secret_");
      }
      window.e9HideFormFieldKeys = hideFieldsKey;
    }
    let checkParams = {
      tableName: 'weaver_sso_app',
      fieldName: 'appid',
      fieldValue: formParams.appid.replace(/^(\s*)|(\s*)$/g, ''),
      idName: 'id',
      idValue: ''
    };
    IntegrationUtil.checkUnique(checkParams, registerAppEditForm, "appid", "2", registerAppId, () => {
      let value = formParams.allow_ip;
      let ipv6 = this.ipv6Test(value.trim());
      formParams.logo_pic = urllinkimagid;
      IntegrationUtil.onCheck(registerAppEditForm, () => {
        if (value.trim() == '' || (value.trim() && ipv6)) {
          let params = Object.assign({ id: registerAppId, operation: registerAppId ? "edit" : "add" }, formParams);
          authenticationCenterStore.getRegisterAppOperation(params, (record) => {
            if ('BTN_SAVE_OPEN_SHARE' === type) {
              authenticationCenterStore.setState({
                editDetailDialogSelectedKey: '1',
                registerAppId: record.id,
              });
              authenticationCenterStore.getRegisterAppShareList({ sysid: record.id });
            }
          }, 'BTN_SAVE_OPEN_SHARE' != type);
        } else {
          registerAppEditForm.showError('allow_ip', getLabel('531149', "ip格式不合法"));
        }
      });
    })
  }

  onRightMenuClick = (type) => {
    const { authenticationCenterStore } = this.props;
    const { registerAppEditForm, status, tableStore2, tableStore3 } = authenticationCenterStore;
    const { registerAppId, editDetailDialogSelectedKey } = status;
    const formParams = registerAppEditForm.getFormParams();

    if (type === "BTN_COLUMN") {
      if (editDetailDialogSelectedKey == 2) {
        tableStore2.setColSetVisible(true);
        tableStore2.tableColSet(true);
      }
    } else if ("BTN_SAVE_OPEN_SHARE" === type) {
      this.onBaseInfoSave('BTN_SAVE_OPEN_SHARE');
    } else if (type == 'BTN_SAVE') {
      this.onBaseInfoSave('BTN_SAVE');
    } else if (type == 'rb_1') {
      //注册数据映射
      this.doDataMappingEditById({ randomField0: '', appid: formParams.appid });
    } else if (type == 'rb_2') {
      //导入
      authenticationCenterStore.registerAppDataMappingImportForm.reset();
      let params = Object.assign({ id: registerAppId, operation: "import" }, formParams);
      authenticationCenterStore.getRegisterAppDataMappingImportForm(params);
      authenticationCenterStore.setState({ appEditFormDetailDataMappingImportDialogVisible: true });
    } else if (type == 'rb_3') {
      //删除
      if (toJS(tableStore2.selectedRowKeys).length > 0) {
        authenticationCenterStore.confirmModal(
          `${getLabel(385625, '确定要删除选择的记录吗？')}`,
          authenticationCenterStore.getRegisterAppDataMappingOperation,
          {
            operation: 'delete', id: toJS(tableStore2.selectedRowKeys)
          });
      }
    } else if (type === "share_delete") {
      IntegrationUtil.doConfirm(
        getLabel(385625, '确定要删除选择的记录吗？'),
        authenticationCenterStore.getRegisterAppShareForm,
        { operate: "delShare", sysid: registerAppId, id: toJS(tableStore3.selectedRowKeys) }
      )
    } else if (type === "share_add") {
      authenticationCenterStore.setState({
        showAddShare: true
      })
      authenticationCenterStore.getRegisterAppShareForm({ operate: "getAddShareForm", sysid: registerAppId });
    }
  }

  onOperatesClick = (record, index, operate) => {
    const {
      authenticationCenterStore,
    } = this.props, {
      registerAppId,
      editDetailDialogSelectedKey,
    } = authenticationCenterStore.status;

    if (operate.index == "0") {
      this.doDataMappingEditById(record);
    } else if (operate.index == "1") {
      //删除
      if (editDetailDialogSelectedKey == "1") {
        IntegrationUtil.doConfirm(
          getLabel(15097, '确定要删除吗？'),
          authenticationCenterStore.getRegisterAppShareForm,
          { operate: "delShare", sysid: registerAppId, id: record.randomFieldId }
        )
      } else {
        authenticationCenterStore.confirmModal(
          `${getLabel(15097, '确定要删除吗？')}`,
          authenticationCenterStore.getRegisterAppDataMappingOperation,
          { operation: 'delete', id: record.randomField0 }
        );
      }
    }
  };

  doDataMappingEditById = (record) => {
    const { authenticationCenterStore } = this.props;
    const { registerAppEditForm } = authenticationCenterStore;
    authenticationCenterStore.registerAppDataMappingEditForm.reset();
    authenticationCenterStore.setOperateDataMappingIndex(record.randomField0);
    authenticationCenterStore.getRegisterAppDataMappingEditForm({ id: record.randomField0, appid: record.appid, account_rules: registerAppEditForm.getFormParams().account_rules });
    authenticationCenterStore.setState({ appEditFormDetailDataMappingDialogVisible: true });
  }

  getColumns = (columns = []) => {
    return columns && columns.map(item => {
      if (item.dataIndex === "LoginId") {
        item.render = (text, record) => {
          return <a onClick={() => this.doDataMappingEditById(record)}>{text}</a>
        }
      }
      return item;
    })
  }
}
