import React, { useEffect, useState, useRef, useMemo } from 'react';
import { connect } from 'dva';
import { Form, Table, DatePicker, Input, Button, Select, Modal } from 'antd';
import styles from './report.less';
import { downloadFile, getToken } from '@/utils/utils.js';
import { queryFinanceProjDetail } from '@/services/workHours';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

function ProjectTree(props) {
  const { dispatch, loading, projectNew } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [current, setCurrent] = useState(null);
  const [columnsFilter, setColumnsFilter] = useState({
    budget: false,
    dep: false,
  });

  var initDate;
  if (dayjs().date() > 25) {
    initDate = [
      dayjs().subtract(1, 'month').set('date', 26),
      dayjs().set('date', 25),
    ];
  } else {
    initDate = [
      dayjs().subtract(2, 'month').set('date', 26),
      dayjs().subtract(1, 'month').set('date', 25),
    ];
  }

  const columns = useMemo(() => {
    let arr = [
      {
        title: '名称',
        dataIndex: 'name',
        // render: (name, item) => <a onClick={() => handleClick(item)}>{name}</a>,
      },
      {
        title: '本月待审核工时',
        dataIndex: 'month_pending_audit_cnt',
        width: '15%',
      },
      {
        title: '本月已拒绝工时',
        dataIndex: 'month_refuse_audit_cnt',
        width: '15%',
      },
      {
        title: '本月已审核工时',
        dataIndex: 'month_pass_audit_cnt',
        width: '15%',
      },
      { title: '累计有效工时', dataIndex: 'total_workload', width: '15%' },
    ];
    if (columnsFilter.budget) {
      arr.push({
        title: '预算 ',
        dataIndex: 'budget',
        width: '10%',
        render: (_, record) =>
          record.cond?.project_id && record.cond?.status == 0
            ? record.budget === null
              ? '未设置'
              : record.budget
            : null,
      });
    }
    // if (columnsFilter.dep) {
    //   arr.splice(1, 0, { title: '所属部门', dataIndex: 'dep_name', width: '15%' });
    // }
    return arr;
  }, [columnsFilter]);

  const filterRef = useRef({});
  const cacheRef = useRef({});
  const onChangePage = (pagination) => {
    dispatch({
      type: 'report/queryProjectReportNew',
      payload: {
        ...filterRef.current,
        currentPage: pagination.current,
      },
    });
  };
  const handleSearch = () => {
    const { time } = form.getFieldsValue();
    filterRef.current.s_time = time[0]
      ? dayjs(time[0]).format('YYYY-MM-DD')
      : null;
    filterRef.current.e_time = time[1]
      ? dayjs(time[1]).format('YYYY-MM-DD')
      : null;

    dispatch({
      type: 'report/queryProjectReportNew',
      payload: {
        ...filterRef.current,
      },
    });
  };

  const handleClick = (item) => {
    setCurrent({
      s_time: filterRef.current.s_time,
      e_time: filterRef.current.e_time,
      project_id: item.project_id,
    });
    setVisible(true);
  };

  const onExpand = (expanded, record) => {
    // 加入缓存
    cacheRef.current[record.key] = record;
  };
  const onExpandedRowsChange = (expandedRows) => {
    let budget = false,
      dep = false;
    // 根据表格当前展开项决定是否显示预算和部门
    const fn = (data) => {
      data.forEach((record) => {
        // 判断是否展开
        if (expandedRows.includes(record.key)) {
          // 执行项目被展开则显示预算
          if (record.cond.status == 0) {
            budget = true;
          }
          // 子集含有部门则显示部门列
          if (record.child[0]?.dep_name) {
            dep = true;
          }
          if (record.child) fn(record.child);
        }
      });
    };
    fn(projectNew);

    setColumnsFilter({ budget, dep });
  };

  const renderSearch = () => {
    return (
      <Form layout="inline" form={form}>
        <Form.Item label="时间" name="time" initialValue={initDate}>
          <RangePicker placeholder="选择时间" allowClear={false} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" loading={loading} onClick={handleSearch}>
            查询
          </Button>
        </Form.Item>
      </Form>
    );
  };
  useEffect(() => {
    handleSearch();
  }, []);

  return (
    <div>
      <div className={styles.topPart}>{renderSearch()}</div>
      <Table
        loading={loading}
        style={{ marginTop: 20 }}
        rowKey={`key`}
        columns={columns}
        dataSource={projectNew}
        expandable={{
          childrenColumnName: 'child',
          onExpand,
          onExpandedRowsChange,
        }}
        // pagination={projectNew.pagination}
        // onChange={onChangePage}
        pagination={false}
      />
      <ProjectTreeModal
        data={current}
        visible={visible}
        onCancel={() => setVisible(false)}
      />
    </div>
  );
}

function ProjectTreeModal(props) {
  const { visible, data, onCancel } = props;
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);
  const columns = [
    { title: '项目名称', dataIndex: 'name' },
    { title: '项目编号', dataIndex: 'name' },
    { title: '分项工作代码', dataIndex: 'name' },
    { title: '本月人日数', dataIndex: 'name' },
    { title: '累计人日数', dataIndex: 'name' },
    { title: '项目预算人日 ', dataIndex: 'name' },
  ];

  const queryList = async () => {
    setLoading(true);
    let res = await queryFinanceProjDetail(data);
    if (res) {
      setList(res.data);
    }
    setLoading(false);
  };
  useEffect(() => {
    if (visible && data) {
      queryList();
    }
    if (!visible) {
      setList([]);
    }
  }, [visible, data]);

  return (
    <Modal
      title="项目详情"
      width="80%"
      open={visible}
      onCancel={onCancel}
      footer={false}
      destroyOnClose
    >
      <Table
        columns={columns}
        loading={loading}
        dataSource={list}
        rowKey="project_name"
      ></Table>
    </Modal>
  );
}

export default connect(({ report, loading }) => ({
  projectNew: report.projectNew,
  loading: loading.models.report,
}))(ProjectTree);
