import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import {
  Form,
  Table,
  DatePicker,
  Input,
  Button,
  Select,
  Modal,
  Popover,
} from 'antd';
import { ProfileOutlined } from '@ant-design/icons';
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 FinanceProject(props) {
  const { dispatch, loading, project, userList } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [current, setCurrent] = useState(null);

  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 = [
    // {
    //   title: '序号',
    //   render: (_, __, index) => {
    //     const { current, pageSize } = project.pagination;
    //     return (current - 1) * pageSize + index + 1;
    //   },
    // },
    {
      title: '项目名称',
      dataIndex: 'name',
      render: (name, item) => <a onClick={() => handleClick(item)}>{name}</a>,
    },
    { title: '项目编号', dataIndex: 'code' },
    {
      title: (
        <div>
          本月人日数
          <Popover
            content={
              <div>
                本月人日数为上一个工时周期(前月26日至当月25日)内的工时数,
                <br />
                与选取时间无关
              </div>
            }
          >
            <ProfileOutlined style={{ color: 'rgba(0,0,0,0.4)' }} />
          </Popover>
        </div>
      ),
      dataIndex: 'month_workload',
    },
    {
      title: (
        <div>
          总人日数
          <Popover content={<div>选取时间内的总工时数</div>}>
            <ProfileOutlined style={{ color: 'rgba(0,0,0,0.4)' }} />
          </Popover>
        </div>
      ),
      dataIndex: 'total_workload',
    },
    { title: '项目预算人日 ', dataIndex: 'budget' },
  ];

  const filterRef = useRef({ pageSize: 20 });
  const onChangePage = (pagination) => {
    dispatch({
      type: 'finance/queryFinanceProjReport',
      payload: {
        ...filterRef.current,
        currentPage: pagination.current,
      },
    });
  };
  const handleSearch = () => {
    const { time, user_id } = form.getFieldsValue();
    filterRef.current.s_time = time[0]
      ? dayjs(time[0]).format('YYYY-MM-DD')
      : '';
    filterRef.current.e_time = time[1]
      ? dayjs(time[1]).format('YYYY-MM-DD')
      : '';
    filterRef.current.user_id = user_id || '';

    dispatch({
      type: 'finance/queryFinanceProjReport',
      payload: {
        ...filterRef.current,
      },
    });
  };

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

  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="user_id">
          <Select
            options={userList}
            fieldNames={{ label: 'CName', value: 'ID' }}
            style={{ width: 150 }}
            showSearch
            filterOption={(inputValue, option) =>
              option.CName.includes(inputValue)
            }
            allowClear
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" loading={loading} onClick={handleSearch}>
            查询
          </Button>
        </Form.Item>
      </Form>
    );
  };

  const handleDownload = () => {
    const token = getToken();
    const { user_id, time } = form.getFieldsValue();
    let s_time = time[0] ? dayjs(time[0]).format('YYYY-MM-DD') : '';
    let e_time = time[1] ? dayjs(time[1]).format('YYYY-MM-DD') : '';

    downloadFile(
      `/api/v2/workload/finance/exe/export?JWT-TOKEN=${token}&s_time=${s_time}&e_time=${e_time}&user_id=${
        user_id || ''
      }`,
      `财务报表_项目${dayjs().format('YYYYMMDDHHMMSS')}.xlsx`,
    );
  };

  useEffect(() => {
    handleSearch();
    if (!userList.length > 0) dispatch({ type: 'user/fetch' });
  }, []);

  return (
    <div>
      <div className={styles.topPart}>
        {renderSearch()}
        <Button type="primary" onClick={handleDownload}>
          导出
        </Button>
      </div>
      <Table
        loading={loading}
        style={{ marginTop: 20 }}
        rowKey={`code`}
        columns={columns}
        dataSource={project.list}
        pagination={project.pagination}
        onChange={onChangePage}
      />
      <FinanceProjectModal
        data={current}
        visible={visible}
        onCancel={() => setVisible(false)}
      />
    </div>
  );
}

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

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

  return (
    <Modal
      title={data ? `${data.project_name}【${data.project_code}】` : '详情'}
      width="80%"
      visible={visible}
      onCancel={onCancel}
      footer={false}
      destroyOnClose
    >
      <Table
        columns={columns}
        loading={loading}
        dataSource={list}
        rowKey="name"
      ></Table>
    </Modal>
  );
}

export default connect(({ finance, user, loading }) => ({
  project: finance.project,
  userList: user.list,
  loading: loading.models.finance,
}))(FinanceProject);
