import { useRef, useState } from "react";
import { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { Space, Tag, message, Popconfirm } from "antd";
import AddTemplateDrawer from "./AddTemplateDrawer";
import {
  GetTemplateList,
  DeleteTemplate,
  OnMarketTemplate,
  OffMarketTemplate,
} from "@/api/templateStore";
import { history } from "umi";
import { MODULE_TEMPLATE_TYPE } from "@/constants";

export default () => {
  const actionRef = useRef<ActionType>();
  const [editData, setEditData] = useState<any>();
  const handleToDetail = (id?: string) => {
    history.push(`/detail/template/${id}`);
  };

  const handleOffMarket = async (id?: string) => {
    if (id) {
      await OffMarketTemplate({ ids: [id] });
      actionRef.current?.reload();
      message.success("下架成功");
    }
  };

  const handleOnMarket = async (id?: string) => {
    if (id) {
      await OnMarketTemplate({ ids: [id] });
      actionRef.current?.reload();
      message.success("上架成功");
    }
  };

  const handleDelete = async (id?: string) => {
    if (id) {
      await DeleteTemplate({ ids: [id] });
      actionRef.current?.reload();
      message.success("删除成功");
    }
  };

  const columns: ProColumns<any>[] = [
    {
      title: "图标",
      dataIndex: "icon",
      search: false,
      render: (_, record) => (
        <img
          src={`/api/File/Download?fileId=${record.icon}`}
          alt=""
          style={{
            width: 30,
            height: 30,
            borderRadius: "50%",
          }}
        />
      ),
    },
    {
      title: "模版名称",
      dataIndex: "name",
      copyable: true,
      ellipsis: true,
    },
    {
      title: "作者",
      dataIndex: "createByName",
      ellipsis: true,
      search: false,
    },
    {
      title: "模版分类",
      dataIndex: "type",
      copyable: true,
      ellipsis: true,
      valueType: "select",
      fieldProps: {
        options: MODULE_TEMPLATE_TYPE,
      },
    },
    {
      disable: true,
      title: "标签",
      dataIndex: "labels",
      search: false,
      renderFormItem: (_, { defaultRender }) => {
        return defaultRender(_);
      },
      render: (_, record) => (
        <Space>
          {record.tags?.split(",").map((tag: string) => (
            <Tag color="green" key={tag}>
              {tag}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: "上架状态",
      dataIndex: "isOnMarket",
      ellipsis: true,
      valueType: "select",
      valueEnum: {
        on: {
          text: "已上架",
          status: "Error",
        },
        off: {
          text: "未上架",
          status: "Success",
        },
      },
      render: (_, record) => (
        <Tag color={record.isOnMarket ? "green" : "red"}>
          {record.isOnMarket ? "已上架" : "未上架"}
        </Tag>
      ),
    },
    {
      title: "使用量",
      dataIndex: "useNum",
      search: false,
    },
    {
      title: "价格",
      dataIndex: "price",
      search: false,
      renderText: (text) => {
        return text ? `¥${text}` : "免费";
      },
    },
    {
      title: "更新时间",
      dataIndex: "createTime",
      search: false,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      search: false,
    },
    {
      title: "操作",
      valueType: "option",
      key: "option",
      width: 180,
      render: (text, record, _, action) => [
        <a key="edit" onClick={() => setEditData(record)}>
          编辑
        </a>,
        <a
          target="_blank"
          rel="noopener noreferrer"
          key="view"
          onClick={() => handleToDetail(record.id)}
        >
          详情
        </a>,
        record.isOnMarket ? (
          <a
            target="_blank"
            rel="noopener noreferrer"
            key="off"
            onClick={() => handleOffMarket(record.id)}
          >
            下架
          </a>
        ) : (
          <a
            target="_blank"
            rel="noopener noreferrer"
            key="on"
            onClick={() => handleOnMarket(record.id)}
          >
            上架
          </a>
        ),
        <Popconfirm
          key="delete"
          title="确定删除吗？"
          onConfirm={() => handleDelete(record.id)}
        >
          <a className="text-red-500" target="_blank" rel="noopener noreferrer">
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable
      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async (params, sort, filter) => {
        const isOnMarket =
          params?.isOnMarket === "on"
            ? 1
            : params?.isOnMarket === "off"
              ? 0
              : undefined;
        const res = await GetTemplateList({
          currentPage: params.current || 1,
          pageSize: params.pageSize || 10,
          filters: [
            { name: "name", value: params?.name },
            { name: "isFree", value: params?.isFree },
            { name: "isOnMarket", value: isOnMarket },
            { name: "isDel", value: 0 },
            { name: "type", value: params?.type },
          ],
        });

        const data = res?.result || {};

        return {
          success: true,
          data: data.model || [],
          total: data.totalCount || 0,
        };
      }}
      columnsState={{
        persistenceKey: "shalu-marketplace",
        persistenceType: "localStorage",
        defaultValue: {
          option: { fixed: "right", disable: true },
        },
      }}
      rowKey="id"
      search={{
        labelWidth: "auto",
      }}
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      pagination={{
        pageSize: 10,
      }}
      dateFormatter="string"
      headerTitle={
        <AddTemplateDrawer
          onClose={() => setEditData(undefined)}
          onSuccess={() => {
            actionRef.current?.reload();
          }}
          editData={editData}
        />
      }
    />
  );
};
