import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, Modal} from "antd";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import WhiteList from "../../public/WhiteList";
import {
  WeaLocaleProvider,
  WeaTop,
  WeaRightMenu,
  WeaFormItem,
  WeaTools,
  WeaSearchGroup,
  WeaTableEditable,
  WeaNewScroll,
  WeaInput,
} from "ecCom";
import DoubleInput from '../doubleInput';
import * as IntegrationUtil from "../../util/IntegrationUtil";
import { WeaSwitch } from "comsMobx";
import PopoverButton from '../../public/PopoverButton';
import "../../style/webxml.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("webseal")
@inject("whiteListStore")
@observer
export default class IMrtx extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editExcludeTableSelected: [],
      editRuleTableSelected:[],
      showRowSelect: true,
      clazz: 'weaver.interfaces.sso.webseal.WebSealSSOLoginFilter'
    };
  }

  componentDidMount() {
    const { webseal, whiteListStore } = this.props;
    whiteListStore.getRegisterFilterId({filter_clazz: this.state.clazz}, webseal.doInit);
  }

  onRightMenuClick = (type, recordId) => {
    const { webseal } = this.props;
    switch (type) {
      case "save":
        if(this.table1) {
          let result = this.table1.doValidate();
          if(!result.pass ) {
            return
          }
        }
        if(this.table2) {
          let result = this.table2.doValidate();
          if(!result.pass ) {
            return
          }
        }
        webseal.save();
        break;
      case "test":
        Modal.confirm({
          title: getLabel(129118,'提交后请手动重启服务，以确保系统可以正常使用！'),
          onOk: webseal.complete,
        })
        break;
    }
  };

  getBtns = () => {
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@c47p2m@integrationWebsealButtonSave`} type="primary" onClick={() => this.onRightMenuClick("save")}>{getLabel("86", "保存")}</Button>,
      <PopoverButton ecId={`${this && this.props && this.props.ecId || ''}_PopoverButton@kyslni@integrationWebsealButtonTest`} 
        content={getLabel("555", "完成")}
        type="primary"
        onClick={() => this.onRightMenuClick("test")}
      />
    ];
  };

  getColumns = (columns=[]) => {
    let cols = [];
    columns && columns.forEach((col)=> {
      if(col&&col.dataIndex&&(col.dataIndex=="excludedescription"||col.dataIndex=="ruledescription")){
        col.com = [{
          type: 'CUSTOM',
          key: `${col.dataIndex}`,
          render: (text, record, index, onEdit) => {
            return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@5ot01v@integrationWebsealColumns${col.dataIndex}`}
              value={record[col.dataIndex]}
              inputType={"multilang"}
              isMulti={true}
              isBase64={true}
              viewAttr={record.viewAttr =='1'?'1':2}
              hasBorder
              onChange={(v) => {
                record[col.dataIndex] = v;
                onEdit({
                  type: 'CUSTOM',
                  record,
                  index,
                })
              }}
            />
          }
        }]
      }else{
        col.com = [{
          type: 'CUSTOM',
          key: `${col.dataIndex}`,
          render: (text, record, index, onEdit) => {
            return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@ac8dkf@integrationWebsealColumns${col.dataIndex}`}
              value={record[col.dataIndex]}
              viewAttr={record.viewAttr =='1'?'1':'3'}
              hasBorder
              onChange={(v) => {
                record[col.dataIndex] = v;
                onEdit({
                  type: 'CUSTOM',
                  record,
                  index,
                })
              }}
            />
          }
        }]
      }

      cols.push(col);
    })
    return cols;
  }

  getRightMenu() {
    let btnArr = [{
      key: "save",
      icon: <i className="icon-coms-Preservation" />,
      content: getLabel("86", "保存"),
      onClick: () => this.onRightMenuClick("save")
    },{
      key: "test",
      icon: <i className="icon-coms-Approval" />,
      content: getLabel("555", "完成"),
      onClick: () => this.onRightMenuClick("test")
    }];
    return btnArr;
  }

  getExcludeRowSelection = rowSelection => {
    const sel = { ...rowSelection };
    sel.getCheckboxProps = record => {
      return { disabled: record.iscustom === '0' };
    };
    return this.state.showRowSelect ? sel : null;
  }

  excludeTableEditOperate = type => {
    const { webseal } = this.props;
    const { excludeTableEdit } = webseal;
    switch (type) {
      case "add":
        excludeTableEdit.doAdd();
        break;
      case "del":
        excludeTableEdit.doDelete();
        break;
    }
  };

  ruleTableEditOperate = type => {
    const { webseal } = this.props;
    const { ruleTableEdit } = webseal;
    switch (type) {
      case "add":
        ruleTableEdit.doAdd();
        break;
      case "del":
        ruleTableEdit.doDelete();
        break;
    }
  };

  willDelete = (datas, keys) => new Promise((resolve, reject) => {
    Modal.confirm({
      content:`${getLabel(385625, '确定要删除选择的记录吗？')}`,
      onOk: () => resolve(true),
      onCancel: () => resolve(false)
    })
  })

  /**获取白名单的helpfulTip */
  getWhiteListTip = () => {
    return <div style={{wordBreak: "break-all"}}>
      <p>1、{getLabel('514625','点击‘+’如果选择不到需要的白名单地址，可以去【统一白名单地址配置】-【通用白名单】里面进行设置；【统一白名单地址配置】页面需要“统一白名单地址配置”权限')}。</p>
      <p>2、{getLabel('514626','白名单地址也可以直接在【统一白名单地址配置】-【过滤器白名单】中进行维护，过滤器对应weaver.interfaces.sso.webseal.WebSealSSOLoginFilter')}。</p>
    </div>
  }

  getFormSearchs(form, datas){
    const { webseal } = this.props;
    const {tableStore, status} = webseal;
    const { res, tableDatas, tableColumns, tableColumns2, tableDatas2} = toJS(status);
    const {isFormInit} = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.forEach((c, idx) => {
      let items = [];
      c.items && c.items.forEach(field => {
        let leftDis = idx == 5 ? -17 : 0;
        let hideLabel = false;
        let fieldcolSpan = field.fieldcol;
        const key = WeaTools.getKey(field);
        const bindObj = form.$(key);
        if ('DESCRIPTION' == field.conditionType) {
          fieldcolSpan = 24;
        }
        let dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@4qnpjw@integrationWebsealForm${field.domkey[0]}`} fieldConfig={field} form={form} formParams={formParams}/>
        if ('oaaddress' == field.domkey[0]) {
          dom = <div style={{position: 'relative'}}>
            {dom}
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sepqv7@integrationWebsealForm${field.domkey[0]}`} style={{position: 'absolute', right:'-55px', top: '4px'}}
              onClick={()=> {this.refs.systemSetting && this.refs.systemSetting.onShow()}}
              size="small" type={'ghost'}>{getLabel("19653", "设置")}</Button>
          </div>
        }
        if ('loginPage' == field.domkey[0] ) {
          dom = <DoubleInput ecId={`${this && this.props && this.props.ecId || ''}_DoubleInput@2rwyqb@integrationWebsealForm${field.domkey[0]}`}
            leftValue={formParams.oaaddress || res.defaultEcologyUrl}
            {...bindObj.bind()}
          />
        }
        if ('logoutPage' == field.domkey[0] ) {
          dom = <DoubleInput ecId={`${this && this.props && this.props.ecId || ''}_DoubleInput@xfwcij@integrationWebsealForm${field.domkey[0]}`}
            leftValue={formParams.oaaddress || res.defaultEcologyUrl}
            {...bindObj.bind()}
          />
        }
        items.push({
          com:(<div style={{marginLeft: leftDis}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@rn3kyf@integrationWebsealForm${field.domkey[0]}`}
              hideLabel={hideLabel}
              label={field.label}
              labelCol={{span: field.labelcol}}
              wrapperCol={{span: fieldcolSpan}}
              error={form.getError(field)}
              fieldType={field.conditionType.toUpperCase()}
              tipPosition="bottom"
            >
              {dom}
            </WeaFormItem>
          </div>),
          colSpan: 1,
        })
      });
      if (formParams.isUse !== '1' && idx > 0 && idx < 5) {
      } else {
        if (idx !== 4 && idx !== 3 && idx !== 5) {
          group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ejb71r@integrationWebsealForm${idx}`} center multiCol col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        }else if (idx == 5) {
          group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@fsb0pw@integrationWebsealForm${idx}`} multiCol col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        }else if (idx == 3) {
          group.push(<div className="inte-webseal-whitelist-custom"><WhiteList ecId={`${this && this.props && this.props.ecId || ''}_WhiteList@0escmc@integrationWebsealForm${idx}`} helpfulTip={this.getWhiteListTip()} /></div>)
        }else if (idx == 4) {
          group.push(
            <div style={{paddingLeft:25, paddingRight:25}}>
              <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@xcpfn0@integrationWebsealForm${idx}`}
                ref={el => this.table2 = el}
                validator={{
                  rules: {
                    securityrule: 'required',
                  },
                }}
                rowKey = {'key'}
                title={c.title}
                showCollapse={true}
                columns={this.getColumns(tableColumns2)}
                getRowSelection={this.getRowSelection}
                datas = {tableDatas2}
                onChange={(datas)=> {
                  webseal.setState({tableDatas2: datas})
                }}
                showRowSelect={true}
                showCopy={false}
                willDelete={this.willDelete}
                selectedRowKeys={this.state.editRuleTableSelected}
                onRowSelect={(selectedRowKeys, record) => {
                  this.setState({
                    editRuleTableSelected: selectedRowKeys
                  });
                }}
                onAdd={(keys, datas) => {
                  const data = toJS(tableDatas2).push(datas[0]);
                  webseal.setState({tableDatas2: data})
                }}
                onDelete={(keys, datas) => {
                  let data = toJS(tableDatas2);
                  data = data.filter(function (el, index) {
                    return !keys.includes(index);
                  });
                }}
              />
            </div>
          )
        }
      }
    });
    return group;
  }
  render() {
    const { webseal, whiteListStore } = this.props;
    const { newBaseForm, status, hasRight, rightLoading } = webseal;
    const { newBaseFormFields, hasNonStandard, nonStandLoading } = toJS(status);
    return (
      nonStandLoading
        ? null
        : hasNonStandard
          ? rightLoading 
            ? null
            : hasRight
              ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@hlibxn`}
                  className={"inte-webxml-rightmenu"}
                  datas={this.getRightMenu()}
                  collectParams={{
                    favname: `${getLabel(128589, "WebSEAL集成")}`,
                    favouritetype: 1,
                    objid: 0,
                    link: "wui/engine.html#/integration/webseal",
                    importantlevel: 1
                  }}
                >
                  <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ty2neg`}
                    title={getLabel(128589, "WebSEAL集成")}
                    icon={<i className={IntegrationUtil.GeneralTitleColor.icon} />}
                    iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                    buttons={this.getBtns()}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    dropMenuProps={{
                      collectParams: {
                        favname: `${getLabel(128589, "WebSEAL集成")}`,
                        favouritetype: 1,
                        objid: 0,
                        link: "wui/engine.html#/integration/webseal",
                        importantlevel: 1
                      }
                    }}
                  />
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@5i7lot`} height={'100%'}>
                    {this.getFormSearchs(newBaseForm, newBaseFormFields)}
                    <div style={{height: 50}}></div>
                  </WeaNewScroll>
                  {
                    window.weaPortalPublic && window.weaPortalPublic.WeaSystemSetting &&
                    <window.weaPortalPublic.WeaSystemSetting ecId={`${this && this.props && this.props.ecId || ''}_undefined@j01n1s`}
                      ref="systemSetting"
                      onSave={()=> whiteListStore.getRegisterFilterId({filter_clazz: this.state.clazz}, webseal.doInit)}
                    />
                  }
                </WeaRightMenu>
              : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@3ak9dl`} />
          : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@8y0uga`} />
    );
  }
}
