import React, { useState } from 'react';
import {
  Form,
  InputNumber,
  Input,
  Button,
  Popover,
  Divider,
  Collapse,
  List,
  Table,
  Select,
  Row,
  Col,
} from 'antd';
import styles from './index.less';

const { Panel } = Collapse;
const { Option } = Select;

function AuthWorkList(props) {
  const { list, onAuth, onSearch, onSave, project = [], allType, onAgree, onReject, user } = props;
  const [form] = Form.useForm();
  const [edit, setEdit] = useState(false);
  const columns = [
    {
      title: '分类',
      dataIndex: 'type_id',
      render: type_id => allType[type_id]?.name,
    },
    {
      title: '提交人',
      dataIndex: ['User', 'CName'],
    },
    {
      title: '审核状态',
      render: record => renderStatus(record),
    },
    {
      title: '工时',
      width: 110,
      render: item => {
        if (item.zIndex === 0) {
          return '总计 ' + item.children.reduce((total, item) => total + item.workload, 0) + '小时';
        }
        return item?.workload + '小时';
      },
    },
    {
      title: '操作',
      render: item => {
        if (item.zIndex === 0) return '';
        if (item.audit_state != 1) return;
        return (
          <>
            <a onClick={() => onAgree([item], true)}>通过</a>
            <Divider type="vertical"></Divider>
            <a style={{ color: '#f5222d' }} onClick={() => onReject([item])}>
              拒绝
            </a>
          </>
        );
      },
    },
  ];
  const renderStatus = item => {
    // 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 getList = arr => {
    let data = {};
    arr.forEach(item => {
      let userId = item.User.ID;
      let id = item.project_id;
      let name;
      if (id == '0') {
        name = '其他';
      } else {
        name = item.Project.Name;
      }

      if (!data[id]) data[id] = { list: [], name, id };
      data[id].list.push(item);
    });
    let allList = Object.values(data);
    // 将id为0的项 放置到数组最后
    let index = allList.findIndex(item => item.id == '0');
    if (index != -1) {
      var temp = allList.splice(index, 1);
      allList.push(temp[0]);
    }
    allList.forEach(item => {
      const { list, audit } = getTableInfo(item.list);
      item.list = list;
      item.audit = audit;
    });
    return allList;
  };

  const getTableInfo = list => {
    let data = {},
      audit = [];
    list.forEach(item => {
      let pid = allType[item.type_id]?.parent_id;
      if (!data[pid]) data[pid] = [];
      data[pid].push(item);
      // 判断是否处于待审批状态
      if (item.audit_state == 1) {
        // 保存可审批的项
        audit.push(item);
      }
    });
    let newList = Object.keys(data).map(pid => ({
      zIndex: 0,
      id: pid,
      type_id: allType[pid]?.id,
      children: data[pid],
    }));
    return {
      list: newList,
      audit,
    };
  };

  const renderSearch = () => {
    const onHandleSearch = () => {
      form.validateFields().then(values => {
        onSearch(values);
      });
    };
    return (
      <Form style={{ marginBottom: 20 }} form={form}>
        <Row gutter={12}>
          <Col span={12}>
            <Form.Item label="人员" name="userId">
              <Select
                allowClear
                showSearch
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {user.map(item => (
                  <Option key={item.ID}>{item.CName}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="项目" name="projectId">
              <Select
                allowClear
                showSearch
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {project.map(item => (
                  <Option key={item.ID}>{`${item.Name}(${item.Code})`}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Button onClick={onHandleSearch} type="primary">
              搜索
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  const dataList = getList(list);

  return (
    <div style={{ height: 730, overflowY: 'auto', overflowX: 'hidden' }}>
      {renderSearch()}
      {dataList.length > 0 && (
        <Collapse>
          {dataList.map(item => {
            // 合计未审核时间
            let auditTime = item.audit.reduce((total, item) => total + item.workload, 0);
            let extra;
            if (auditTime > 0) {
              extra = (
                <>
                  <a onClick={(e) => {
                    e.stopPropagation();
                    onAgree(item.audit, true)
                  }}>全部通过</a>
                  <Divider type="vertical"></Divider>
                  <a style={{ color: '#f5222d' }} onClick={() => {
                    e.stopPropagation();
                    onReject(item.audit)
                  }}>
                    全部拒绝
                  </a>
                </>
              );
            }
            return (
              <Panel header={`${item.name} (待审核：${auditTime}小时)`} key={item.id} extra={extra}>
                <Table rowKey="id" columns={columns} dataSource={item.list} />
              </Panel>
            );
          })}
        </Collapse>
      )}
    </div>
  );
}

export default AuthWorkList;
