import React from 'react';
import moment from 'moment';
import "moment/locale/zh-cn";
import { connect } from 'dva';
import axios from 'axios';
import {
  Tabs,
  Alert,
  DatePicker,
  Button,
  Table,
  Popover,
  Icon,
  message
} from 'antd';
import store from 'store';

import { getHostByPath } from '../../../utils/request';

import './statistics.less';

const TabPane = Tabs.TabPane;
const { MonthPicker } = DatePicker;
const namespace = 'task';

const mapStateToProps = state => {
  return {
    monthStatisticsData: state[namespace].monthStatisticsData,
    companyName: state['global'].companyInfo.comName
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getmonthStatisticsData: payload => {
      dispatch({
        type: `${namespace}/getmonthStatisticsData`,
        payload
      });
    },
    resetModel: payload => {
      dispatch({
        type: `${namespace}/resetModel`,
        payload
      });
    },
    exportData: payload => {
      dispatch({
        type: `${namespace}/exportData`,
        payload
      });
    }
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class MonthStatistics extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // dateRange: `数据时间范围：${moment(new Date()).format(
      //   monthFormat
      // )}.01~${moment(new Date()).format(monthFormat)}.${moment(
      //   moment(new Date()).format(monthFormat)
      // ).daysInMonth()}`
      dateRange: `数据时间范围：`,
      startDate: '',
      endDate: '',
      month: ''
    };
  }

  onPickMonth = (date, dateString) => {
    this.props.getmonthStatisticsData({
      month: dateString.replace('-', ''),
      startDate: `${dateString}-01`,
      endDate: `${dateString}-${moment(date).daysInMonth()}`,
      departId: '',
      keyWord: '',
      pageNumber: this.props.monthStatisticsData.pagination.pageNumber,
      pageSize: this.props.monthStatisticsData.pagination.pageSize
    });
    dateString = dateString.replace('-', '.');
    this.setState({
      dateRange: `数据时间范围：${dateString}.01~${dateString}.${moment(
        date
      ).daysInMonth()}`,
      month: dateString.replace('-', ''),
      startDate: `${dateString}-01`,
      endDate: `${dateString}-${moment(date).daysInMonth()}`
    });
  };

  handlePage = (page, pageSize) => {
    if (!this.state.month) {
      message.warning('请选择数据时间范围！');
      return;
    }
    this.props.getmonthStatisticsData({
      month: this.state.month,
      startDate: this.state.startDate,
      endDate: this.state.endDate,
      departId: '',
      keyWord: '',
      pageNumber: page,
      pageSize: pageSize
    });
  };

  handlePageSize = (current, size) => {
    if (!this.state.month) {
      message.warning('请选择数据时间范围！');
      return;
    }
    this.props.getmonthStatisticsData({
      month: this.state.month,
      startDate: this.state.startDate,
      endDate: this.state.endDate,
      departId: '',
      keyWord: '',
      pageNumber: 1,
      pageSize: size
    });
  };

  renderColumns = data => {
    return data.map(v => {
      return {
        title: (
          <div>
            {v.title}
            {v.tip && v.tip.length > 0 ? (
              <Popover
                content={
                  <span
                    style={{
                      width: '300px',
                      whiteSpace: 'normal',
                      display: 'inline-block',
                      padding: '10px'
                    }}
                  >
                    {v.tip}
                  </span>
                }
                placement="rightTop"
              >
                <Icon
                  type="question-circle"
                  style={{
                    color: '#faad14',
                    marginLeft: '4px'
                  }}
                />
              </Popover>
            ) : (
              ''
            )}
          </div>
        ),
        dataIndex: v.dataIndex,
        align: v.align,
        key: v.key,
        fixed: v.fixed,
        children: v.children ? this.renderColumns(v.children) : null,
        render: v.children
          ? null
          : (text, record, index) => {
              if (v.width >= 300) {
                return (
                  <Popover
                    content={
                      <span
                        style={{
                          whiteSpace: 'normal',
                          width: '300px',
                          display: 'inline-block',
                          padding: '10px'
                        }}
                      >
                        {text}
                      </span>
                    }
                    placement="rightTop"
                  >
                    <p
                      style={{
                        maxWidth: '300px',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        overflow: 'hidden',
                        marginTop: '8px',
                        marginBottom: '8px'
                      }}
                      dangerouslySetInnerHTML={{
                        __html: text
                      }}
                    />
                  </Popover>
                );
              } else {
                if (v.key === 'operation') {
                  return (
                    <div style={{ width: 40 }}>
                      <a onClick={() => this.openDetail(record.perId)}>操作</a>
                    </div>
                  );
                } else if (v.key === 'perId') {
                  return <p>{(this.props.monthStatisticsData.pagination.pageNumber - 1) * this.props.monthStatisticsData.pagination.pageSize + index + 1}</p>;
                } else if (v.key === 'result') {
                  return (
                    <Popconfirm
                      overlayClassName="change-clock-pop"
                      title={
                        <div>
                          <h4>修改打卡结果{record.key}</h4>
                          <RadioGroup
                            onChange={this.onChange}
                            value={this.state.value}
                          >
                            <Radio value={1}>正常</Radio>
                            <Radio value={2}>漏卡</Radio>
                            <Radio value={3}>迟到</Radio>
                          </RadioGroup>
                          <Input
                            placeholder=""
                            style={{ width: 80 }}
                            size="small"
                          />
                          分钟
                        </div>
                      }
                      onConfirm={this.confirm}
                      onCancel={this.cancel}
                      okText="确定"
                      cancelText="取消"
                      icon={null}
                    >
                      <a href="#">Delete</a>
                    </Popconfirm>
                  );
                } else {
                  return (
                    <p
                      dangerouslySetInnerHTML={{
                        __html: text
                      }}
                    />
                  );
                }
              }
            }
      };
    });
  };

  //声明函数 导出excel
  exportData = () => {
    axios({
      method: 'get',
      url:
        getHostByPath() +
        '/task/count/task-count/export-count-per-task-month', //后台请求地址
      responseType: 'blob',
      params: {
        month: this.state.month,
        startDate: this.state.startDate,
        endDate: this.state.endDate,
        departId: '',
        keyWord: ''
      },
      headers: {
        access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

      }
    }).then(data => {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(data.data);
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute(
        'download',
        `${this.props.companyName}_${this.state.month.replace(
          '.',
          ''
        )}驻勤报表_${moment().format('YYYYMMDDHHmmss')}.xls`
      );
      document.body.appendChild(link);
      link.click();
    });
  };

  componentWillUnmount() {
    this.props.resetModel();
  }

  render() {
    const dataSource = this.props.monthStatisticsData.data;
    const columns = this.renderColumns(this.props.monthStatisticsData.columns);

    return (
      <div className="statistics">
        <Tabs defaultActiveKey="1" style={{ padding: '0 20px' }}>
          <TabPane tab="驻勤月报" key="1">
            <Alert
              message={
                <div>
                  <p style={{ marginBottom: 0 }}>
                    数据：驻勤月报实时读取、汇总日报数据，若您需要修改打卡情况，请到日报中直接修改。
                  </p>
                  <p style={{ marginBottom: 0 }}>
                    查询：驻勤月报仅可查询前6个月及本月的报表，请及时导出保存，若您需要更多的驻勤数据，请联系在线客服获取。
                  </p>
                </div>
              }
              type="warning"
              showIcon
              style={{ marginBottom: '15px' }}
            />
            <div className="operation-area">
              <div className="left">
                <MonthPicker
                  // defaultValue={moment(
                  //   moment().year() + '-' + (moment().month() + 1)
                  // )}
                  onChange={this.onPickMonth}
                />
                <div className="month-picker-tip">{this.state.dateRange}</div>
              </div>
              <div className="right">
                <Button
                  type="primary"
                  onClick={this.exportData}
                  disabled={!this.props.monthStatisticsData.data.length}
                >
                  导出
                </Button>
              </div>
            </div>
            <div className="table-area">
              <Table
                // rowKey={record => record.perId} 需要一个唯一的key，未发现唯一值，如果必要可以自己创建一个
                dataSource={dataSource}
                columns={columns}
                // scroll={{ x: '100%' }}
                // scroll={{ x: '1560px' }}
                bordered
                size="small"
                pagination={{
                  current: this.props.monthStatisticsData.pagination.pageNumber,
                  total: this.props.monthStatisticsData.pagination.total,
                  pageSize: this.props.monthStatisticsData.pagination.pageSize,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  onChange: this.handlePage,
                  onShowSizeChange: this.handlePageSize
                }}
              />
            </div>
          </TabPane>
        </Tabs>
      </div>
    );
  }
}
