import React, { useState, useEffect, useRef } from 'react';
import {
  message,
  InputNumber,
  Table,
  Divider,
  Modal,
  Button,
  Input,
  Row,
  Col,
  Calendar,
  Spin,
} from 'antd';
// import SearchForm from './SearchForm';
import RejectModal from './RejectModal';
import AuthWorkList from './AuthWorkList';
import { connect } from 'dva';
import styles from './index.less';
import dayjs from 'dayjs';
import { useRequest, useModel } from '@umijs/max';

function List(props) {
  const {
    initialState: { user },
  } = useModel('@@initialState');
  const { dispatch, loading, list, project, userList, allType } = props;
  const [visible, setVisible] = useState(false);
  const [filter, setFilter] = useState({});
  const [current, setCurrent] = useState({
    date: dayjs(),
    list: [],
  });

  const rejectRef = useRef({});

  const onAgree = (records) => {
    Modal.confirm({
      title: '提示',
      content: '是否确认通过审批?',
      okText: '通过',
      cancelText: '取消',
      onOk() {
        let params = records.map((item) => ({
          id: item.id,
          status: 2,
          desc: '',
        }));
        let time = current.date.format('YYYY-MM-DD');
        dispatch({
          type: 'workload/authWorkload',
          payload: params,
          callback: (list) => {
            setCurrent({
              ...current,
              list: list.filter((item) => item.time == time),
            });
          },
        });
      },
    });
  };
  const onReject = (data) => {
    let items = rejectRef.current;
    let params = items.map((item) => ({
      id: item.id,
      ts: item.ts,
      user_id: item.User.ID,
      workload: item.workload,
      status: 3,
      desc: data.desc || '',
    }));
    let time = current.date.format('YYYY-MM-DD');
    dispatch({
      type: 'workload/authWorkload',
      payload: params,
      callback: (list) => {
        setVisible(false);
        setCurrent({
          ...current,
          list: list.filter((item) => item.time == time),
        });
      },
    });
  };
  const dateCellRender = (value) => {
    let current = value.format('YYYY-MM-DD');
    let timeList = list.filter((item) => item.time == current);
    let total = timeList.reduce((total, item) => {
      if (item.audit_state != 1) return total;
      return total + item.workload;
    }, 0);
    if (timeList.length == 0 || total == 0) return;

    return <span style={{ color: '#1890ff' }}>{total} 小时</span>;
  };

  const onChangeDate = (value) => {
    let time = value.format('YYYY-MM-DD');
    if (current.date.format('YYYY-MM') != value.format('YYYY-MM')) {
      const s_date = value.format('YYYY-MM') + '-01';
      const e_date = dayjs(s_date)
        .add(1, 'month')
        .add(-1, 'days')
        .format('YYYY-MM-DD');
      dispatch({
        type: 'workload/queryAuthWorkHours',
        payload: {
          pageSize: 9999,
          s_time: s_date + ' 00:00:00',
          e_time: e_date + ' 23:59:59',
        },
        callback: (list) => {
          setCurrent({
            date: value,
            list: list.filter((item) => item.time == time),
          });
        },
      });
    } else {
      setCurrent({
        date: value,
        list: list.filter((item) => item.time == time),
      });
    }
  };

  const getList = () => {
    return current.list.filter((item) => {
      if (filter.userId && item.User.ID != filter.userId) return false;
      if (filter.projectId && item.project_id != filter.projectId) return false;

      return true;
    });
  };

  useEffect(() => {
    if (!user.ID) return;
    // 查询分类以及工时
    dispatch({
      type: 'workload/queryWorkType',
      callback: () => {
        const s_date = current.date.format('YYYY-MM') + '-01';
        const e_date = dayjs(s_date)
          .add(1, 'month')
          .add(-1, 'days')
          .format('YYYY-MM-DD');
        dispatch({
          type: 'workload/queryAuthWorkHours',
          payload: {
            pageSize: 9999,
            s_time: s_date + ' 00:00:00',
            e_time: e_date + ' 23:59:59',
          },
          callback: (list) => {
            let time = current.date.format('YYYY-MM-DD');
            setCurrent({
              ...current,
              list: list.filter((item) => item.time == time),
            });
          },
        });
      },
    });

    // 查询项目列表
    dispatch({
      type: 'workload/queryProject',
    });
    dispatch({
      type: 'user/fetch',
    });
    return () => {
      // 清空查询数据
      dispatch({
        type: 'workload/save',
        payload: {
          filter: {},
          list: [],
        },
      });
    };
  }, [user.ID]);

  // useEffect(() => {
  //   onChangeDate(current.date);
  // }, [list]);

  return (
    <div>
      <Spin spinning={loading}>
        <Row gutter={8}>
          <Col span={12}>
            <Calendar
              value={current.date}
              cellRender={dateCellRender}
              onChange={onChangeDate}
            />
          </Col>
          <Col span={12}>
            <AuthWorkList
              allType={allType}
              project={project}
              list={getList()}
              onAgree={onAgree}
              onSearch={setFilter}
              user={userList}
              onReject={(records) => {
                setVisible(true);
                rejectRef.current = records;
              }}
            />
          </Col>
        </Row>
      </Spin>
      <RejectModal
        visible={visible}
        onOk={onReject}
        onCancel={() => setVisible(false)}
      />
    </div>
  );
}

export default connect(({ workload, user, loading }) => ({
  list: workload.list,
  userList: user.list,
  allType: workload.allType,
  project: workload.project,
  loading: loading.models.workload,
}))(List);
