import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Space, message } from 'antd';
import { isEmpty } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';
import EditPromptModal from '@/components/EditAndAddPromptModal';
import DeletePromptModal from '@/components/DeletePromptModal';
import {
  pagePromptWords,
  createPromptWords,
  updatePromptWords,
  deletePromptWords,
  typePromptWords,
} from '@/services/chatGLM/api';
import moment from 'moment';

interface IPromptList {
  id: string;
  title?: string;
  content: string;
  type: string;
  creationTime: string;
  sequenceNumber: number;
}

export interface IFormValue {
  type: string | null;
  content: string;
}

export interface ITypeFormValue {
  type: string | null;
}
interface ILoading {
  editModalLoading: boolean;
  createModalLoading: boolean;
  deleteModalLoading: boolean;
  listLoading: boolean;
}

const PromptWord = () => {
  const actionRef = useRef<ActionType>();

  const [allLoading, setAllLoading] = useState<ILoading>({
    editModalLoading: false,
    createModalLoading: false,
    deleteModalLoading: false,
    listLoading: false,
  });
  const [editAndAddModalOpen, setEditAndDeleteModalOpen] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'edit' | ''>('');
  const [types, setTypes] = useState<string[]>([]);
  const [currentRow, setCurrentRaw] = useState({} as IPromptList);

  const columns: any[] = [
    {
      title: '提示类型',
      key: 'type',
      dataIndex: 'type',
      valueType: 'select',
      order: 1,
      fieldProps: {
        options: types.map((type) => {
          return {
            label: type,
            value: type,
          };
        }),
      },
    },
    {
      title: '提示词语',
      width: '40%',
      key: 'promptWord',
      dataIndex: 'content',
      ellipsis: true,
      search: true,
      order: 2,
    },
    {
      title: '创建时间',
      width: '25%',
      key: 'creationTime',
      dataIndex: 'creationTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: '15%',
      key: 'option',
      render: (_: unknown, record: IPromptList) => (
        <div className={styles.table_action}>
          <Space wrap>
            <div
              className={styles.table_action_edit}
              onClick={() => {
                setCurrentRaw(record);
                setEditAndDeleteModalOpen(true);
                setModalType('edit');
              }}
            >
              <Button size="small" type="link">
                编辑
              </Button>
            </div>
            <div
              className={styles.table_action_delete}
              onClick={() => {
                setDeleteModalOpen(true);
                setCurrentRaw(record);
              }}
            >
              <Button size="small" type="link" danger>
                删除
              </Button>
            </div>
          </Space>
        </div>
      ),
    },
  ];

  const fetchTypes = async () => {
    const data = await typePromptWords();
    setTypes(data);
  };

  useEffect(() => {
    fetchTypes();
  }, []);

  const handleEditPrompt = async (editValue: IFormValue) => {
    setAllLoading({ ...allLoading, editModalLoading: true });
    try {
      await updatePromptWords({
        id: currentRow.id,
        content: editValue.content,
        type: editValue.type,
      });
      setAllLoading({ ...allLoading, editModalLoading: false });
      actionRef.current?.reload();
      message.success('操作成功');
    } catch (error) {
      setAllLoading({ ...allLoading, editModalLoading: false });
      message.error('编辑提示用语失败，请重试');
    }
  };

  const handleCreatePrompt = async (createValue: IFormValue) => {
    setAllLoading({ ...allLoading, createModalLoading: true });
    try {
      await createPromptWords({
        content: createValue.content,
        type: createValue.type,
      });
      setAllLoading({ ...allLoading, createModalLoading: false });
      actionRef.current?.reload();
      message.success('操作成功');
    } catch (error) {
      setAllLoading({ ...allLoading, createModalLoading: false });
      message.error('新增提示用语失败，请重试');
    }
  };

  const handleDeletePrompt = async () => {
    setAllLoading({ ...allLoading, deleteModalLoading: true });

    try {
      await deletePromptWords({
        id: currentRow.id,
      });
      setAllLoading({ ...allLoading, deleteModalLoading: false });
      actionRef.current?.reload();
    } catch (error) {
      setAllLoading({ ...allLoading, deleteModalLoading: false });
      message.error('删除提示用语失败，请重试');
    }
  };

  return (
    <PageContainer>
      <DeletePromptModal
        open={deleteModalOpen}
        setOpen={setDeleteModalOpen}
        title="删除提示用语"
        tip="确定要删除这段提示词语吗？"
        content="一旦删除后，用户无法看到这一条提示词，建议谨慎操作。"
        handleDeletePrompt={handleDeletePrompt}
        loading={allLoading.deleteModalLoading}
      />
      <EditPromptModal
        open={editAndAddModalOpen}
        setOpen={setEditAndDeleteModalOpen}
        types={types}
        modalType={modalType}
        handleEditPrompt={handleEditPrompt}
        oldRow={currentRow}
        handleCreatePrompt={handleCreatePrompt}
        loading={
          modalType === 'create' ? allLoading.createModalLoading : allLoading.editModalLoading
        }
      />
      <ProTable
        request={async (params = { pageSize: 10, current: 0 }) => {
          setAllLoading({ ...allLoading, listLoading: true });
          const promptListParams = {
            filter: params?.promptWord || '',
            type: params?.type || '',
            pageIndex: (params?.current as number) - 1,
            pageSize: params?.pageSize,
          };
          try {
            const response = await pagePromptWords(promptListParams);
            setAllLoading({ ...allLoading, listLoading: false });
            return {
              data: response.items,
              total: response.totalCount,
              success: !isEmpty(response),
            };
          } catch (error) {
            setAllLoading({ ...allLoading, listLoading: false });
            message.error('请求列表失败，请重试');
            return {
              data: [],
              total: 0,
              success: false,
            };
          }
        }}
        actionRef={actionRef}
        columns={columns}
        cardBordered
        rowKey="id"
        pagination={{
          pageSize: 10,
        }}
        options={false}
        headerTitle="账号列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditAndDeleteModalOpen(true);
              setModalType('create');
            }}
            type="primary"
          >
            添加提示语
          </Button>,
        ]}
        loading={allLoading.listLoading}
      />
    </PageContainer>
  );
};

export default PromptWord;
