import React, { useState} from "react";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { Card, Table, Popconfirm, message, Button, Input, Popover, Select } from "antd";
import { PlusOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import usePagination from "@/hooks/usePagination";
import { ListVO, getTimeListApi, taskDeleteApi, ItemListVO } from "./api";
import {TimeUnits } from "./entity";
import { debounce } from "lodash";
import CreateModal from "./components/CreateModal";

import { systemListApi } from "@/pages/admin/Privilege/api";

const Column = Table.Column;
const Search = Input.Search;

export default function TaskConfig() {
  const { list, loading, paginationConfig, setParams, setLoading } = usePagination<ListVO>(getTimeListApi, {}, {});
  const [item, setItem] =useState({});
  const { list: syslist } = usePagination(systemListApi, { current: 1, pageSize: 100 });
  const [modalData, setModalData] = useState<{ visible: boolean; row: ItemListVO }>({ visible: false, row: {} });

  function triggerModal(row: ItemListVO = {}) {
    setModalData({ visible: !modalData.visible, row });
  }
  const _onChange = debounce((val: string) => {
    setParams({ keywords: val.trim(), current: 1 }, true);
  }, 500);
  //根据系统名称搜索
  const _onChangeSys = debounce((e: any) => {
    setParams({ sysId: e, current: 1 }, true);
  }, 500);
  // 删除待办
  const handleDelete = (record: any) => {
    taskDeleteApi(record.id)
      .then((res) => {
        message.success("删除成功！");
        setLoading(true);
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  return (
    <PageHeaderWrapper title="待办时效">
      <Card>
        <div
          style={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: 20,
          }}
        >
          <div style={{ display: "flex" }}>
            <Search allowClear placeholder="搜索待办名" onChange={(e) => _onChange(e.target.value)} style={{ maxWidth: 260, marginRight: 15 }} />

            <Select allowClear placeholder="搜索系统名称" style={{ width: 260, marginRight: 5 }} onChange={(e: any) => _onChangeSys(e)}>
              {syslist.map((item) => (
                <Select.Option value={item.id!} key={item.id}>
                  {item.sysName}
                </Select.Option>
              ))}
            </Select>
          </div>

          <Button type="primary" icon={<PlusOutlined />} onClick={() => triggerModal()}>
            新增
          </Button>
        </div>
        <Table loading={loading} dataSource={list} pagination={paginationConfig} rowKey={(record: ListVO) => String(record.id || record.configId)}>
          <Column title="待办名称" dataIndex="configName" align="center" />
          <Column
            title="待办时效"
            dataIndex="periodValue"
            align="center"
            render={(text, record: ListVO) => {
              const tempTimeData = record.periodUnit ? `${text}${TimeUnits[record.periodUnit]}` : "--";
              return text ? tempTimeData : "--";
            }}
          />
          <Column
            title={
              <Popover
                placement="topLeft"
                content={
                  <>
                    <p> 待办截止时间=待办时效时间+待办延时时间</p>
                    <p>如未配置待办延时时间，则表示待办无结束时间</p>
                  </>
                }
              >
                <span>
                  待办延时时间&nbsp;&nbsp;
                  <ExclamationCircleFilled style={{ color: "#40a9ff" }} />
                </span>
              </Popover>
            }
            dataIndex="extendValue"
            align="center"
            render={(text, record: ListVO) => {
              const endTimeData = record.extendUnit ? `${text}${TimeUnits[record.extendUnit]}` : "--";
              return text !== null ? endTimeData : "--";
            }}
          />
          <Column
            title="操作"
            align="center"
            render={(val, row: ListVO) => (
              <>
                <Button type="link" onClick={() => { triggerModal(row); setItem(row); }}>
                  编辑
                </Button>
                <Popconfirm placement="top" title="确认删除？" onConfirm={() => handleDelete(row)}>
                  <Button type="link">删除</Button>
                </Popconfirm>
              </>
            )}
          />
        </Table>
        <CreateModal visible={modalData.visible} onCancel={() => { triggerModal(); setItem({}); }} onRefreshing={() => setLoading(true)} item={item} />
      </Card>
    </PageHeaderWrapper>
  );
}
