import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, Spin, Modal } from "antd";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import WhiteList from '../../public/WhiteList';
import '../../style/cas.less';
import {
  WeaLocaleProvider,
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaFormItem,
  WeaTools,
  WeaSearchGroup,
  WeaNewScroll,
  WeaHelpfulTip,
  WeaInput,
  WeaDialog,
  WeaCheckbox,
} from "ecCom";

import { WeaSwitch } from "comsMobx";
import DoubleInput from '../doubleInput';
import * as IntegrationUtil from "../../util/IntegrationUtil";
import PopoverButton from '../../public/PopoverButton';

const getLabel = WeaLocaleProvider.getLabel;
@inject("cas")
@inject("whiteListStore")
@observer
export default class Cas extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editTableSelected: [],
      clazz: "weaver.interfaces.sso.cas.AuthenticationFilter",
      ticketClazz: "weaver.interfaces.sso.cas.AbstractTicketValidationFilter",
      datas: [{
        title: getLabel('513856','登录校验'),
        viewcondition: "0"
      }, {
        title: `Ticket${getLabel('128877','校验')}`,
        viewcondition: "1"
      }],
      selectedKey: "0"
    };
  }

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

  onRightMenuClick = (type, recordId) => {
    const { cas } = this.props;
    const { save, newBaseForm } = cas;
    const formParams = newBaseForm.getFormParams();
    switch (type) {
      case "save":
        save();
        break;
      case "test":
        if (formParams.isuse == 1) {
          Modal.confirm({
            title: `${getLabel(131329,'信息确认')}`,
            content: getLabel('514734','部署后会自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
            okText: `${getLabel(382958,'确定')}`,
            cancelText:`${getLabel(31129,'取消')}`,
            onOk: () => this.complete(),
          });
        }else {
          Modal.confirm({
            title: `${getLabel(131329,'信息确认')}`,
            content: getLabel(387003,'是否要关闭CAS？'),
            okText: `${getLabel(382958,'确定')}`,
            cancelText:`${getLabel(31129,'取消')}`,
            onOk: () => this.complete(),
          });
        }
        break;
    }
  }

  /**
   * 完成
   */
  complete = () => {
    const { cas } = this.props;
    const { save, newBaseForm } = cas;
    const formParams = newBaseForm.getFormParams();
    if (formParams.isuse == '1' && formParams.appauth != 1 && formParams.pcauth != 1) {
      Modal.info({
        title: getLabel(15172,'系统提示'),
        content: getLabel(386921,'请开启pc认证或手机认证!'),
        okText: getLabel(826,'确定'),
        onOk:() => {},
      });
    } else {
      save(1);
    }
  }

  getBtns = () => {
    const { cas } = this.props;
    const { loading } = cas; 
    let btns = [];
    btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bgqidb@integrationCasSave`}
        type="primary"
        onClick={() => {
          {
            this.onRightMenuClick("save");
          }
        }}
        disabled={loading}
      >
        {getLabel("86", "保存")}
      </Button>,
      <PopoverButton ecId={`${this && this.props && this.props.ecId || ''}_PopoverButton@yes2p7@integrationCasTest`} 
        type="primary"
        disabled={loading}
        onClick={() => this.onRightMenuClick("test")}
      />,
    ];
    return btns;
  }

  getRightMenu() {
    const { cas } = this.props;
    const { loading } = cas;
    let btnArr = [{
      key: "save",
      disabled: loading,
      icon: <i className="icon-coms-Preservation" />,
      content: getLabel("86", "保存"),
      onClick: () => this.onRightMenuClick("save")
    },{
      key: "test",
      disabled: loading,
      icon: <i className="icon-coms-Approval" />,
      // content: ,
      content: getLabel('514733','部署'),
      onClick: () => this.onRightMenuClick("test")
    }];
    return btnArr;
  }
  getColumns = (columns) => {
    let cols = [];
    columns && columns.forEach((col)=> {
      if (col.dataIndex === 'excludeurl') {
        col.com = [{
          type: 'CUSTOM',
          key: 'excludeurl',
          render: (text, record, index, onEdit) => {
            return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@t4j817@integrationCas${col.dataIndex}${index}`}
              value={record.excludeurl}
              viewAttr={record.viewAttr =='1'?1:3}
              hasBorder
              onChange={(v) => {
                onEdit({
                  type: 'CUSTOM',
                  record,
                  index,
                  key: 'excludeurl',
                  value: v
                })
              }}
            />
          }
        }]
        cols.push(col);
      }else if (col.dataIndex === 'excludedescription') {
        col.com = [{
          type: 'CUSTOM',
          key: 'excludedescription',
          render: (text, record, index, onEdit) => {
            return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@8lapqg@integrationCas${col.dataIndex}${index}`}
              value={record.excludedescription}
              inputType={"multilang"}
              isMulti={true}
              isBase64={true}
              viewAttr={record.viewAttr =='1'?'1':2}
              hasBorder
              onChange={(v) => {
                onEdit({
                  type: 'CUSTOM',
                  record: {
                    ...record,
                    excludedescription: v ? v.trim() : "",
                  },
                  index,
                })
              }}
            />
          }
        }]
        cols.push(col);
      }else if (col.dataIndex === 'logincheck') {
        col.com = [{
          type: 'CHECKBOX',
          key: 'logincheck',
          render: (text, record, index, onEdit) => {
            return <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@138xqq@integrationCas${col.dataIndex}${index}`}
              value={record.logincheck}
              viewAttr={2}
              onChange={(v) => {
                onEdit({
                  type: 'CHECKBOX',
                  record: {
                    ...record,
                    logincheck: v,
                  },
                  index,
                })
              }}
            />
          }
        }]
        col.title=
          <span>
          <span>{col.title}<span className={"wf-backstage-linkAgeViewAttr-helpTip"}
                                 style={{marginLeft: 5}}><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@w12r3n@integrationCas${col.dataIndex}`}
            title={<div><p>{getLabel('', '启用登录校验 ： 勾选，表示认证排除地址生效，不走CAS认证。')}</p>
            </div>}/></span></span>
        </span>
        cols.push(col);
      }else if (col.dataIndex === 'ticketcheck') {
        col.com = [{
          type: 'CHECKBOX',
          key: 'ticketcheck',
          render: (text, record, index, onEdit) => {
            return <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@pg3t47@integrationCas${col.dataIndex}${index}`}
              value={record.ticketcheck}
              viewAttr={2}
              onChange={(v) => {
                onEdit({
                  type: 'CHECKBOX',
                  record: {
                    ...record,
                    ticketcheck: v,
                  },
                  index,
                })
              }}
            />
          }
        }]
        col.title=
          <span>
          <span>{col.title}<span className={"wf-backstage-linkAgeViewAttr-helpTip"}
                                 style={{marginLeft: 5}}><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@khhqd1@integrationCas${col.dataIndex}`}
            title={<div><p>{getLabel('', '启用Ticket校验：勾选，表示认证排除地址生效，若排除地址后带有ticket则不走Ticket校验。')}</p>
            </div>}/></span></span>
        </span>
        cols.push(col);
      }

    })
    return cols;
  }

  tableEditOperate = type => {
    const { cas } = this.props;
    const { tableEdit } = cas;
    switch (type) {
      case "add":
      tableEdit.doAdd();
        break;
      case "del":
      tableEdit.doDelete();
        break;
    }
  };

  willDelete = (datas, keys) => new Promise((resolve, reject) => {
    Modal.confirm({
      title: `${getLabel(131329,'信息确认')}`,
      content: `${getLabel(385625,'确定要删除选择的记录吗？')}`,
      okText: `${getLabel(382958,'确定')}`,
      cancelText:`${getLabel(31129,'取消')}`,
      onOk: () => resolve(true),
      onCancel: () => resolve(false),
    })
  })

  willAdd = (allDatas, addData) => {
    const {cas} = this.props;
    const {tableDatas} = toJS(cas.status);
    let currentData = [];

    currentData = {
      ...addData,
      logincheck: '1'
    }

    allDatas && allDatas.map((v, index) => {
      if(v.key === addData.key) {
        allDatas[index] = currentData;
      }
    })

    cas.setState({tableDatas: allDatas});
  }

  getTabs = () => {
    const {datas, selectedKey, ticketClazz, clazz} = this.state;
    return <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@1u7ybx`} 
        datas={datas}
        keyParam="viewcondition" //主键
        countParam="groupid" //数量
        type="card"
        selectedKey={selectedKey}
        onChange={v => {
          let clazz_ = "";
          this.setState({selectedKey: v});
          if(v == 0) {
            clazz_ = clazz;
          }else if(v == 1) {
            clazz_ = ticketClazz;
          }
          this.props.whiteListStore.getRegisterFilterId({filter_clazz: clazz_});
        }}
      />
  }

  getFormSearchs = (form, datas) => {
    const { cas } = this.props;
    const { res, userAgent } = toJS(cas.status);
    const {isFormInit} = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.forEach((c, idx) => {
      let leftDis = idx == 6 ? -17 : 0;
      let items = [];
      c.items && c.items.forEach(field => {
        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@qiubv7@integrationCasForm${field.domkey[0]}`} fieldConfig={field} form={form} formParams={formParams}/>
        if ('casserverurl' == field.domkey[0]) {
          dom = <div style={{position: 'relative'}}>
            {dom}
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nm2f3t@integrationCasForm${field.domkey[0]}TestBtn`} style={{position: 'absolute', right:'-65px', top: '4px'}} size="small" type={'ghost'}
            onClick={()=> {cas.testCas()}}>{getLabel("25496", "测试")}</Button>
          </div>
        }else if ('casserverloginpage' == field.domkey[0] || 'casserverlogoutpage' == field.domkey[0]) {
          dom = <DoubleInput ecId={`${this && this.props && this.props.ecId || ''}_DoubleInput@746ums@integrationCasForm${field.domkey[0]}`}
            leftValue={formParams.casserverurl || res.defaultCasUrl}
            viewAttr={3}
            {...bindObj.bind()}
          />
        }else if ('ecologyurl' == field.domkey[0]) {
          dom = <div style={{position: 'relative'}}>
            {dom}
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cpj71s@integrationCasForm${field.domkey[0]}SetBtn`} style={{position: 'absolute', right:'-65px', top: '4px'}}
              size="small" type={'ghost'}
              onClick={()=> {this.refs.systemSetting && this.refs.systemSetting.onShow()}}
              >{getLabel("19653", "设置")}</Button>
          </div>
        }else if ('ecologyloginpage' == field.domkey[0] ) {
          dom = <DoubleInput ecId={`${this && this.props && this.props.ecId || ''}_DoubleInput@1tb8mu@integrationCasForm${field.domkey[0]}`}
            leftValue={formParams.ecologyurl || res.defaultEcologyUrl}
            {...bindObj.bind()}
          />
        }else if ('appauthAddress' == field.domkey[0]) {
          dom = <div style={{position: 'relative'}}>
            <DoubleInput ecId={`${this && this.props && this.props.ecId || ''}_DoubleInput@smf2tg`}
              leftValue={formParams.casserverurl || res.defaultCasUrl}
              viewAttr={3}
              {...bindObj.bind()}
              />
            
          </div>
          hideLabel = false;
        }else if('strgy_ua_val' === field.domkey[0]) {
          return;
        }else if('strgy_ua' === field.domkey[0]) {
          let userAgentDom = null;
          if(form.getFormParams().strgy_ua == '1') {
            userAgentDom = userAgent && userAgent.map((field, index) => {
              return <div style={{width:300, marginLeft:45, marginTop: -35 }}>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@msqf34@integrationCasForm${field.domkey[0]}`}
                  label={`${field.label}`}
                  // hideLabel={true}
                  labelCol={{span: 10}}
                  wrapperCol={{span: 14}}
                  error={form.getError(field)}
                  tipPosition="bottom"
                >
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@weu7d1@integrationCasForm${field.domkey[0]}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />
                </WeaFormItem>
              </div>
            });
          }
          dom = <nobr>
            {dom}
            {userAgentDom}
          </nobr>
        }else if('accounttype' === field.domkey[0] && form.getFormParams().accounttype == '7') {
          let marginLeft = 15, marginTop = 5, title = "";
          if(field.selectLinkageDatas && field.selectLinkageDatas["7"]) {
            if(field.selectLinkageDatas["7"].conditionType.toLocaleLowerCase() == "textarea") {
              field.selectLinkageDatas["7"].maxRows = 4;
              field.selectLinkageDatas["7"].minRows = 4;
              marginLeft = 20;
              marginTop = 35;
            }
            title = field.selectLinkageDatas["7"].helpfulTip;
          }
          dom = <nobr>
            {dom}
            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@0a5ea6`} style={{position: "absolute", marginLeft, marginTop}} title={title} />
          </nobr>
        }

        items.push({
          com:(<div style={{marginLeft: leftDis}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@0sn0o8@integrationCasForm${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,
          hide: form.isHide(field, (keys, allParams)=> {
            let hide = false;
            "strgy_ua_val" === field.domkey[0] && allParams.strgy_ua == 0 && (hide = true);
            "clusterNodes" === field.domkey[0] && allParams.is_cluster == 0 && (hide = true);
            return hide;
          })
        })
      });
      if (formParams.isuse == '0' && (idx == 1 || idx == 2 || idx == 3 || idx == 4 || idx == 5)) {
      } else {
        if (idx !== 5 && idx !== 6) {
          group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@0wvg1t@integrationCasForm${idx}`} center multiCol col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        } else if(idx == 6) {
          group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@4acrea@integrationCasForm${idx}`} multiCol col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        } else if(idx == 5){
          group.push(<div className="inte-webseal-whitelist-custom"><WhiteList ecId={`${this && this.props && this.props.ecId || ''}_WhiteList@1v4cwz@integrationCasForm${idx}`} helpfulTip={this.getWhiteListTip()} otherCom={this.getTabs()} /></div>)
        }
      }
    });
    return group;
  }
  /**获取白名单的helpfulTip */
  getWhiteListTip = () => {
    return <div style={{wordBreak: "break-all"}}>
      <p>1、{getLabel('514625','点击‘+’如果选择不到需要的白名单地址，可以去【统一白名单地址配置】-【通用白名单】里面进行设置；【统一白名单地址配置】页面需要“统一白名单地址配置”权限')}。</p>
      <p>2、{getLabel('514627','白名单地址也可以直接在【统一白名单地址配置】-【过滤器白名单】中进行维护，登录校验对应过滤器weaver.interfaces.sso.cas.AuthenticationFilter；Ticket校验对应过滤器weaver.interfaces.sso.cas.AbstractTicketValidationFilter')}。</p>
    </div>
  }

  getRowSelection = rowSelection => {
    const sel = { ...rowSelection };
    sel.getCheckboxProps = record => {
      return { disabled: record.viewAttr === '1' };
    };
    return sel;
  }

  getDialogBtnsRightMenu() {
    const { cas } = this.props;
    let btnArr = [{
      key: "test",
      icon: <i className="icon-coms-complete" />,
      content: getLabel("25496", "测试"),
      onClick: () => cas.telTest()
    }];
    return btnArr;
  }

  render() {
    const { cas, whiteListStore } = this.props;
    const { newBaseForm, status,hasRight, rightLoading, loading } = cas;
    const { newBaseFormFields, testVisible, hasNonStandard, nonStandLoading } = toJS(status);
    return (
      nonStandLoading
        ? null
        : hasNonStandard
          ? rightLoading 
            ? null
            : <div style={{height: '100%'}} className="bs-integration-cas">
              {
                hasRight
                  ? <div>
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@qm1bcm`}
                      className="inte-webxml-rightmenu"
                      datas={this.getRightMenu()}
                      collectParams={{
                        favname: `${getLabel(128653, "CAS集成")}`,
                        favouritetype: 1,
                        objid: 0,
                        link: "wui/engine.html#/inteengine/cas",
                        importantlevel: 1
                      }}
                    >
                      <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@8dxeiv`} spinning={loading || false}>
                        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@d6znxk`}
                          title={getLabel(128653, "CAS集成")}
                          icon={<i className={IntegrationUtil.GeneralTitleColor.icon} />}
                          iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                          buttons={this.getBtns()}
                          showDropIcon={true}
                          dropMenuDatas={this.getRightMenu()}
                          loading={loading}
                          dropMenuProps={{
                            collectParams: {
                              favname: `${getLabel(128653, "CAS集成")}`,
                              favouritetype: 1,
                              objid: 0,
                              link: "wui/engine.html#/integration/cas",
                              importantlevel: 1
                            }
                          }} 
                        >
                          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@2bxfjl`} height={'100%'}>
                            {this.getFormSearchs(newBaseForm, newBaseFormFields)}
                          </WeaNewScroll>
                        </WeaTop>
                      </Spin>
                    </WeaRightMenu>
                    <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@03w77c`}
                      title={getLabel("128643", "手机认证")}
                      onCancel={()=> cas.setState({testVisible: false})}
                      visible={testVisible}
                      style={{width: 500, height: 300}}
                      icon={IntegrationUtil.GeneralTitleColor.icon}
                      iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                      hasScroll
                      buttons={[
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5g4bfj@integrationCasMobileTestBtn`} type="primary" onClick={()=> cas.telTest()}>{getLabel("25496", "测试")}</Button>
                      ]}
                      moreBtn={{
                        datas: this.getDialogBtnsRightMenu(),
                        collectParams: {
                          favname: getLabel("128643", "手机认证"),
                          favouritetype: 1,
                          objid: 0,
                          link: "wui/engine.html#/integration/cas",
                          importantlevel: 1
                        }
                      }}
                    >
                      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@t8o271`} datas={this.getDialogBtnsRightMenu()} collectParams={{
                        favname: getLabel("128643", "手机认证"),
                        favouritetype: 1,
                        objid: 0,
                        link: "wui/engine.html#/integration/cas",
                        importantlevel: 1
                      }}>
                        {cas.telForm.render({col: 1})}
                        </WeaRightMenu>
                    </WeaDialog>
                    {
                      window.weaPortalPublic && window.weaPortalPublic.WeaSystemSetting &&
                      <window.weaPortalPublic.WeaSystemSetting ecId={`${this && this.props && this.props.ecId || ''}_weaPortalPublic_WeaSystemSetting@nhj9c8`}
                        ref="systemSetting"
                        onSave={()=> whiteListStore.getRegisterFilterId({filter_clazz: this.state.clazz}, cas.doInit)}
                      />
                    }
                    </div>
                  : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@ddulgt`}/>
              }
              </div>
          : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@j60t7q`} />
    );
  }
}
