import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import { Form, Table, DatePicker, Input, Button, Select, message, Popover } from 'antd';
import report from './models/report';
import styles from './report.less';
import moment from 'moment';
import UserProjectRptModal from './UserProjectRptModal';
import { downloadFile, getToken } from '@/utils/utils.js';

const { Option } = Select;
const { RangePicker } = DatePicker;
const initDate = [moment().startOf('years'), moment()];

// var currentYear = new Date().getFullYear();
// var yearList = [];
// // 获得过去10年至未来20年的年份列表
// for (var i = currentYear - 10; i < currentYear + 20; i++) {
//   yearList.push(i);
// }

function Resource(props) {
  const { dispatch, loading, project } = props;
  const [form] = Form.useForm();
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [visible, setVisible] = useState(false);
  const [modalFilter, setModalFilter] = useState({});
  const filterRef = useRef({});
  // const onChangePage = pagination => {
  //   dispatch({
  //     type: 'report/queryProjectReport',
  //     payload: {
  //       ...filterRef.current,
  //       currentPage: pagination.current,
  //     },
  //   });
  // };
  const getMonthColumns = () => {
    let arr = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
    var time;
    if (filterRef.current.s_time) {
      time = [moment(filterRef.current.s_time), moment(filterRef.current.e_time)];
    } else {
      time = initDate;
    }
    var date = {};
    let eYear = time[1].year();
    let eMonth = time[1].month();
    let current = moment(time[0]);
    let cYear, cMonth;

    // do {
    //   cYear = current.year();
    //   cMonth = current.month();
    //   if (!date[cYear]) date[cYear] = [];
    //   date[cYear].push(arr[cMonth]);
    //   current.add('month', 1);
    // } while (cYear != eYear || cMonth != eMonth);
    for (let i = 0; i < 12; i++) {
      cYear = current.year();
      cMonth = current.month();
      if (!date[cYear]) date[cYear] = [];
      date[cYear].push(arr[cMonth]);
      current.add('month', 1);
    }
    current.subtract('month', 12);
    let monthColumns = Object.keys(date).map(year => ({
      title: year + '年',
      children: date[year].map(item => {
        let key = current.format('YYYY-MM');
        current.add('month', 1);
        return {
          title: `${item}`,
          render: record => {
            const { month } = record;
            return month.find(item => item.st == key)?.pass_audit_cnt || 0;
            // return month[key]?.total_audit_cnt || 0;
            // return (
            //   <Popover
            //     content={
            //       <>
            //         {`审核通过: ${month[key]?.pass_audit_cnt || 0}`}
            //         <br />
            //         {`审核中: ${month[key]?.pending_audit_cnt || 0}`}
            //         <br />
            //         {`审核拒绝: ${month[key]?.refuse_audit_cnt || 0}`}
            //         <br />
            //         {`未提审: ${month[key]?.refuse_audit_cnt || 0}`}
            //       </>
            //     }
            //   >
            //     {month[key]?.total_audit_cnt || 0}
            //   </Popover>
            // );
            // return `${JSON.stringify(month)}`;
          },
        };
      }),
    }));
    return monthColumns;
  };
  // const onExpand = (expanded, record) => {
  //   if (expanded && !record.isLoad) {
  //     dispatch({
  //       type: 'report/queryProjectReportDetail',
  //       payload: {
  //         ...filterRef.current,
  //         record: record,
  //       },
  //     });
  //   }
  // };

  const handleSearch = () => {
    const { time, project_name } = form.getFieldsValue();
    if (
      !moment(time[0])
        .add(12, 'month')
        .isSameOrAfter(time[1])
    ) {
      message.error('时间间隔超过12个月，请重新选择。');
      return;
    }
    filterRef.current.s_time = time[0] ? moment(time[0]).format('YYYY-MM-DD') : null;
    filterRef.current.e_time = time[1] ? moment(time[1]).format('YYYY-MM-DD') : null;
    dispatch({
      type: 'report/queryProjectReport',
      payload: {
        ...filterRef.current,
        project_name: project_name,
      },
    });
  };
  const handleDownload = () => {
    const s_time = !filterRef.current.s_time ? '' : filterRef.current.s_time;
    const e_time = !filterRef.current.e_time ? '' : filterRef.current.e_time;
    const project_name = form.getFieldValue('project_name');
    const token = getToken();
    downloadFile(
      `/api/v2/workload/rpt/projects/export2excel?JWT-TOKEN=${token}&s_time=${s_time}&e_time=${e_time}&project_name=${
        !project_name ? '' : project_name
      }`,
      `项目报表${moment().format('YYYYMMDDHHMMSS')}.xlsx`
    );
  };
  const renderSearch = () => {
    return (
      <Form layout="inline" form={form}>
        <Form.Item label="时间" name="time" initialValue={initDate}>
          <RangePicker placeholder="选择时间" allowClear={false} />
        </Form.Item>
        <Form.Item label="项目" name="project_name">
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" loading={loading} onClick={handleSearch}>
            查询
          </Button>
        </Form.Item>
      </Form>
    );
  };
  const columns = [
    {
      title: '项目名称',
      render: record =>
        !record.child && record.total_audit_cnt ? (
          <a onClick={() => showUserModal(record)}>{record.name}</a>
        ) : (
          record.name
        ),
    },
    ...getMonthColumns(),
    { title: '总计', dataIndex: 'total_audit_cnt' },
  ];
  // const columns = [
  //   {
  //     title: '项目名称',
  //     render: record =>
  //       !record.isParent ? (
  //         <a onClick={() => showUserModal(record)}>{record.type_name}</a>
  //       ) : (
  //         record.type_name
  //       ),
  //   },
  //   {
  //     title: '分项工作代码',
  //     align: 'center',
  //     dataIndex: 'type_code',
  //   },
  //   // {
  //   //   title: '项目名称',
  //   //   render: record => (record.project_id == 0 ? '' : record.project_name),
  //   // },
  //   // {
  //   //   title: '项目编号',
  //   //   dataIndex: 'project_code',
  //   // },
  //   // {
  //   //   title: '工作内容',
  //   //   dataIndex: 'type_name',
  //   // },
  //   ...getMonthColumns(),
  //   {
  //     title: '总计',
  //     dataIndex: 'month_rpt',
  //     render: arr => (
  //       <Popover
  //         content={
  //           <>
  //             {`审核通过: ${
  //               arr ? arr.reduce((total, item) => total + item.pass_audit_cnt, 0) : ''
  //             }`}
  //             <br />
  //             {`审核中: ${
  //               arr ? arr.reduce((total, item) => total + item.pending_audit_cnt, 0) : ''
  //             }`}
  //             <br />
  //             {`审核拒绝: ${
  //               arr ? arr.reduce((total, item) => total + item.refuse_audit_cnt, 0) : ''
  //             }`}
  //             <br />
  //             {`未提审: ${arr ? arr.reduce((total, item) => total + item.un_audit_cnt, 0) : ''}`}
  //           </>
  //         }
  //       >
  //         {arr ? arr.reduce((total, item) => total + item.total_audit_cnt, 0) : ''}
  //       </Popover>
  //     ),
  //   },
  // ];
  const showUserModal = item => {
    const { s_time, e_time } = filterRef.current;
    setModalFilter({
      s_time: s_time,
      e_time: e_time,
      type_id: item.id,
      project_id: item.project_id,
      flag: item.flag,
    });
    setVisible(true);
  };
  useEffect(() => {
    handleSearch();
  }, []);

  // useEffect(() => {
  //   setExpandedRowKeys(project.list.map(item => item.id));
  // }, [project.list]);

  return (
    <div className={styles.page}>
      <div className={styles.topPart}>
        {renderSearch()}
        <Button type="primary" onClick={handleDownload}>
          导出
        </Button>
      </div>
      <Table
        style={{ marginTop: 20 }}
        columns={columns}
        rowKey="key"
        childrenColumnName="child"
        // onExpand={onExpand}
        dataSource={project}
        pagination={false}
      />
      <UserProjectRptModal
        filter={modalFilter}
        visible={visible}
        onCancel={() => setVisible(false)}
      />
    </div>
  );
}

export default connect(({ report, loading }) => ({
  project: report.project,
  // projectList: report.projectList,
  loading: loading.models.report,
}))(Resource);
