import React from 'react';
import {
  inject,
  observer
} from 'mobx-react';
import {
  WeaTop,
  WeaTab,
  WeaOrgTree,
  WeaEchart,
  WeaYear,
  WeaDialog,
  WeaPopoverHrm,
  WeaCheckbox,
  WeaRadioGroup,
  WeaRightMenu,
  WeaTools,
  WeaErrorPage,
  WeaAlertPage,
  WeaDatePicker,
  WeaBrowser,
  WeaNewScroll,
  WeaSearchGroup
} from 'ecCom';

import {
  WeaTableNew
} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import {
  Modal,
  Row,
  Col,
  Button,
  Spin,
  Icon,
  Calendar,
  Tooltip,
  Timeline
} from 'antd';
import '../style/checking.less';
import '../style/outside.less';
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import toString from 'lodash/toString';
import moment from 'moment';
import * as Util from '../util/index';
import Map from '../coms/Map';
import loadjs from 'loadjs';

import OutSideTabkey1 from './OutsideTabkey1.js';
import OutSideTabkey2 from './OutsideTabkey2.js';
import OutSideTabkey3 from './OutsideTabkey3.js';
import {
  i18n
} from '../public/i18n';
import {
  WeaLocaleProvider
} from 'ecCom';
import {
  carousel
} from '../util/index'
import {addContentPath} from '../util/index.js'
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;

@inject('hrmOutside')

@observer
class main extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.init();
    this.getData();
    //document.title = hrmOutside.title;
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      const {
        hrmOutside
      } = this.props;
      hrmOutside.init();
      this.getData();
    }
  }
  getData() {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.getData();
  }
  getRightMenu() {
    const {
      hrmOutside
    } = this.props;
    const {
      dataKey,
      tabkey,
      hasRight
    } = hrmOutside;
    let btns = [];
    if (tabkey == '3' && hasRight) { //分页控件导出有bug，先屏蔽
      btns.push({
        key: "exportExcel",
        icon: <i className='icon-coms-export'/>,
        content: i18n.button.export(),
        onClick: key => {
          hrmOutside.exportExcel(dataKey)
        }
      });
    }

    return btns;
  }
  chooseUser(e) {
    const {
      hrmOutside
    } = this.props;
    let hrmId = '',
      hrmName = undefined;
    if (e.selected) {
      hrmId = e.node.props.id;
      hrmName = e.node.props.name;
    }
    if (hrmId) {
      hrmOutside.updateHrmId(hrmId);
      if (hrmName) hrmOutside.updateHrmName(hrmName);
      this.getData();
    }
  }
  changeUserRoot(ids, names, datas) {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.updateUserRoot(datas);
  }
  resetUserRoot() {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.updateUserRoot();
    hrmOutside.updateHrmId();
    hrmOutside.updateHrmName();
    this.getData();
  }
  reFresh() {
    this.getData();
  }
  changeTab(key) {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.changeTab(key);
    //this.resetUserRoot();
    if(key!="3"){
      this.getData();
    }
    
  }
  changeDateTab(key) {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.changeDateTab(key);
    this.getData();
  }
  changeDate(v1, v2) {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.changeDate(v1, v2);
    this.getData();
  }
  handlerCheckbox(v) {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.handlerCheckbox(v);
  }
  handlerPosition(item) {
    const {
      hrmOutside
    } = this.props;
    hrmOutside.updatePosition(item);
    hrmOutside.updateVisible(true);
  }
  onTreeCheck(ids, datas) {
    const {
      hrmOutside
    } = this.props;
    let idds = [];
    datas.forEach((d) => {
      idds.push(d.id);
    })
    hrmOutside.updateHrmId(idds.join(','));
    hrmOutside.updateOrgTreeCheckedDatas(datas);
    this.getData();
  }
  renderLeft() {
    const {
      hrmOutside
    } = this.props;
    let {
      leftTitle,
      userRoot,
      orgTreeIsMult,
      orgTreeCheckedDatas
    } = hrmOutside;
    userRoot = toJS(userRoot);
    return <div className="wea-hrm-checking-left" style={{height: window.innerHeight - 125}}>
      <div className="left-header">
        <div className="header-title bb">
          <div style={{padding: '0 15px'}}>
            <span style={{float: 'left'}}>{leftTitle()}</span>
            <span style={{float: 'right', fontSize: '12px'}}>
                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@lgdz1j`} onChange={(v)=> {
                    hrmOutside.updateOrgTreeIsMult(v);
                    hrmOutside.updateOrgTreeCheckedDatas();
                    this.refs.orgTree && this.refs.orgTree.resetCheck()
                }}
              value={orgTreeIsMult}/>&nbsp;&nbsp;{getLabel('386504',"开启选择")}
            </span>
          </div>
        </div>
      </div>
      <div className="left-body">
        <div>
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@pgolae`} isSingle={true}
              linkUrl="/hrm/resource/HrmResource.jsp?id=" title={getLabel('179',"人力资源")} type="1" viewAttr="2"
              replaceDatas={userRoot}
              customIcon="icon-coms-Reset"
              addOnClick={this.resetUserRoot.bind(this)}
              onChange={this.changeUserRoot.bind(this)}
            />
            <div style={{display: orgTreeIsMult == '0'?'block':'none',height: window.innerHeight - 225}}>
              <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@31k36r`}
                renderNodeId = {(item)=> item.id}
                dataUrl="/api/hrm/base/getHrmResourceTree"
                rootKey="rootManager"
                treeNodeClick={this.chooseUser.bind(this)}
                params={Array.isArray(userRoot) && userRoot[0] ? {rootid: userRoot[0].id} : {}}
              />
            </div>
            <div style={{display: orgTreeIsMult == '1'?'block':'none',height: window.innerHeight - 225}}>
              <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@nr691d`}
                ref="orgTree"
                dataUrl="/api/hrm/base/getHrmResourceTree"
                rootKey="rootManager"
                onCheck={this.onTreeCheck.bind(this)}
                isMult={true}
                checkStrictly={false}
                checkedDatas={orgTreeCheckedDatas}
                params={Array.isArray(userRoot) && userRoot[0] ? {rootid: userRoot[0].id} : {}}
              />
            </div>
        </div>
      </div>
    </div>
  }
  renderList() {
    const {
      hrmOutside
    } = this.props;
    let {
      timeData
    } = hrmOutside;
    timeData = toJS(timeData);
    return <Timeline ecId={`${this && this.props && this.props.ecId || ''}_Timeline@7x4jhb`} className="list-wrapper grayBG">
      {
        timeData && timeData.map((item,index) => {
          return <Timeline.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@n3i6ob@${index}`} className="list-item">
            <div className="list-item-wrapper">
              <div className="list-item-title">{item.date}</div>
              <div className="list-item-content">
                {
                  isEmpty(item.items) && <div className="no-signinfo gray align-center">
                      <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@bb4xa6@${index}`} type="frown gray" style={{marginRight : 10}} />
                      {getLabel('386505',"当天无外勤签到记录")}
                    </div>
                }
                {
                  !isEmpty(item.items) && item.items.map(i=> {
                    return <div className="list-item-single">
                      <div className="mb5">
                        {i.name}
                        <span className="gray" style={{marginLeft: 15}}>{i.time}</span>
                        <span style={{float: 'right', marginRight: 10, color: '#67AFF7'}}>{i.signTitle}</span>
                      </div>
                      {i.information && <div className="mb5" dangerouslySetInnerHTML={{__html: i.information}}></div>}
                      {i.pics && <div className="mb5">
                        {
                          i.pics.map(pic=> {
                            return <div>{
                              <img src={addContentPath(pic)} border="0" width="100" height="110" onClick={event => carousel(pic,index,'ant-timeline-item')}/>
                            }
                            </div>
                          })
                        }
                        </div>
                      }
                      {
                        i.crm && i.crm.length > 0 &&
                        <div style={{display: 'flex'}}>
                          <i className="icon-coms-currency-Customer" style={{marginRight: 10}}/>
                          <div style={{flex: 1, width: '98%'}}>
                            {
                              i.crm.map((d, i) => {
                                return (
                                  <div className='text-elli'>{d}</div>
                                )
                              })
                            }
                          </div>
                        </div>
                      }
                      <span className="cursor-pointer gray"
                          onClick={this.handlerPosition.bind(this, i)}>
                          <i className="icon-coms-position" style={{marginRight: 6}}/> {i.title}</span>
                    </div>
                  })
                }
              </div>
            </div>
          </Timeline.Item>
        })
      }
    </Timeline>
  }



  renderDetail() {
    const {
      hrmOutside
    } = this.props;
    let {
      config,
      dataKey,
      table,
      onRadioGroupChange     
    } = hrmOutside;
    config = toJS(config);
    return <div className="radio-search-group">
     {/* <WeaRadioGroup config={config()} onChange={(params)=> {console.debug(1);hrmOutside.radioGroupParams=params;hrmOutside.getData(params)}}/> */}
     <WeaRadioGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaRadioGroup@qawhry`} config={toJS(config)} onChange={(params)=> {hrmOutside.radioGroupParams=params;hrmOutside.onRadioGroupChange(params)}}/>
     <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@2ry8am`} needTigger={true} title={getLabel('19325',"明细表")} showGroup={true}>
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@r5jcrz`}
        comsWeaTableStore={table}
        hasOrder={true}
        needScroll={true}
        getColumns={columns => this.reRenderColumns(columns,hrmOutside)}
        />
      </WeaSearchGroup>
     </div>
    
  }
  reRenderColumns = (columns, store) => {
    const {
      handleViewClick
    } = store;

    columns.map(c => {
      if (c.dataIndex === 'canViewSignImg') {
        c.render = function(text, record) {
          const {
            randomFieldId,
            canViewSignImgspan
          } = record;
          if (canViewSignImgspan === '1') {
            return <a onClick={() => handleViewClick(randomFieldId)}>{getLabel(33564,'查看')}</a>
          } else {
            return <span />
          }
        }
      }
    });
  }
  renderMap() {
    const {
      hrmOutside
    } = this.props;
    let {
      mapData
    } = hrmOutside;
    mapData = toJS(mapData);
    if (!isEmpty(mapData)) {
      return <Map ecId={`${this && this.props && this.props.ecId || ''}_Map@x9b9e7`} config={mapData} mult/>
    } else {
      return <div className="grayBG"><WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@guvicv`}
      icon={<img style={{width: 77, height: 97}} src={addContentPath('/cloudstore/resource/pc/com/images/no_sign.png')}/>}
      ><div>{getLabel('386505',"当天无外勤签到记录")}</div></WeaAlertPage></div>
    }
  }
  renderContent() {
    const {
      hrmOutside
    } = this.props;
    let {
      tabkey
    } = hrmOutside;
    if (tabkey == 1) return this.renderList();
    if (tabkey == 2) return this.renderMap();
    if (tabkey == 3) return this.renderDetail();
  }

  getTabButtonsAd() {
    const {
      hrmOutside
    } = this.props;
    const {
      dataKey
    } = hrmOutside;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h2bec9@1`} type="primary" onClick={()=>{hrmOutside.exportExcel(dataKey)}}>{i18n.button.export()}</Button>),
    ]
  }

  showtabs(){
    const {
      hrmOutside
    } = this.props;
    let {
      tabkey
    } = hrmOutside;
    return tabkey==3?<OutSideTabkey3 ecId={`${this && this.props && this.props.ecId || ''}_OutSideTabkey3@cpqfjr`} {...this.props}/>:this.renderContent()
  }

  render() {
    const {
      hrmOutside
    } = this.props;
    let {
      title,
      tabkey,
      tabDatas,
      loading,
      hasRight,
      hrmName,
      dateTabkey,
      dateTabDatas,
      dateTabDatas1,
      pDate,
      showSignInfo,
      signTitle,
      visible,
      positionObj,
      getRadioGroupConfig
    } = hrmOutside;
    tabDatas = tabDatas();
    dateTabDatas1 = dateTabDatas1();
    dateTabDatas = dateTabDatas();
    positionObj = toJS(positionObj);
    const errorMsg = getLabel('386507', "你无权查看{params}的外勤数据！").replace('{params}', hrmName);
    return (
      <div className="wea-hrm-checking wea-hrm-outside">
          <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@jsxngc`} />
          <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@x45bue`}
            visible={visible}
            onCancel={()=> {hrmOutside.updateVisible(false);}}
            closable
            style={{width: 700, height: 500}}
            title = {getLabel('386506',"位置详情")}
            icon="icon-coms-hrm"
            iconBgcolor='#008572'
          >
            {visible &&<Map ecId={`${this && this.props && this.props.ecId || ''}_Map@axdn1n`} config={positionObj} ref="map1"/>}
          </WeaDialog>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@n2tc87`} spining={loading}>
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@wiqo47`} datas={this.getRightMenu()}>
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@2t013k`}
                title={title()}
                icon={<i className='icon-coms-hrm'/>}
                iconBgcolor='#217346'
                buttons={[]}
                buttonSpace={10}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
              >
                {this.renderLeft()}
                <div style={{width: '100%', paddingLeft: 221}}>
                  <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@02rcfa`}
                    buttons={tabkey==3 && this.getTabButtonsAd()}
                    selectedKey={tabkey}
                    keyParam='key'
                    datas={tabDatas}
                    onChange={this.changeTab.bind(this)}
                  />
                  {
                    tabkey!=3 && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@f22knl`} className="picker-wrapper">
                      {tabkey == 1 && dateTabDatas.map((item)=> {
                        return <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@w553ql@1`} span={1} onClick={this.changeDateTab.bind(this, item.key)} className={`cursor-pointer date-item ${item.key===dateTabkey?'active':'' }`}>
                          {item.title}
                         </Col>
                        }
                      )}
                      {tabkey == 2 && dateTabDatas1.map((item)=> {
                        return <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@74encf@2`} span={1} onClick={this.changeDateTab.bind(this, item.key)} className={`cursor-pointer date-item ${item.key===dateTabkey?'active':'' }`}>
                          {item.title}
                         </Col>
                        }
                      )}
                      <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@0c5bq0`} span={13} className="picker">
                        <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@hjxlz3`} arrow type={dateTabkey == '3' ? 'month': 'day'} date={pDate} onChange={this.changeDate.bind(this)}/>
                        <i className="icon-coms-Refresh cursor-pointer outside-refresh" onClick={this.reFresh.bind(this)}/>
                      </Col>
                      <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@hk28pe`} span={6} className ="checkbox-wrapper" title={signTitle()}>
                        <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@jyzl9z`} value={showSignInfo} onChange={this.handlerCheckbox.bind(this)}/>
                        {signTitle()}
                      </Col>
                    </Row>
                  }
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@ad6pfy`} height={tabkey==3? window.innerHeight - 150 - 35 : window.innerHeight - 150 - 65}>
                    <div className={`${tabkey == 2 ? 'wea-outside-content': ''}`}>
                     
                      {!hasRight ? <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@amx6wv`}>
                        <div>{errorMsg}</div>
                      </WeaAlertPage>
                      :
                      this.showtabs()
                      // this.renderContent()
                      // <div>
                      //   {
                      //     tabkey == 1 &&this.renderContent()
                      //     // <OutSideTabkey1 {...this.props} />
                      //   }
                      //   {
                      //     tabkey == 2 &&this.renderContent()
                      //     // <OutSideTabkey2 {...this.props} />
                      //   }
                      //   {
                      //     tabkey == 3 &&
                      //     <OutSideTabkey3 {...this.props}/>
                      //   }                        
                      // </div>
                      }
                    </div>
                  </WeaNewScroll>
                </div>
              </WeaTop>
            </WeaRightMenu>
          </Spin>
        </div>
    )
  }
}

export default main