import { 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 { useRef, useState } from 'react';
import styles from './index.less';
import {
  pagePromptWordType,
  createPromptWordType,
  updatePromptWordType,
} from '@/services/chatGLM/api';
import EditPromptTypeModal from '@/components/EditAndAddPromptTypeModal';
import { ITypeFormValue } from '../PromptWord';

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

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

interface ILoading {
  editModalLoading: boolean;
  createModalLoading: boolean;
  deleteModalLoading: boolean;
  listLoading: boolean;
}

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

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

  const columns: any[] = [
    {
      title: '提示类型',
      key: 'type',
      dataIndex: 'type',
      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}>
          <div
            className={styles.table_action_edit}
            onClick={() => {
              setCurrentRaw(record);
              setEditAndDeleteModalOpen(true);
              setModalType('edit');
            }}
          >
            <Button size="small" type="link">
              编辑
            </Button>
          </div>
        </div>
      ),
    },
  ];

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

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

  return (
    <PageContainer>
      <EditPromptTypeModal
        open={editAndAddModalOpen}
        setOpen={setEditAndDeleteModalOpen}
        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['type'] || '',
            pageIndex: (params?.current as number) - 1,
            pageSize: params?.pageSize,
          };
          try {
            const response = await pagePromptWordType(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 PromptWordType;
