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

const { RangePicker } = DatePicker;

function Finance(props) {
  const { dispatch, loading, finance, userList } = props;
  const [form] = Form.useForm();
  const [modalFilter, setModalFilter] = useState({});

  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: '资源名称', dataIndex: 'c_name' },
    { title: '资源编号', dataIndex: 'user_name' },
    { title: '资源归属部门', dataIndex: 'dep_name' },
    { title: '项目名称', dataIndex: 'project_name' },
    { title: '项目编号', dataIndex: 'project_code' },
    { title: '项目状态', dataIndex: 'project_status' },
    { title: '项目归属部门', dataIndex: 'project_dep_name' },
    { title: '有效工时', dataIndex: 'workload' },
    { title: '工时类型', dataIndex: 'type_name' },
  ];

  const STATUS = [
    { value: 0, label: '售前' },
    { value: 1, label: '转执行' },
    { value: 2, label: '转运营' },
    { value: 3, label: '转质保' },
  ];

  const filterRef = useRef({ pageSize: 20 });

  const onChangePage = (pagination) => {
    dispatch({
      type: 'report/queryFinanceReport',
      payload: {
        ...filterRef.current,
        currentPage: pagination.current,
      },
    });
  };
  const handleSearch = () => {
    const { time, user_id, project_name, project_status } =
      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;
    filterRef.current.user_id = user_id;
    filterRef.current.project_name = project_name;
    filterRef.current.project_status = project_status;

    dispatch({
      type: 'report/queryFinanceReport',
      payload: {
        ...filterRef.current,
      },
    });
  };
  const handleDownload = () => {
    const token = getToken();
    const s_time = filterRef.current?.s_time || '';
    const e_time = filterRef.current?.e_time || '';
    const user_id = filterRef.current?.user_id || '';
    const project_name = filterRef.current?.project_name || '';
    const project_status = filterRef.current?.project_status || '';
    downloadFile(
      `/api/v2/workload/finance/export2excel?JWT-TOKEN=${token}&s_time=${s_time}&e_time=${e_time}&user_id=${user_id}&project_name=${project_name}&project_status${project_status}`,
      `财务报表${dayjs().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="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 label="项目名称" name="project_name">
          <Input />
        </Form.Item>
        <Form.Item label="项目状态" name="project_status" initialValue={null}>
          <Select style={{ width: 120 }}>
            <Select.Option value={null}>全部</Select.Option>
            {STATUS.map((item) => (
              <Select.Option key={item.value}>{item.label}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" loading={loading} onClick={handleSearch}>
            查询
          </Button>
        </Form.Item>
      </Form>
    );
  };
  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={(record) =>
          `${record.user_name}-${record.project_code}-${record.type_name}`
        }
        columns={columns}
        dataSource={finance.list}
        pagination={finance.pagination}
        onChange={onChangePage}
      />
    </div>
  );
}

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