import React, { useState, useEffect, useRef } from 'react';
import {
  Modal,
  Button,
  Calendar,
  Popover,
  Spin,
  Row,
  Col,
  message,
} from 'antd';
import AddModal from './AddModal';
import WorkList from './WorkList';
import { connect } from 'dva';
import dayjs from 'dayjs';
import { useRequest, useModel } from '@umijs/max';

function List(props) {
  const {
    typeList,
    dispatch,
    loading,
    dataList,
    projectList,
    // currentUser,
    allType,
    depUserTree,
    depUserMap,
  } = props;
  const {
    initialState: { user },
  } = useModel('@@initialState');
  const [visible, setVisible] = useState(false);
  const [current, setCurrent] = useState({
    date: dayjs(),
    list: [],
  });

  const onAuth = (item, workload) => {
    if (workload == 0) return message.error('请上报有效工时');
    Modal.confirm({
      title: '提示',
      content: '是否上报审批?',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        console.log(item);
        let params = [
          {
            type_id: Number(item.type_id),
            // 父级id
            parent_type_id: allType[item.type_id].parent_id,
            data: [
              {
                id: item.id,
                project_id: item.project_id,
                workload: workload,
                day: item.time,
                pay_dep_id: item.pay_dep_id,
              },
            ],
          },
        ];
        dispatch({
          type: 'workload/addAuthWorkHours',
          payload: params,
          callback: (list) => {
            let time = current.date.format('YYYY-MM-DD');
            setCurrent({
              ...current,
              list: list.filter((item) => item.time == time),
            });
          },
        });
      },
    });
  };

  const MultiAuth = () => {
    Modal.confirm({
      title: '提示',
      content: '是否上报全部审批?',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        let params = [];
        debugger;
        for (let i = 0; i < dataList.length; i++) {
          const element = dataList[i];
          if (element.audit_state != 0) continue;
          var arr = params.find((arr) => arr.type_id == element.type_id);
          if (arr) {
            console.log(arr);
            arr.parent_type_id = allType[element.type_id].parent_id;
            arr.data.push({
              id: element.id,
              project_id: element.project_id,
              workload: element.workload,
              day: element.time,
              pay_dep_id: element.pay_dep_id,
            });
          } else {
            let data = [];
            data.push({
              id: element.id,
              project_id: element.project_id,
              workload: element.workload,
              day: element.time,
              pay_dep_id: element.pay_dep_id,
            });
            params.push({
              type_id: Number(element.type_id),
              // 父级id
              parent_type_id: allType[element.type_id].parent_id,
              data: data,
            });
          }
        }
        console.log(params);
        dispatch({
          type: 'workload/addAuthWorkHours',
          payload: params,
        });
      },
    });
  };

  const currentDayAuth = () => {
    var list = current.list;
    Modal.confirm({
      title: '提示',
      content: '是否上报本日审批?',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        let params = [];
        for (let i = 0; i < list.length; i++) {
          const element = list[i];
          if (element.audit_state != 0) continue;
          var arr = params.find((arr) => arr.type_id == element.type_id);
          if (arr) {
            console.log(arr);
            arr.parent_type_id = allType[element.type_id].parent_id;
            arr.data.push({
              id: element.id,
              project_id: element.project_id,
              workload: element.workload,
              day: element.time,
              pay_dep_id: element.pay_dep_id,
            });
          } else {
            let data = [];
            data.push({
              id: element.id,
              project_id: element.project_id,
              workload: element.workload,
              day: element.time,
              pay_dep_id: element.pay_dep_id,
            });
            params.push({
              type_id: Number(element.type_id),
              // 父级id
              parent_type_id: allType[element.type_id].parent_id,
              data: data,
            });
          }
        }
        console.log(params);
        dispatch({
          type: 'workload/addAuthWorkHours',
          payload: params,
        });
      },
    });
  };

  const onSave = (item, workload) => {
    let params = [
      {
        type_id: Number(item.type_id),
        comment: '',
        // 父级id
        parent_type_id: allType[item.type_id].parent_id,
        data: [
          {
            id: item.id,
            project_id: Number(item.project_id),
            workload: workload,
            day: item.time,
            pay_dep_id: item.pay_dep_id,
          },
        ],
      },
    ];

    dispatch({
      type: 'workload/addWorkHours',
      payload: params,
      callback: (list) => {
        let time = current.date.format('YYYY-MM-DD');
        setCurrent({
          ...current,
          list: list.filter((item) => item.time == time),
        });
      },
    });
  };

  const onDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除工时?',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'workload/deleteWorkHour',
          payload: { id: item.id },
          callback: (list) => {
            let time = current.date.format('YYYY-MM-DD');
            setCurrent({
              ...current,
              list: list.filter((item) => item.time == time),
            });
          },
        });
      },
    });
  };

  const onAddWork = (data) => {
    dispatch({
      type: 'workload/addWorkHours',
      payload: data,
      callback: (list) => {
        setVisible(false);
        let time = current.date.format('YYYY-MM-DD');
        setCurrent({
          ...current,
          list: list.filter((item) => item.time == time),
        });
      },
    });
  };

  const dateCellRender = (value, info) => {
    let current = value.format('YYYY-MM-DD');
    // console.log(value);
    let list = dataList.filter(
      (item) => item.time == current && item.status == 0,
    );
    // let total = list.reduce((total, item) => total + item.workload, 0);
    let waitTotal = 0,
      successTotal = 0;
    list.forEach((item) => {
      if (item.audit_state == 2) {
        successTotal += item.workload;
      } else {
        waitTotal += item.workload;
      }
    });
    if (list.length == 0) return info.origin;
    let content = (
      <div>
        {list.map((item) => (
          <div key={item.type_id}>
            {getName(item)}-{item.TypeInfo?.name}:{item.workload}小时
          </div>
        ))}
      </div>
    );
    return (
      <Popover content={content}>
        {successTotal !== 0 && <div>已审批: {successTotal}</div>}
        {waitTotal !== 0 && (
          <div style={{ color: '#e43d33' }}>待处理: {waitTotal}</div>
        )}
      </Popover>
    );
  };

  const onChangeDate = (value) => {
    console.log(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/queryWorkHours',
        payload: {
          pageSize: 9999,
          user_id: user.ID,
          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: dataList.filter((item) => item.time == time),
      });
    }
  };

  const getName = (item) => {
    let name;
    if (item.project_id == '0') {
      let pid = allType[item.type_id]?.parent_id;
      if (!pid) return '';
      name = allType[pid].name;
    } else {
      name = item.Project.Name;
    }
    return name;
  };

  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/queryWorkHours',
          payload: {
            pageSize: 9999,
            user_id: user.ID,
            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',
    // });
    return () => {
      // 清空查询数据
      dispatch({
        type: 'workload/save',
        payload: {
          filter: {},
          list: [],
        },
      });
    };
  }, [user.ID]);
  console.log(current.date);

  // useEffect(() => {
  //   onChangeDate(current.date);
  // }, [dataList]);
  useEffect(() => {
    dispatch({
      type: 'workload/fetchDepV2',
    });
  }, []);
  return (
    <div>
      <Spin spinning={loading}>
        <Row gutter={8}>
          <Col span={10}>
            <Calendar
              // value={current.date}
              // cellRender={dateCellRender}
              onChange={onChangeDate}
            />
          </Col>
          <Col span={14}>
            <div>
              <Button
                type="primary"
                style={{ marginBottom: 20 }}
                onClick={() => setVisible(true)}
              >
                新增
              </Button>
              <Button
                type="primary"
                style={{ marginBottom: 20, marginLeft: 20 }}
                onClick={() => MultiAuth()}
              >
                上报所有工时
              </Button>
              {current.list.length > 0 && (
                <Button
                  type="primary"
                  style={{ marginBottom: 20, marginLeft: 20, float: 'right' }}
                  onClick={() => currentDayAuth()}
                >
                  上报今日工时
                </Button>
              )}
            </div>

            <WorkList
              allType={allType}
              list={current.list}
              onAuth={onAuth}
              onSave={onSave}
              onDelete={onDelete}
              depUserMap={depUserMap}
            />
          </Col>
        </Row>
      </Spin>

      <AddModal
        typeList={typeList}
        visible={visible}
        onOk={onAddWork}
        time={current.date?.format('YYYY-MM-DD')}
        onCancel={() => setVisible(false)}
        depUserTree={depUserTree}
      />
    </div>
  );
}

export default connect(({ workload, user, loading }) => ({
  dataList: workload.dataList,
  typeList: workload.typeList,
  allType: workload.allType,
  // currentUser: user.currentUser,
  loading: loading.models.workload,
  depUserTree: workload.depUserTree,
  depUserMap: workload.depUserMap,
}))(List);
