import { FC, useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Button, Table } from "antd";
import { DageTableActions } from "@dage/pc-components";
import { FileTemplateForm, FileTemplateModal } from "../FileTemplateModal";
import style from "./index.module.scss";

export interface FileTemplateTableProps {
  value?: FileTemplateForm[];
  tips?: string;
  onChange?: (val: FileTemplateForm[]) => void;
}

export const FileTemplateTable: FC<FileTemplateTableProps> = ({
  tips,
  value,
  onChange,
}) => {
  const [checkedItem, setCheckedItem] = useState<FileTemplateForm | null>(null);
  const [templateVisible, setTemplateVisible] = useState(false);

  const handleTemplate = (val: FileTemplateForm, isEdit?: boolean) => {
    const temp = value ? [...value] : [];

    if (isEdit) {
      const idx = temp.findIndex((i) => i.id === val.id);
      temp.splice(idx, 1, val);
    } else {
      temp.push(val);
    }

    onChange?.(temp);
  };

  const handleDelete = (index: number) => {
    const temp = value ? [...value] : [];
    temp.splice(index, 1);
    onChange?.(temp);
  };

  const handleCloseModal = () => {
    setTemplateVisible(false);
    setCheckedItem(null);
  };

  return (
    <div>
      <div className={style.top}>
        <Button
          className="second-button"
          icon={<PlusOutlined />}
          size="large"
          type="primary"
          onClick={() => setTemplateVisible(true)}
        >
          新增
        </Button>

        {tips && <p>{tips}</p>}
      </div>

      <Table
        className="cus-table mw650"
        dataSource={value}
        rowKey="id"
        columns={[
          {
            title: "资料名称",
            dataIndex: "name",
            key: "name",
            align: "center",
          },
          {
            title: "必须上传",
            key: "age",
            align: "center",
            render: (item: FileTemplateForm) => {
              return item.required ? "是" : "否";
            },
          },
          {
            title: "模板",
            key: "address",
            align: "center",
            render: (item: FileTemplateForm) => {
              return item.file ? item.file[0].name : "/";
            },
          },
          {
            title: "操作",
            align: "center",
            render: (item: FileTemplateForm, record, index) => {
              return (
                <DageTableActions
                  onEdit={() => {
                    setCheckedItem(item);
                    setTemplateVisible(true);
                  }}
                  onDelete={handleDelete.bind(undefined, index)}
                />
              );
            },
          },
        ]}
      />

      <FileTemplateModal
        item={checkedItem}
        open={templateVisible}
        onOk={handleTemplate}
        onCancel={handleCloseModal}
      />
    </div>
  );
};
