import React from 'react';
import { inject, observer} from 'mobx-react';
import {WeaAlertPage,WeaTools,WeaTab,WeaTop,WeaSearchGroup,WeaFormItem,WeaRightMenu} from 'ecCom';
import { Tabs,Button,Table,Form, Modal,message,Row,Col, Spin} from 'antd';
import {WeaSwitch} from 'comsMobx';
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty';
const toJS = mobx.toJS;
import * as PublicFunc from '../util/pulic-func';
window.openFullWindowForXtable = PublicFunc.openFullWindowForXtable;
import moment from 'moment';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import cloneDeep from 'lodash/cloneDeep'
import {i18n} from '../public/i18n';
import '../style/financeExpand.less';
import AlertPage from '../public/components/AlertPage.js';
import VerifyResourceID from './financeExpand/VerifyResourceID.js';

@inject('hrmFinance')
@inject('hrmCard')
@observer
class HrmFinance extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.showDialog();
    }
  }

  componentDidMount() {
    this.showDialog((token) => {
      const {hrmCard} = this.props;
      hrmCard.setTopButtons(this.getTopButtons.bind(this));
      hrmCard.setTopRightMenus(this.getRightMenu.bind(this));
      hrmCard.setTopShowDropIcon(true);
      this.init(token);
    });
  }

  showDialog = (cb)=>{
    const {
        hrmFinance
    } = this.props, {
        financeExpand
    } = hrmFinance;

    if (window.doCheckSecondaryVerify4ec) {
        window.doCheckSecondaryVerify4ec({mouldCode: 'HRM', itemCode: 'SALARY'}, res => {
            if (res.status == "1") {
                cb && cb(res.token);
            }
            financeExpand.loading = false;
            financeExpand.isNeedSecondPwdVerify = false;
        })
    } else {
        financeExpand.fetchSecondPwdVerifyInfo().then(isNeedSecondPwdVerify => {
            isNeedSecondPwdVerify && financeExpand.openDialog();
            cb && cb();
        });
    }

  }

  init(token) {
    const {hrmFinance} = this.props;
    const hrmId = this.props.params.hrmId || '';
    hrmFinance.hrmId = hrmId;
    hrmFinance.init(token);
    hrmFinance.getTabInfo();
  }

  componentWillUnmount() {
    const {
      financeExpand
    } = this.props.hrmFinance, {
      resetParams
    } = financeExpand;
    resetParams();
  }


  render(){
    const { hrmFinance } = this.props;
    let {title,form,tabDatas,table,formFields,tabkey,isEditor} = hrmFinance;
    let qname = '';

    const {query} = this.props.location;
    const formParams = form.getFormParams();

    const {
      financeExpand
    } = hrmFinance, {
      isNeedSecondPwdVerify,
      dialogStore,
      loading,
    } = financeExpand, {
      visible
    } = dialogStore;

    if (isNeedSecondPwdVerify) {
      return (
        <div className='salary-pre'>
          <AlertPage ecId={`${this && this.props && this.props.ecId || ''}_AlertPage@7v5vm5`} loading={loading}/>
          {
            visible && <VerifyResourceID ecId={`${this && this.props && this.props.ecId || ''}_VerifyResourceID@89s97u`} store={financeExpand} />
          }
        </div>
      )
    }

    try{
    return (
      <div className='wea-myhrm-finance wea-myhrm' style={{background: '#ffffff',height:'100%', position: 'relative'}}>
          <div style={{minHeight:window.innerHeight-146,height:"100%"}} className={query.fromcard?"noTop":""}>
            <div style={query.fromcard? {display:'none'} :  {display:''}}>
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@04akab`}
              title={title()}
              icon={<i className='icon-coms-hrm' />}
              iconBgcolor='#217346'
              buttons={this.getTopButtons()}
              buttonSpace={10}
              showDropIcon={true}
              dropMenuDatas={this.getRightMenu()}
            />
            </div>
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@q0r16e`} spinning={isEmpty(toJS(table)) && isEmpty(toJS(formFields))} >
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ljefg8`} datas={this.getRightMenu()}>
              <div className='hrm-my-card-basicInfo hrm-my-cardInfo'>
                {this.getFormField()}
              </div>
              <div style={isEditor||isEmpty(tabDatas)? {display:'none'} : {height: '100%'}} className="pay-list">
              <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@qa9pb5`}
                  selectedKey={tabkey}
                  datas={tabDatas}
                  keyParam='key'
                  onChange={this.onTabChange}
                />
                {this.getTable()}
                </div>
            </WeaRightMenu>
            </Spin>
          </div>
      </div>
    );
    }catch(e){
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@2obf87`}>
          <div style={{ color: '#000' }}>{i18n.message.authFailed()}</div>
        </WeaAlertPage>
      )
    }
  }

  editCard = () => {
    const {hrmFinance} = this.props;
    hrmFinance.edit();
  }

  saveEditCard = () => {
    const {hrmFinance} = this.props;
    hrmFinance.save();
  }

  
  backCard = () => {
    this.init();
  }
  
  getTable = () => {
    const { hrmFinance } = this.props;
    let {table} = hrmFinance;
    table = toJS(table);
    if(!isEmpty(table)){
      return (<div className="wea-new-table wea-table-edit">
        <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@wungd5`} dataSource={table.datas} scroll={{x: table.columns.length * 100,y:$(".pay-list").height() - 90}} columns={this.reRenderColumns(table.columns)} pagination={false}/>
      </div>)
    }
  }

  reRenderColumns = (columns) => {
    columns.forEach(c=>{
        if(c.dataIndex.indexOf('column_')!=-1){
            c.render = function(text, record){
                return  <span title={record[c.dataIndex].titles || ''}>{typeof(record[c.dataIndex]) == 'object' ? record[c.dataIndex].value : record[c.dataIndex]}</span>
            }
        }
    })
    return columns;
  }

  getFormField = () => {
    const {hrmFinance} = this.props;
    let {form, formFields, isEditor} = hrmFinance;
    const {isFormInit} = form;
    let group = [];
    isFormInit && formFields.forEach((c, i) =>{
        let items = [];
        c.items.forEach( (field, j) => {
          items.push({
            com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@anitce@${j}`}
                underline={!isEditor}
                label={`${field.label}`}
                labelCol={{span: `${window.HrmLabelCol}`}}
                wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@49i4q6@${j}`} fieldConfig={field} form={form}/>
                </WeaFormItem>),
            colSpan: 1
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@qxdoyc@${i}`} className={`${isEditor?'hrm-center':''} ${c.isHide?'wea-hide':''}`}
          needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} col={window.HrmGroupCol}/>)
    });
    return group;
  }

  onTabChange = (key) => {
    const {hrmFinance} = this.props;
    hrmFinance.changeTab(key);
  }

  getRightMenu = () => {
    const {hrmFinance, hrmCard} = this.props;
    const {isEditor, buttons, hrmId} = hrmFinance;
    let arr = [];
    try{
    if(buttons && buttons.hasEdit){
        if (isEditor){
            arr = [{
                icon: <i className='icon-coms-common'/>,
                content:i18n.button.save(),
                key: 'save',
                onClick: key =>{
                  this.saveEditCard();
                }
            }, {
                icon: <i className='icon-coms-go-back'/>,
                content:i18n.button.back(),
                key: 'back',
                onClick: key =>{
                  this.backCard();
                }
                
            }]
        } else {
            arr = [{
                    icon: <i className='icon-coms-edit'/>,
                    content:i18n.button.modify(),
                    key: 'editCard',
                    onClick: key =>{
                        this.editCard();
                    }
                }
            ]

            arr.push(
            {
              icon: <i className='icon-coms-Print-log'/>,
              content:i18n.button.log(),
              key: 'showLog',
              onClick: key =>{
                window.setLogViewProps({logSmallType:i18n.smallType.HRM_RSOURCE_CARD_FINANCE,targetId:hrmId});
              }
            }
          )
        }
    }
  }catch(e){}
    return arr;
  }

  getTopButtons = () => {
    const {hrmFinance} = this.props;
    const {isEditor, buttons} = hrmFinance;
    const save = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d9r9r1`} type="primary" onClick={this.saveEditCard} >{i18n.button.save()}</Button>;
    const back = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0kqkox`} type="primary" onClick={this.backCard} >{i18n.button.back()}</Button>;
    const edit = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mvyesk`} type="primary" onClick={this.editCard} >{i18n.button.modify()}</Button>;
    const btns = [];
    try{
    if (isEditor) {
      if (buttons && buttons.hasSave) {
        btns.push(save);
        btns.push(back);
      }
    } else {
      if (buttons && buttons.hasEdit) {
        btns.push(edit);
      }
    }
  }catch(e){}
    return btns;
  }
}

export default HrmFinance
