import React, { useState, useEffect } from "react";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import {
  Card,
  Table,
  Popconfirm,
  Switch,
  message,
  Button,
  Input,
  Select,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import usePagination from "@/hooks/usePagination";
import {
  ListVO,
  getConfigListApi,
  taskEnableApi,
  taskDeleteApi,
  taskDisableApi,
} from "./api";
import { TodoTypeEnum } from "./entity";
import moment from "moment";
import { debounce } from "lodash";
import CreateModal from "./components/CreateModal";
import { getAllRoleCodeApi } from "@/common/api";
import { systemListApi } from "@/pages/admin/Privilege/api";
import {
  getWorkTypeListApi,
  WorkTypeListVO,
} from "@/pages/backlog/WorkTypeConfig/api";

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

export default function TaskConfig() {
  const { list, loading, paginationConfig, setList, setParams, setLoading } =
    usePagination<ListVO>(getConfigListApi, {}, {});
  const [switchLoading, setSwitchLoading] = useState(false);
  const [modalData, setModalData] = useState<{ visible: boolean; row: ListVO }>(
    { visible: false, row: {} }
  );
  /**
   * 查询系统列表
   */
  const { list: syslist } = usePagination(systemListApi, {
    current: 1,
    pageSize: 100,
  });

  /**
   * 查询工作类型列表
   */
  const { list: workTyoeList } = usePagination<WorkTypeListVO>(
    getWorkTypeListApi,
    { pageSize: 1000 }
  );

  useEffect(() => {
    getAllRoleCodeApi()
      .then((res) => {})
      .catch((e) => {
        message.error(`获取角色列表失败：${e.message}`);
      });
  }, []);

  function triggerModal(row: ListVO = {}) {
    setModalData({ visible: !modalData.visible, row });
  }

  const _onChange = debounce((val: string) => {
    setParams({ keywords: val.trim(), current: 1 }, true);
  }, 500);

  // 禁用或启用待办
  const handleChangeStatus = (record: ListVO) => {
    const API = record.status ? taskDisableApi : taskEnableApi;
    record.id &&
      API(record.id)
        .then((res) => {
          setSwitchLoading(false);
          message.success(record.status ? "禁用成功" : "启用成功");
          const tempList = list.map((item: ListVO) => {
            if (item.id == record.id) {
              return { ...item, status: record.status == 0 ? 1 : 0 };
            }
            return item;
          });
          setList(tempList);
        })
        .catch((e) => {
          setSwitchLoading(false);
          message.error(e.message);
        });
  };

  // 删除待办
  const handleDelete = (record: any) => {
    taskDeleteApi(record.id)
      .then((res) => {
        message.success("删除成功！");
        setLoading(true);
      })
      .catch((e) => {
        setSwitchLoading(false);
        message.error(e.message);
      });
  };

  //根据系统名称搜索
  const _onChangeSys = (value: any) => {
    setParams({ ...value, current: 1 }, true);
  };

  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={(value: any) => _onChangeSys({ sysId: value })}
              showSearch
              optionFilterProp="children"
            >
              {syslist.map((item) => (
                <Select.Option value={item.id!} key={item.id}>
                  {item.sysName}
                </Select.Option>
              ))}
            </Select>
            <Select
              allowClear
              placeholder="选择工作类型"
              style={{ width: 260, marginRight: 5 }}
              onChange={(value: number) => _onChangeSys({ workType: value })}
              showSearch
              optionFilterProp="children"
            >
              {workTyoeList.map((item) => (
                <Select.Option value={item.id!} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => triggerModal()}
          >
            新增配置
          </Button>
        </div>
        <Table
          loading={loading}
          dataSource={list}
          pagination={paginationConfig}
          rowKey="itemCode"
        >
          <Column title="待办项" dataIndex="itemName" align="center" />
          <Column title="待办编码" dataIndex="itemCode" align="center" />
          <Column
            title="类型"
            dataIndex="itemType"
            align="center"
            render={(t) => TodoTypeEnum[t]}
          />

          <Column
            title="对接新待办"
            dataIndex="dock"
            align="center"
            render={(text) => (String(text) === "true" ? "是" : "否")}
          />
          <Column
            title="待办时效考核"
            dataIndex="assess"
            align="center"
            render={(text) => (String(text) === "true" ? "是" : "否")}
          />
          <Column
            title="归属系统"
            dataIndex="applySysName"
            align="center"
            render={(text) => <span>{text || "--"}</span>}
          />
          <Column
            title="工作类型"
            dataIndex="workTypeName"
            align="center"
            render={(text) => <span>{text || "--"}</span>}
          />
          <Column
            title="创建时间"
            dataIndex="createTime"
            align="center"
            render={(text) => moment(text).format("YYYY-MM-DD")}
          />
          <Column
            title="状态"
            align="center"
            dataIndex="status"
            render={(val, row: ListVO) => (
              <Popconfirm
                placement="top"
                title={`确认${val ? "禁用" : "启用"}？`}
                onConfirm={() => handleChangeStatus(row)}
                onCancel={() => setSwitchLoading(false)}
              >
                <Switch
                  checkedChildren="启用"
                  unCheckedChildren="禁用"
                  checked={!!val}
                  size="small"
                  loading={switchLoading}
                  onClick={() => setSwitchLoading(true)}
                />
              </Popconfirm>
            )}
          />
          <Column
            title="操作"
            align="center"
            render={(val, row: ListVO) => (
              <>
                <Button type="link" onClick={() => triggerModal(row)}>
                  编辑
                </Button>
                <Popconfirm
                  placement="top"
                  title="确认删除？"
                  onConfirm={() => handleDelete(row)}
                >
                  <Button type="link">删除</Button>
                </Popconfirm>
              </>
            )}
          />
        </Table>
        <CreateModal
          visible={modalData.visible}
          onCancel={triggerModal}
          onRefreshing={() => setLoading(true)}
          item={modalData.row}
          systemList={syslist || []}
          workTyoeList={workTyoeList || []}
        />
      </Card>
    </PageHeaderWrapper>
  );
}
