import React, { useState, useEffect } from 'react';
import { InputNumber, Popover, Divider, Table, message } from 'antd';

function WorkList(props) {
  const { list, onAuth, onSave, onDelete, allType, depUserMap } = props;
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  let workHour = {};
  const columns = [
    {
      title: '分类',
      dataIndex: 'type_id',
      width: '20%',
      render: type_id => allType[type_id]?.name,
    },
    {
      title: '所属项目/所属部门',
      width: '30%',
      render: item => {
        if (item.zIndex === 0) return '';
        return item.Project?.Name || depUserMap?.get(item.pay_dep_id)?.Name || '-';
      },
    },
    {
      title: '审核状态',
      width: '15%',
      render: record => renderStatus(record),
    },
    {
      title: '工时',
      width: '15%',
      render: item => {
        if (item.zIndex === 0) {
          return '总计 ' + item.children.reduce((total, item) => total + item.workload, 0) + '小时';
        }
        if (item.audit_state == 1 || item.audit_state == 2) return item?.workload + '小时';
        workHour[`${item.id}`] = item?.workload;
        return (
          <InputNumber
            style={{ width: 60 }}
            min={0}
            step={0.5}
            defaultValue={item?.workload}
            onChange={value => {
              workHour[`${item.id}`] = value;
            }}
          />
        );
      },
    },
    {
      title: '操作',
      width: '20%',
      render: item => {
        if (item.zIndex === 0) return '';
        if (item.audit_state == 2) return;
        if (item.audit_state == 1) return <a onClick={() => handleDelete(item)}>删除</a>;
        return (
          <>
            <a
              onClick={() =>
                onHandleSave(item, workHour[`${item.id}`])
              }
            >
              保存
            </a>
            <Divider type="vertical"></Divider>
            <a
              onClick={() =>
                onAuth(item, workHour[`${item.id}`])
              }
            >
              上报审批
            </a>
            <Divider type="vertical"></Divider>
            <a onClick={() => handleDelete(item)}>删除</a>
          </>
        );
      },
    },
  ];
  const renderStatus = item => {
    if (item.zIndex === 0) return '';
    // auditState  0-未提审 1- 已提交审核，2-审核通过，3-审核拒绝
    switch (item.audit_state) {
      case 0:
        return <span>未提审</span>;
      case 1:
        return <span style={{ color: '#1890ff' }}>待审核</span>;
      case 2:
        return <span style={{ color: '#a0d911' }}>审核通过</span>;
      case 3:
        return (
          <Popover content={`拒绝原因: ${item.audit_desc}`}>
            <span style={{ color: '#f5222d' }}>审核拒绝</span>
          </Popover>
        );
      default:
        return '';
    }
  };

  const onHandleSave = (item, data) => {
    let currentWorkload = list
      .filter(item => item.status == 0)
      .reduce((total, temp) => {
        if (temp.id == item.id) return total;
        return total + temp.workload;
      }, 0);
    if (data + currentWorkload > 8) return message.error('每日工时不能超过8小时！');
    onSave(item, data);
  };

  const handleDelete = item => {
    onDelete(item);
  };

  const getList = () => {
    let data = {},
      expandedRowKeys = [];
    list
      .filter(item => item.status == 0)
      .forEach(item => {
        let pid = allType[item.type_id]?.parent_id;
        expandedRowKeys.push(pid);
        if (!data[pid]) data[pid] = [];
        data[pid].push(item);
      });
    let dataSource = Object.keys(data).map(pid => ({
      zIndex: 0,
      id: allType[pid]?.id,
      type_id: allType[pid]?.id,
      children: data[pid],
    }));

    setDataSource(dataSource);
    setExpandedRowKeys([...new Set(expandedRowKeys)]);
  };

  useEffect(() => {
    getList();
  }, [list]);

  return (
    <div>
      <Table
        expandedRowKeys={expandedRowKeys}
        rowKey="id"
        columns={columns}
        onExpandedRowsChange={keys => setExpandedRowKeys(keys)}
        dataSource={dataSource}
      />
    </div>
  );
}

export default WorkList;
