import React from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Tabs,
  Alert,
  DatePicker,
  Button,
  Table,
  Popover,
  Icon,
  TreeSelect,
  Input,
  Form,
  Modal,
  Popconfirm,
  Radio,
  message
} from 'antd';

import './statistics.less';

const TabPane = Tabs.TabPane;
const { RangePicker } = DatePicker;
const namespace = 'monitor';
const dateFormat = 'YYYY/MM/DD';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const detailColumns = [
  {
    title: '打卡',
    dataIndex: 'attendRecordTurn',
    align: 'left',
    key: 'attendRecordTurn'
  },
  {
    title: '内勤时间',
    dataIndex: 'attendTime',
    align: 'left',
    key: 'attendTime'
  },
  {
    title: '打卡时间',
    dataIndex: 'clockInTime',
    align: 'left',
    fixed: false,
    key: 'clockInTime'
  },
  {
    title: '打卡结果',
    dataIndex: 'attendResult',
    align: 'left',
    fixed: false,
    key: 'attendResult'
  },
  {
    title: '打卡地址',
    dataIndex: 'attendAddress',
    align: 'left',
    fixed: false,
    key: 'attendAddress',
    width: 300
  },
  {
    title: '备注',
    dataIndex: 'remark',
    align: 'left',
    fixed: false,
    key: 'remark',
    width: 300
  }
];

const mapStateToProps = state => {
  return {
    dayStatisticsData: state[namespace].dayStatisticsData,
    departmentData: state[namespace].departmentData,
    detailData: state[namespace].detailData
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getdayStatisticsData: payload => {
      dispatch({
        type: `${namespace}/getdayStatisticsData`,
        payload
      });
    },
    resetModel: payload => {
      dispatch({
        type: `${namespace}/resetModel`,
        payload
      });
    },
    getDepartMentData: payload => {
      dispatch({
        type: `${namespace}/getDepartMentData`,
        payload
      });
    },
    getAttendRecordDetail: payload => {
      dispatch({
        type: `${namespace}/getAttendRecordDetail`,
        payload
      });
    },
    changeRecordDetail: payload => {
      dispatch({
        type: `${namespace}/changeRecordDetail`,
        payload
      });
    }
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
@Form.create()
export default class DayStatistics extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openDetailModal: false, // 是否打开详情模态框
      dateRange: [
        moment(
          moment().year() +
            '-' +
            (moment().month() + 1 + '-' + moment().date()),
          dateFormat
        ),
        moment(
          moment().year() +
            '-' +
            (moment().month() + 1) +
            '-' +
            (moment().date() + 1),
          dateFormat
        )
      ], // 内勤日期范围
      attendStatus: 0, // 打卡结果
      minute: null, // 迟到/早退时间
      disableMinute: true // 默认禁止用户输入
    };
  }

  handlePage = (page, pageSize) => {
    let values = this.props.form.getFieldsValue();
    if (!values.dateRange.length) {
      message.warning('请选择内勤日期！');
      return;
    }
    values = {
      ...values,
      dateRange: [
        values.dateRange[0].format('YYYY-MM-DD'),
        values.dateRange[1].format('YYYY-MM-DD')
      ]
    };
    this.props.getdayStatisticsData({
      startDate: values.dateRange[0],
      endDate: values.dateRange[1],
      departId: values.department,
      keyWord: values.keyWord,
      pageSize: pageSize,
      pageNumber: page
    });
  };

  handlePageSize = (current, size) => {
    let values = this.props.form.getFieldsValue();
    if (!values.dateRange.length) {
      message.warning('请选择内勤日期！');
      return;
    }
    values = {
      ...values,
      dateRange: [
        values.dateRange[0].format('YYYY-MM-DD'),
        values.dateRange[1].format('YYYY-MM-DD')
      ]
    };
    this.props.getdayStatisticsData({
      startDate: values.dateRange[0],
      endDate: values.dateRange[1],
      departId: values.department,
      keyWord: values.keyWord,
      pageSize: size,
      pageNumber: 1
    });
  };

  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 (typeof text === 'string' && text.indexOf('$') !== -1) {
                const re = /(.*)(\$(.+)\$)(.*)/;
                const textGroup = text.match(re);
                text = (
                  <p>
                    {textGroup[1] !== '(' ? textGroup[1] : ''}
                    <span style={{ color: '#FFB800' }}>{textGroup[3]}</span>
                    {textGroup[1] !== '(' ? textGroup[4] : ''}
                  </p>
                );
              }
              if (v.width >= 300) {
                return (
                  <Popover
                    content={
                      <span
                        style={{
                          whiteSpace: 'normal',
                          width: '300px',
                          display: 'inline-block',
                          padding: '10px'
                        }}
                      >
                        {text}
                      </span>
                    }
                    placement="rightTop"
                  >
                    <div
                      style={{
                        maxWidth: '300px',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        overflow: 'hidden',
                        marginTop: '8px',
                        marginBottom: '8px'
                      }}
                    >
                      {text}
                    </div>
                  </Popover>
                );
              } else {
                if (v.key === 'operation') {
                  if (record.restDays !== 0) {
                    return <div style={{ width: 40 }} />;
                  } else {
                    return (
                      <div style={{ width: 40 }}>
                        <a
                          onClick={() =>
                            this.openDetail(
                              record.perId,
                              record.attendGroupId,
                              record.attendDate,
                              record.name,
                              record.departName,
                              record.attendGroupName
                            )
                          }
                        >
                          修改
                        </a>
                      </div>
                    );
                  }
                } else if (v.key === 'perId') {
                  return <p>{(this.props.dayStatisticsData.pagination.pageNumber - 1) * this.props.dayStatisticsData.pagination.pageSize + index + 1}</p>;
                } else if (v.key === 'attendResult') {
                  if (
                    text === '正常' ||
                    text === '驻勤打卡' ||
                    text === '未下班'
                  ) {
                    return <p>{text}</p>;
                  } else if (text === '请假' || text === '已补卡') {
                    return (
                      <Popconfirm
                        overlayClassName="change-clock-pop do-not-sow"
                        title={
                          <div>
                            <h4>修改打卡结果</h4>
                            <p style={{ marginBottom: 0 }}>
                              审批单号：{record.approveApplyId}
                            </p>
                          </div>
                        }
                        okText="确定"
                        cancelText="取消"
                        icon={null}
                      >
                        <a href="#">{text}</a>
                      </Popconfirm>
                    );
                  } else if (
                    record.attendRecordTurn &&
                    record.attendRecordTurn.indexOf('上班') !== -1
                  ) {
                    if (text === '漏卡' || text === '迟到') {
                      return (
                        <Popconfirm
                          overlayClassName="change-clock-pop"
                          title={
                            <div>
                              <h4>修改打卡结果</h4>
                              <RadioGroup
                                onChange={this.onChange}
                                value={this.state.attendStatus}
                                style={{ marginRight: 0 }}
                              >
                                <Radio value={1}>正常</Radio>
                                <Radio value={2} style={{ paddingRight: 0 }}>
                                  迟到
                                  <Input
                                    disabled={this.state.disableMinute}
                                    value={this.state.minute}
                                    placeholder=""
                                    type="number"
                                    style={{ width: 60, margin: '0 2px' }}
                                    size="small"
                                    onChange={this.handleInput}
                                    min="1"
                                    max="120"
                                    step="1"
                                  />
                                  分钟
                                </Radio>
                              </RadioGroup>
                            </div>
                          }
                          onConfirm={() => this.submitRecordDetail(record)}
                          onCancel={this.concelRecordDetail}
                          okText="确定"
                          cancelText="取消"
                          icon={null}
                        >
                          <a href="#">{text}</a>
                        </Popconfirm>
                      );
                    }
                  } else if (
                    record.attendRecordTurn &&
                    record.attendRecordTurn.indexOf('下班') !== -1
                  ) {
                    if (text === '漏卡' || text === '早退') {
                      return (
                        <Popconfirm
                          overlayClassName="change-clock-pop"
                          title={
                            <div>
                              <h4>修改打卡结果</h4>
                              <RadioGroup
                                onChange={this.onChange}
                                value={this.state.attendStatus}
                              >
                                <Radio value={1}>正常</Radio>
                                <Radio value={3} style={{ paddingRight: 0 }}>
                                  早退
                                  <Input
                                    disabled={this.state.disableMinute}
                                    value={this.state.minute}
                                    placeholder=""
                                    type="number"
                                    style={{ width: 60, margin: '0 2px' }}
                                    size="small"
                                    onChange={this.handleInput}
                                  />
                                  分钟
                                </Radio>
                              </RadioGroup>
                            </div>
                          }
                          onConfirm={() => this.submitRecordDetail(record)}
                          onCancel={this.concelRecordDetail}
                          okText="确定"
                          cancelText="取消"
                          icon={null}
                        >
                          <a href="#">{text}</a>
                        </Popconfirm>
                      );
                    }
                  }
                } else {
                  return <div>{text}</div>;
                }
              }
            }
      };
    });
  };

  onDepartmentChange = (value, label, extra) => extra.triggerValue;

  handleSearch = e => {
    e.preventDefault();
    this.props.form.validateFields((err, fieldsValue) => {
      if (!err) {
        const rangeValue = fieldsValue['dateRange'];
        const keyWord = fieldsValue['keyWord'];
        if (!rangeValue.length) {
          message.warning('请选择内勤日期！');
          return;
        }
        if (keyWord && keyWord.length < 2) {
          message.warning('搜索内容长度需要2个及以上字符！');
          return;
        }

        const startTime = moment(rangeValue[0]);
        const endTime = moment(rangeValue[1]);
        const during = endTime.diff(startTime, 'days');
        if (during >= 7) {
          message.warning('开始日期和结束日期的间隔需要在七天以内！');
          this.props.form.setFieldsValue({
            dateRange: []
          });
          return;
        }

        const values = {
          ...fieldsValue,
          dateRange: [
            rangeValue[0].format('YYYY-MM-DD'),
            rangeValue[1].format('YYYY-MM-DD')
          ]
        };
        this.props.getdayStatisticsData({
          startDate: values.dateRange[0],
          endDate: values.dateRange[1],
          departId: values.department,
          keyWord: values.keyWord,
          pageSize: this.props.dayStatisticsData.pagination.pageSize,
          pageNumber: 1
        });
      }
    });
  };

  handleReset = () => {
    this.props.form.resetFields();
  };

  openDetail = (
    perId,
    attendGroupId,
    attendDate,
    name,
    departName,
    attendGroupName
  ) => {
    this.props.getAttendRecordDetail({
      perId,
      attendGroupId,
      attendDate,
      name,
      departName,
      attendGroupName
    });
    this.setState({
      openDetailModal: true
    });
  };

  handleCancel = () => {
    this.setState({
      openDetailModal: false
    });
    let values = this.props.form.getFieldsValue();
    values = {
      ...values,
      dateRange: [
        values.dateRange[0].format('YYYY-MM-DD'),
        values.dateRange[1].format('YYYY-MM-DD')
      ]
    };
    this.props.getdayStatisticsData({
      startDate: values.dateRange[0],
      endDate: values.dateRange[1],
      departId: values.department,
      keyWord: values.keyWord,
      pageSize: this.props.dayStatisticsData.pagination.pageSize,
      pageNumber: this.props.dayStatisticsData.pagination.pageNumber
    });
  };

  onChange = e => {
    if (e.target.value === 1) {
      this.setState({
        minute: null,
        disableMinute: true
      });
    } else if (e.target.value === 2 || e.target.value === 3) {
      this.setState({
        disableMinute: false
      });
    }
    this.setState({
      attendStatus: e.target.value
    });
  };

  submitRecordDetail = record => {
    if (this.state.attendStatus === 0) {
      message.warning('请选择具体的修改方案！');
      return;
    }
    if (this.state.attendStatus === 2 || this.state.attendStatus === 3) {
      if (this.state.minute <= 0) {
        message.warning('时间需要大于0！');
        this.setState({
          minute: null,
          attendStatus: 0,
          disableMinute: true
        });
        return;
      }
      if (this.state.minute > 120) {
        message.warning('时间需要小于120！');
        this.setState({
          minute: null,
          attendStatus: 0,
          disableMinute: true
        });
        return;
      }
      if (!Number.isInteger(this.state.minute)) {
        message.warning('时间需要为正整数！');
        this.setState({
          minute: null,
          attendStatus: 0,
          disableMinute: true
        });
        return;
      }
    }
    const {
      perId,
      attendDate,
      attendGroupId
    } = this.props.detailData.personalInfo;
    this.props.changeRecordDetail({
      attendCardRecordId: record.attendCardRecordId,
      perId,
      attendGroupId,
      attendDate,
      commutRound: record.commutRound,
      clockInType: record.clockInType,
      attendStatus: this.state.attendStatus,
      minute: this.state.minute || 0
    });
    this.setState({
      minute: null,
      attendStatus: 0,
      disableMinute: true
    });
  };

  concelRecordDetail = () => {
    this.setState({
      minute: null,
      attendStatus: 0,
      disableMinute: true
    });
  };

  disabledDate(current) {
    // Can not select days before today and today
    return current && current > moment(parseInt(sessionStorage.getItem('requestDate'))).endOf('day');
  }

  handleInput = e => {
    this.setState({
      minute: Number(e.target.value)
    });
  };

  componentDidMount() {
    // this.props.getdayStatisticsData({
    //   startDate: this.state.dateRange[0].format('YYYY-MM-DD'),
    //   endDate: this.state.dateRange[1].format('YYYY-MM-DD'),
    //   departId: '',
    //   keyWord: '',
    //   pageSize: '10',
    //   pageNumber: 1
    // });
    this.props.getDepartMentData();
  }

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

  render() {
    const dataSource = this.props.dayStatisticsData.data;
    const columns = this.renderColumns(this.props.dayStatisticsData.columns);
    const detailcolumns = this.renderColumns(detailColumns);
    const { getFieldDecorator } = this.props.form;
    const treeData = this.props.departmentData;
    const dataSourceDetail = this.props.detailData.data;
    const tProps = {
      treeData,
      // showSearch: true,
      // onChange: this.onDepartmentChange,
      placeholder: '请选择部门',
      style: {
        width: 300
      },
      dropdownStyle: {
        maxHeight: 400,
        overflow: 'auto'
      },
      treeDefaultExpandAll: true
    };

    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 }}>
                    查询：内勤日期仅支持最多一次性查询7天的数据，最多查询前6个月及本月的数据，若您需要更多的内勤数据，请联系在线客服获取。
                  </p>
                </div>
              }
              type="warning"
              showIcon
            />
            <Form className="operation-area" onSubmit={this.handleSearch}>
              <FormItem label="内勤日期">
                {getFieldDecorator('dateRange', {
                  initialValue: [
                    // moment(
                    //   moment().year() +
                    //     '-' +
                    //     (moment().month() + 1 + '-' + moment().date()),
                    //   dateFormat
                    // ),
                    // moment(
                    //   moment().year() +
                    //     '-' +
                    //     (moment().month() + 1) +
                    //     '-' +
                    //     (moment().date()),
                    //   dateFormat
                    // )
                  ],
                  rules: [{ required: true, message: '请选择内勤日期' }]
                })(
                  <RangePicker
                    format={dateFormat}
                    disabledDate={this.disabledDate}
                  />
                )}
              </FormItem>
              <FormItem label="部门">
                {getFieldDecorator('department', {
                  getValueFromEvent: this.onDepartmentChange
                })(<TreeSelect {...tProps} />)}
              </FormItem>
              <FormItem label="关键词">
                {getFieldDecorator('keyWord')(
                  <Input
                    placeholder="请输入姓名/手机号码"
                    style={{ width: 300 }}
                  />
                )}
              </FormItem>
              <FormItem>
                <div className="operation-item">
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                    重置
                  </Button>
                </div>
              </FormItem>
            </Form>
            <div className="table-area">
              <Table
                // rowKey={record => record.perId} 需要一个唯一的key，未发现唯一值，如果必要可以自己创建一个
                dataSource={dataSource}
                columns={columns}
                // scroll={{ x: '100%' }}
                bordered
                size="small"
                pagination={{
                  current: this.props.dayStatisticsData.pagination.pageNumber,
                  total: this.props.dayStatisticsData.pagination.total,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  onChange: this.handlePage,
                  onShowSizeChange: this.handlePageSize
                }}
              />
            </div>
          </TabPane>
        </Tabs>
        <Modal
          title={`${this.props.detailData.personalInfo.name} ${
            this.props.detailData.personalInfo.attendDate
          }`}
          visible={this.state.openDetailModal}
          footer={false}
          onCancel={this.handleCancel}
          className="work-clock"
          width={800}
        >
          <div className="personal-info">
            <img
              src={
                this.props.detailData.avatar
                  ? this.props.detailData.avatar
                  : require('../../assets/images/avatar.png')
              }
              alt="打卡人头像"
              width={50}
              height={50}
              style={{ borderRadius: '50%' }}
            />
            <div className="name-job">
              <p>
                {this.props.detailData.personalInfo.name}
                {this.props.detailData.personalInfo.departName !== ''
                  ? `（
                ${this.props.detailData.personalInfo.departName}）`
                  : ''}
              </p>
              <p>{this.props.detailData.personalInfo.attendGroupName}</p>
            </div>
          </div>
          <div className="work-table">
            <Table
              rowKey={record => record.attendRecordTurn}
              dataSource={dataSourceDetail}
              columns={detailcolumns}
              bordered
              size="small"
              pagination={false}
            />
          </div>
        </Modal>
      </div>
    );
  }
}
