import React from 'react';
import { inject, observer} from 'mobx-react';
import {WeaTop, WeaTab, WeaOrgTree, WeaEchart, WeaYear, WeaDialog, WeaPopoverHrm,
    WeaRightMenu,WeaTools,WeaErrorPage, WeaAlertPage, WeaDatePicker,WeaBrowser, WeaNewScroll
} from 'ecCom';
import {Modal, Row, Col, Button, Spin, Icon, Calendar, Tooltip, Timeline} from 'antd';
import '../style/checking.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 {i18n} from '../public/i18n';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;

@inject('hrmShift')

@observer
class main extends React.Component {
  constructor(props) {
    super(props);
    const { hrmShift } = this.props;
    hrmShift.init();
  }
  componentDidMount() {
    this.getData();
    const { hrmShift } = this.props;
    //document.title = hrmShift.title;
  }
  componentWillReceiveProps(nextProps) {
    if(this.props.location.key !== nextProps.location.key) {
      const { hrmShift } = this.props;
      hrmShift.init();
      this.getData();
    }
  }
  getData() {
    const { hrmShift } = this.props;
    hrmShift.getData();
  }
  getRightMenu(){
    const {hrmShift} = this.props;
    const {newChecking} = hrmShift;
    let btns = [];
    btns.push({
          key: "search",
          icon: <i className='icon-workflow-Right-menu--search'/>,
          content: newChecking(),
          onClick: key =>{
            this.addChecking();
          }
      });
    return btns;
  }
  addChecking() {
    const {hrmShift} = this.props;
    hrmShift.updateNewVisible(true);
  }
  chooseUser(e) {
    const {hrmShift} = this.props;
    let hrmId = '', hrmName = undefined;
    if (e.selected) {
        hrmId = e.node.props.id;
        hrmName = e.node.props.name;
    }
    if (hrmId) {
      hrmShift.updateHrmId(hrmId);
      if (hrmName) hrmShift.updateHrmName(hrmName);
      this.getData();
    }
  }
  changeUserRoot(ids,names,datas) {
    const {hrmShift} = this.props;
    hrmShift.updateUserRoot(datas);
  }
  resetUserRoot() {
    const {hrmShift} = this.props;
    hrmShift.updateUserRoot();
    hrmShift.updateHrmId();
    hrmShift.updateHrmName();
    this.getData();
  }
  changeDateTab(key) {
    const {hrmShift} = this.props;
    hrmShift.changeDateTabHandler(key);
    this.getData();
  }
  reFresh() {
    const {hrmShift} = this.props;
    this.getData();
  }
  changeDate(v) {
    const {hrmShift} = this.props;
    const {dateTabkey} = hrmShift;
    if (dateTabkey == '2') {
      v = new moment(v).format('YYYY-MM');
    } else {
      v = new moment(v).format('YYYY');
    }
    hrmShift.changeDateHandler(v);
    this.getData();
  }
  renderLeft() {
    const {hrmShift} = this.props;
    let {leftTitle, userRoot} = hrmShift;
    userRoot = toJS(userRoot);
    return <div className="wea-hrm-checking-left" style={{height: window.innerHeight - 125}}>
      <div className="left-header">
        <div className="header-title bb align-center header-title-shift">
          {leftTitle}
        </div>
      </div>
      <div className="left-body">
        <div>
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@khwx7g`} 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={{height: window.innerHeight - 225}}>
            <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@ljvk0o`} dataUrl="/api/hrm/base/getHrmResourceTree" rootKey="rootManager"
                treeNodeClick={this.chooseUser.bind(this)}
                params={Array.isArray(userRoot) && userRoot[0] ? {rootid: userRoot[0].id} : {}}
            />
            </div>
        </div>
      </div>
    </div>
  }
  getLocale() {
		return {
			firstDayOfWeek: 0,
			lang: {
				format: {
					eras: [getLabel(383357, "公元前"), getLabel(383358, "公元")],
					months: [getLabel(1492, "一月"), getLabel(1493, "二月"), getLabel(383385, "三月"), getLabel(383387, "四月"), getLabel(1496, "五月"), getLabel(383392, "六月"),
						getLabel(383393, "七月"), getLabel(383394, "八月"), getLabel(383395, "九月"), getLabel(383396, "十月"), getLabel(383397, "十一月"), getLabel(383398, "十二月")
					],
					shortMonths: [getLabel(1492, "一月"), getLabel(1493, "二月"), getLabel(383385, "三月"), getLabel(383387, "四月"), getLabel(1496, "五月"), getLabel(383392, "六月"),
						getLabel(383393, "七月"), getLabel(383394, "八月"), getLabel(383395, "九月"), getLabel(383396, "十月"), getLabel(383397, "十一月"), getLabel(383398, "十二月")
					],
					weekdays: [getLabel(24626, "星期天"), getLabel(383399, "星期一"), getLabel(383400, "星期二"), getLabel(383402, "星期三"), getLabel(383403, "星期四"),
						getLabel(383404, "星期五"), getLabel(383405, "星期六")
					],
					shortWeekdays: [getLabel(16106, "周日"), getLabel(16100, "周一"), getLabel(16101, "周二"), getLabel(16102, "周三"), getLabel(16103, "周四"), getLabel(16104, "周五"),
						getLabel(16105, "周六")
					],
					veryShortWeekdays: [getLabel(16106, "周日"), getLabel(16100, "周一"), getLabel(16101, "周二"), getLabel(16102, "周三"), getLabel(16103, "周四"), getLabel(16104, "周五"), getLabel(16105, "周六")],
					ampms: [getLabel(383408, "上午"), getLabel(383409, "下午")],
					datePatterns: [`yyyy'${getLabel(383372,"年")}'M'${getLabel(383373,"月")}'d'${getLabel(383374,"日")}' EEEE`, `yyyy'${getLabel(383372,"年")}'M'${getLabel(383373,"月")}'d'${getLabel(383374,"日")}'`, "yyyy-M-d", "yy-M-d"],
					timePatterns: [`ahh'${getLabel(383411,"时")}'mm'${getLabel(383412,"分")}'ss'${getLabel(383414,"秒")}' 'GMT'Z`, `ahh'${getLabel(383411,"时")}'mm'${getLabel(383412,"分")}'ss'${getLabel(383414,"秒")}'`, "H:mm:ss", "ah:mm"],
					dateTimePattern: '{date} {time}'
				}
			},
		}
	}
  onyearMonthSelect(date) {
    const {hrmShift} = this.props;
    let select = new moment(date.time).format('YYYY-MM');
    hrmShift.changeDateHandler(select);
    hrmShift.updateDateTabkey('2');
    this.getData();
  }
  monthDateCellRender(date) {
    const {hrmShift} = this.props;
    let {dateTabkey, pDate, calendarData, statusActiveType} = hrmShift;
    calendarData = toJS(calendarData);
    let select = new moment(date.time).format('YYYY-MM');
    if (pDate.slice(0,7) == select) {
      let day = date.getDayOfMonth();
      let data = calendarData[day];
      if (data) {
        return (
          <div className="calendar-item">
            <span className="tip" style={{color: data.isWorkDay?'#FF1B10':'#1B9B12'}}>{data.tip}</span>
            {
              data.items && data.items.map((item, i)=> {
                return <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@nnllqe@${i}`} placement="right" title={item.title}>
                        <div className='workflow-item text-overflow shift-item' style={{backgroundColor: item.color}}>
                          {item.title}
                        </div>
                  </Tooltip>
              })
            }
          </div>
        )
      }
    }
  }
  renderYearCellBottom(items) {
    if (!isEmpty(items)) {
      return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@or3wgj`} className="year-cell-bottom">
        {
          items.map((item, i)=> {
            return <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@cb986k@${i}`} span={24/items.length} style={{backgroundColor: item.color, height: '100%'}}></Col>
          })
        }
      </Row>
    }
  }
  yearDateCellRender(date) {
    const {hrmShift} = this.props;
    let {pDate, yearData} = hrmShift;
    yearData = toJS(yearData);
    const d = date.getDayOfMonth();
    const m = date.getMonth() + 1;
    let data = {};
    if (yearData !== undefined && !isEmpty(yearData)) {
      data = yearData[m][d];
    }
    let content = <span>
      {data.tip && <span className="tip" style={{color: data.isWorkDay?'#FF1B10':'#1B9B12'}}>{data.tip}</span>}
      {d}
      {data.items && this.renderYearCellBottom(data.items)}
    </span>
    return <div className="date-item">
      {content}
    </div>
  }
  renderCalendar() {
    const {hrmShift} = this.props;
    let {dateTabkey, pDate} = hrmShift;
    return <div className="calendar-wrapper">
        {dateTabkey == '2' &&
          <Calendar ecId={`${this && this.props && this.props.ecId || ''}_Calendar@bu7v0s`}
            mode="month"
            dateCellRender={this.monthDateCellRender.bind(this)}
            locale={this.getLocale()}
            value={new Date(pDate)}
          />
        }
        {dateTabkey == '1' &&
          <WeaYear ecId={`${this && this.props && this.props.ecId || ''}_WeaYear@jjf3q4`} value={pDate}
            dateCellRender={this.yearDateCellRender.bind(this)}
            onMonthSelect={this.onyearMonthSelect.bind(this)}
          />
        }
    </div>
  }

  render() {
    const {hrmShift} = this.props;
    const {title,dateTabDatas, dateTabkey, pDate, hasRight, canSearch, leftTitle, hrmName, loading} = hrmShift;
    const errorMsg = getLabel('386500',"您无权查看 {params} 的排班数据！").replace('{params}', hrmName);
    return (
        <div className="wea-hrm-checking">
          <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@q0b33v`} />
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@vtzq3b`} spining={loading}>
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@8yg5m0`}
              title={title()}
              icon={<i className='icon-coms-hrm'/>}
              iconBgcolor='#217346'
              buttons={[]}
              buttonSpace={10}
              showDropIcon={false}
              // dropMenuDatas={this.getRightMenu()}
            >
              {canSearch && this.renderLeft()}
              <div style={{width: '100%', paddingLeft: canSearch ?221 : 0}}>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@htwf7m`} className="picker-wrapper">
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3d7n8w`} span={2} className="leftTitle" >{leftTitle()}&nbsp;:&nbsp;&nbsp;{hrmName}</Col>
                  {[ {title:i18n.label.year(),key:"1"}, {title:i18n.label.month(),key:"2"}].map((item, i)=> {
                    return  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@a8meg9@${i}`} 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@gzgftb`} span={10} className="picker">
                    <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@p6jb0f`} arrow type={dateTabkey == '1' ? 'year': 'month'} date={pDate} onChange={this.changeDate.bind(this)}/>
                    <i className="icon-coms-Refresh cursor-pointer" onClick={this.reFresh.bind(this)}/>
                  </Col>
                </Row>

                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@md30ha`} height={window.innerHeight - 153 - 15} className="bt">
                    {!hasRight && <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@cwv3lj`} >
                      <div>{errorMsg}</div>
                    </WeaAlertPage>}
                    {hasRight &&
                      <div className="hrm-checking-content">
                        {this.renderCalendar()}
                      </div>
                    }
                  </WeaNewScroll>

              </div>
            </WeaTop>
          </Spin>
        </div>
    )
  }
}

export default main
