import {
  inject,
  observer,
} from 'mobx-react';

import {
  Row,
  Col,
  Spin,
  Modal,
  Button,
  message,
} from 'antd'

import {
  WeaTop,
  WeaTab,
  WeaTools,
  WeaDialog,
  WeaFormItem,
  WeaRightMenu,
  WeaSearchGroup,
  WeaLocaleProvider,
  WeaAlertPage,
} from 'ecCom'

import React from 'react'
import * as mobx from 'mobx'
import {
  WeaSwitch
} from 'comsMobx';
import {
  WeaTableNew
} from 'comsMobx';
import {
  i18n
} from '../../public/i18n';
import {addContentPath} from '../../util/index.js'
import * as PublicFunc from '../../util/pulic-func';

import '../../style/systemCard.css';

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

@inject('hrmSystemCard')

@observer
class SystemCard extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.init();
  }

  init() {
    const {
      hrmSystemCard,
      id,
    } = this.props;
    const {
      getHasRight,
    } = hrmSystemCard;

    getHasRight(id);
  }

  getViewCards() {
    const {
      hrmSystemCard
    } = this.props;
    const {
      headerColumns
    } = hrmSystemCard;
    let arr = [];
    for (let i = 0; i < headerColumns.length; i++) {
      arr.push(<div style={{float: 'left',width: '150px',height: '70px',marginLeft: '30px'}}>
		  				<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@o0evtu@${i}`}>
		  					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ol9n46@${i}`} span={10}>
		  						<img src={addContentPath(headerColumns[i].icon)} alt='' />
		  					</Col>
		  					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@menkfi@${i}`} span={14}>
		  						<div>{headerColumns[i].label}</div>
		  						<div style={{color: headerColumns[i]['font-color']}}>{headerColumns[i].num}</div>
		  					</Col>
		  				</Row>
					</div>);
    }
    arr.push(<div style={{clear: 'both'}}></div>);
    return <div style={{marginTop: '25px'}}>{arr}</div>;
  }

  getPanelComponent() {
    const {
      hrmSystemCard
    } = this.props;
    const {
      condition1,
      form1
    } = hrmSystemCard;
    const {
      isFormInit
    } = form1;
    let condition = condition1;
    let form = form1;
    let formParams = form1.getFormParams();
    let arr = [];

    isFormInit && condition.map(c => {
      c.items.slice(0, 2).map((field, j) => {
        arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@a5jjti@${j}`} span={10} offset={1}>
      						<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@q2mmi7@${j}`}
                          		label={`${field.label}`}
                          		labelCol={{span: `${field.labelcol}`}}
                          		wrapperCol={{span: `${field.fieldcol}`}}>
                            		<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@g2wppj@${j}`} fieldConfig={field} form={form} formParams={formParams} />
                       		</WeaFormItem>
      					</Col>);
      })
    })
    return <div style={{paddingTop: '30px',paddingBottom: '30px'}}><Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ohjqgo`}
      onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && hrmSystemCard.getTableInfo()}
    >{arr}</Row></div>
  }

  handleSearch() {
    const {
      hrmSystemCard
    } = this.props;
    hrmSystemCard.getTableInfo();
    hrmSystemCard.hideSearchAd();
  }

  handleChange = (data) => {
      const { hrmSystemCard:{handleCondition,form2} } = this.props;
      if (data.userUsbType) {
        handleCondition()
        form2.updateFields({
          usbstate:'0'
        })
      }
  }

  getSecSettingForm() {
    const {
      hrmSystemCard
    } = this.props;
    const {
      condition2,
      form2,
      isSecSetting
    } = hrmSystemCard;
    const {
      isFormInit
    } = form2;

    let condition = condition2;
    let form = form2;
    let formParams = form2.getFormParams();
    let arr = [];
    let userUsbType;
    let usbstate;
    let needauto;
    if (formParams.userUsbType) userUsbType = formParams.userUsbType;
    if (formParams.usbstate) usbstate = formParams.usbstate;
    if (formParams.needauto) needauto = formParams.needauto;

    isFormInit && condition.map((c, j) => {
      let items = c.items;
      for (let i = 0; i < items.length; i++) {
        let field = items[i];
        let domkey = (field.domkey)[0];
        
        if (userUsbType == '6' && !['userUsbType','usbstate'].includes(domkey)) {
          continue;
        }
        if ((!userUsbType || userUsbType == '-1') && domkey !== 'userUsbType') continue;
        if (userUsbType == '4' && (!usbstate || usbstate == '0' || usbstate == '2') && (domkey == 'tokenKey' || domkey == 'serial' || domkey == 'needauto' || domkey == 'enableDate' || domkey == 'enableUsbType')) continue;
        if (userUsbType == '4' && usbstate == '1' && (!needauto || needauto == '0') && (domkey == 'tokenKey' || domkey == 'serial' || domkey == 'enableDate' || domkey == 'enableUsbType')) continue;
        if (userUsbType == '4' && usbstate == '1' && needauto == '1' && (domkey == 'tokenKey' || domkey == 'serial')) continue;

        if (userUsbType == '2' && (!usbstate || usbstate == '0' || usbstate == '2') && (domkey == 'tokenKey' || domkey == 'mobile' || domkey == 'needauto' || domkey == 'enableDate' || domkey == 'enableUsbType')) continue;
        if (userUsbType == '2' && usbstate == '1' && (!needauto || needauto == '0') && (domkey == 'tokenKey' || domkey == 'mobile' || domkey == 'enableDate' || domkey == 'enableUsbType')) continue;
        if (userUsbType == '2' && usbstate == '1' && needauto == '1' && (domkey == 'tokenKey' || domkey == 'mobile')) continue;

        if (userUsbType == '3' && (!usbstate || usbstate == '0' || usbstate == '2') && (domkey == 'serial' || domkey == 'mobile' || domkey == 'needauto' || domkey == 'enableDate' || domkey == 'enableUsbType')) continue;
        if (userUsbType == '3' && usbstate == '1' && (!needauto || needauto == '0') && (domkey == 'serial' || domkey == 'mobile' || domkey == 'enableDate' || domkey == 'enableUsbType')) continue;
        if (userUsbType == '3' && usbstate == '1' && needauto == '1' && (domkey == 'serial' || domkey == 'mobile')) continue;

        if ((domkey == 'tokenKey' || domkey == 'serial' || domkey == 'mobile') && field.viewAttr !== 3) field.viewAttr = 3;

        let dom;
        if (domkey == 'serial') {
          dom = this.getInputAndBtn(field, form, formParams);
        } else if (domkey == 'tokenKey') {
          dom = this.getInputAndBtn(field, form, formParams);
        } else {
          dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@g4p7d1@${i}`} fieldConfig={field} form={form} formParams={formParams} onChange={this.handleChange}/>;
        }

        arr.push(
          <div style={{marginTop: '10px'}}>
      					<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@nr6wck@${i}`}>
      						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@sb10cu@${i}`} span={22} offset={1}>
      							<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jn7vce@${i}`}
                          			label={`${field.label}`}
                          			labelCol={{span: 8}}
                          			wrapperCol={{span: 10}}>
                            			{dom}
                            			{isSecSetting ? '' :(domkey == 'userUsbType'  && <p style={{marginTop: 5}}>{i18n.message.noAvailableCheckoutMethod()}，<a href={addContentPath('/spa/hrm/engine.html#/hrmengine/securitySetting')} target='_blank'>{i18n.button.clickSetting()}</a>。</p>) }
                       			</WeaFormItem>
      						</Col>
      					 </Row>
      				</div>
        );
      }
    })
    //将二次验证密码push到队列中
    const {
      isSecondaryVerifyUsed,
      isSecondaryVerifySetted,
      saveSecondaryPasswordSetting,
    } = hrmSystemCard;

    arr.push(
      <div style={{marginTop: '10px'}}>
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@scfpic@1`}>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@k49wnj@1`} span={22} offset={1}>
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@i1cwxw@1`}
                label={getLabel('501204',"二次验证密码")}
                labelCol={{span: 8}}
                wrapperCol={{span: 16}}>
                <div style={{marginTop: !isSecondaryVerifySetted ? 7 : 0}}>
                  <span>
                    {isSecondaryVerifySetted ? getLabel('514132',"已设置") : i18n.label['514133']()}
                  </span>
                  { isSecondaryVerifySetted &&
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6skj57@1`} type='primary' style={{marginLeft: 111}} onClick={() => this.showConfirm()}>
                      {getLabel('26471',"停用")}
                    </Button>
                  }
                </div>
              </WeaFormItem>
            </Col>
          </Row>
      </div>)

    return <div style={{marginTop: '30px',paddingLeft: '60px'}}>{arr}</div>
  }

  showConfirm = () => {
    const {
      hrmSystemCard
    } = this.props, {
      saveSecondaryPasswordSetting
    } = hrmSystemCard;

    confirm({
      title: getLabel(131329, '信息确认'),
      content: (<div>
                  <span>{getLabel('528277',"确定要停用该管理员的二次验证密码吗？")}</span><br />
                  <span>{getLabel('528278',"为确保账户安全，请及时重设密码！")}</span>
               </div>),
      okText: getLabel(33703, '确定'),
      cancelText: getLabel(32694, '取消'),
      onOk() {
        saveSecondaryPasswordSetting(false);
      },
      onCancel() {
        return false
      },
    });
  }

  getInputAndBtn(field, form, formParams) {
    return (<div> 
      				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@a2dbh9`} fieldConfig={field} form={form} formParams={formParams} />
      				<div style={{position: 'absolute',top: 0,left: 220}}>
      					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j9fhel`} type="primary" onClick={() => this.updateKey()}>{i18n.label.binding()}</Button>
      				</div>
      			</div>)
  }

  secSettingFormVerify() {
    const {
      hrmSystemCard
    } = this.props;
    const {
      form2,
      isSecSetting
    } = hrmSystemCard;
    const userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    const isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
    const isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器

    let params = form2.getFormParams();
    let userUsbType = params.userUsbType;
    let usbstate = params.usbstate;
    let mobile = params.mobile;
    let tokenKey = params.tokenKey;
    let serial = params.serial;

    if (!isSecSetting) {
      message.warning(i18n.message.noAvailableCheckMode());
      return false;
    }
    if (!userUsbType || userUsbType == '-1') {
      // message.warning('请选择辅助校验方式！');
      // return false;
      hrmSystemCard.save();
      return
    }

    if (userUsbType == '4' && !mobile) {
      message.warning(i18n.message.fillTelphoneNum());
      return false;
    }

    if (userUsbType == '4' && mobile && mobile.length !== 11) {
      message.warning(i18n.message.fillAvailableTelphoneNum());
      return false;
    }

    if (userUsbType == '2' && !isIE) {
      message.warning(i18n.message.htKey());
      return false;
    }

    if (userUsbType == '2' && isIE && !serial) {
      message.warning(i18n.message.fillUserKey());
      return false;
    }

    if (userUsbType == '3' && !tokenKey) {
      message.warning(i18n.message.bindToken());
      return false;
    }

    if (userUsbType == '3' && tokenKey && (!this.isdigit(tokenKey) || tokenKey.length !== 10)) {
      message.warning(i18n.message.tokenNumLen());
      return false;
    }

    this.isTokenKeyUsed({
      tokenKey: tokenKey
    });

  }

  isdigit(s) {
    var r, re;
    re = /\d*/i; //\d表示数字,*表示匹配多个数字
    r = s.match(re);
    return (r == s) ? true : false;
  }
  //序列号是否被占用
  isTokenKeyUsed(params) {
    const {
      hrmSystemCard
    } = this.props;
    const {userid} = hrmSystemCard
    params.userid = userid
    params.id = userid
    WeaTools.callApi('/api/hrm/sysadmin/checkIsUsed', 'POST', params).then((data) => {
      if (data.isUsed) {
        let msg = i18n.message.tokenBinded().replace('{params}', data.lastname);
        message.warning(msg);
        // message.warning('令牌序列号已经绑定给' + data.lastname + '，不能重复绑定！');
      } else {
        hrmSystemCard.save();
      }
    })
  }

  //"用户密钥"和"令牌序列号"绑定
  updateKey() {
    const {
      hrmSystemCard
    } = this.props;
    const {
      form2
    } = hrmSystemCard;
    let needusb = (form2.getFormParams()).userUsbType;
    if (needusb == "2") {
      let returnstr = PublicFunc.getUserName() || '';
      if (returnstr !== "") {
        hrmSystemCard.setLoginId(returnstr);
      }
    } else if (needusb == "3") {
      this.bindTokenKey();
    }
  }

  bindTokenKey() {
    const title = "";
    let url = "/spa/hrm/index_mobx.html#/main/hrm/BindTokenKey?requestFrom=system&userid=" + this.props.params.hrmId;
    const dialog = ecCom.WeaTools.createDialog({
      title,
      url,
      style: {
        width: 600,
        height: 365
      },
      zIndex: 9999
    });
    dialog.show();
  }

  setSecurity() {
    const {
      hrmSystemCard
    } = this.props;
    let hrmId = this.props.params.hrmId || '';
    hrmSystemCard.hrmId = hrmId;
    let params = {
      id: hrmId
    };

    hrmSystemCard.setDialogShow();
    hrmSystemCard.getSecSettingCondition(params);
  }


  render() {
    const {
      hrmSystemCard
    } = this.props;
    const {
      tabKey,
      headerColumns,
      tableStore,
      isPanelShow,
      isSecSettingShow,
      hrmId,
      hrmName,
      hasRight,
      loading,
    } = hrmSystemCard;
    const {
      form1
    } = hrmSystemCard;

    const btn1 = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oqbkom@1`} type="primary" onClick={() => this.setSecurity()}>{i18n.label.securitySetting()}</Button>),
    ]

    const btn2 = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u90qu8@2`} type="primary" onClick={() => this.handleSearch()}>{i18n.button.search()}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@le24e4@3`} type="primary" onClick={() => {form1.reset(); hrmSystemCard.tabKey = '0'}}>{i18n.button.reset()}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oy588r@4`} type="primary" onClick={() => hrmSystemCard.hideSearchAd()}>{i18n.button.cancel()}</Button>),
    ];

    const btn3 = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g2bk7w@5`} type="primary" onClick={() => this.secSettingFormVerify()}>{i18n.button.save()}</Button>),
    ]

    const dropMenuDatas = [{
      key: '0',
      content: i18n.label.securitySetting(),
      icon: <i className='icon-coms-Preservation' />
    }, {
      key: '1',
      content: i18n.button.save(),
      icon: <i className='icon-coms-Preservation' />
    }, ]

    const dropMenuDatas1 = dropMenuDatas.slice(0, 1);
    const dropMenuDatas2 = dropMenuDatas.slice(1, 2);
    dropMenuDatas1.push({
      icon: <i className='icon-coms-Print-log'/>,
      content: i18n.button.log(),
      key: 'showLog',
      onClick: key => {
        window.setLogViewProps({
          logSmallType: i18n.smallType.HRM_RSOURCEMANAGER_SECURITYSETTING,
        });
      }
    })

    const tabName1 = [{
      key: '0',
      title: i18n.label.all()
    }, {
      key: '1',
      title: i18n.label.today()
    }, {
      key: '2',
      title: i18n.label.tswk()
    }, {
      key: '3',
      title: i18n.label.tsmth()
    }, {
      key: '4',
      title: i18n.label.tssn()
    }, {
      key: '5',
      title: i18n.label.tsyr()
    }, ]

    const items = [{
      com: (
						<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@s5gqti@1`} 
						  comsWeaTableStore={tableStore}
              hasOrder={true}
              needScroll={true}
            />
      )
    }]

    if (loading) {
      return <div />
    }

    if (!hasRight) {
      return (
        <div style={{height:'100%'}}>
                    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@flndcf`}>
                        <div style={{ color: '#000' }}>
                            {getLabel(2012, '对不起，您暂时没有权限！')}
                        </div>
                    </WeaAlertPage>
                </div>
      )
    }

    return (
      <div>
  				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@lty9an`} 
            datas={dropMenuDatas1} 
            onClick={key => (key === "0") && this.setSecurity()}
            collectParams={{favname: i18n.label.sysManager(),favouritetype:5}}
          >
  					<WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jq8agi`} 
            			title={hrmName}
            			icon={<i className='icon-coms-hrm' />}
            			iconBgcolor='#217346'
            			loading={true}
            			buttons={btn1}
            			showDropIcon={true}
            			dropMenuDatas={dropMenuDatas1}
            			onDropMenuClick={() => this.setSecurity()}
          			/>
                  
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ot4m8p`}
                    selectedKey={tabKey}
                    datas={tabName1}
                    keyParam='key'
                    searchType={['base','advanced']}
                    showSearchAd={isPanelShow}
                    searchsBaseValue={form1.getFormParams().relatedname}
                    setShowSearchAd={bool => hrmSystemCard.setShowSearchAd(bool)}
                    hideSearchAd={ () => hrmSystemCard.hideSearchAd() }
                    searchsAd={<div>{form1.render()}</div>}
                    advanceHeight={94}
                    hasMask={false}
                    buttonsAd={btn2}
                    onSearch={() => hrmSystemCard.getTableInfo()}
                    onChange={(key) => hrmSystemCard.tabClick(key)}
                    onSearchChange={v => hrmSystemCard.updateFormFields(v, '1')}
                />
                
          			
                {this.getViewCards()}

                <div className='system-card-info-group'>
                	<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wl59sj`}
                		needTigger={true}
                		title={i18n.label.sysOpLog()}
                		showGroup={true}
          				  items={items}
          				  col={1}
                	/>
                </div>
  				</WeaRightMenu>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@78hu93`}
            		title={i18n.label.securitySetting()}
            		icon="icon-coms-hrm"
            		iconBgcolor="#217346"
            		visible={isSecSettingShow}
            		closable={true}
            		onCancel={() => {hrmSystemCard.hideDialog(); hrmSystemCard.reset()}}
            		buttons={btn3}
            		style={{width: '600px', height: '300px'}}
          		> 
          			<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@gy10tw`} datas={dropMenuDatas2} onClick={() => this.secSettingFormVerify()}>
          				{this.getSecSettingForm()}
          			</WeaRightMenu>
          		</WeaDialog>
  			</div>
    )
  }
}

export default SystemCard