import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import React, { useRef, useState } from 'react';
import { App, Button, Modal } from 'antd';
import {
  deleteAppRobotCommand,
  listAppRobotCommand,
  updateAppRobotCommand,
} from '@/services/api/appRobotCommand';
import { isEqual } from 'lodash-es';
import AddAppRobotCommand from '@/pages/AppManage/components/AddAppRobotCommand';
import { whitespaceForbidden } from '@/constants/rules';

type TableListItem = API.ListAppRobotCommandVo;

/** 应用机器人管理组件 */
const AppRobotCommandManage: React.FC<{
  /** 受控的打开关闭 */
  open: boolean;
  /** 打开关闭的事件 */
  setOpen: (v: boolean) => void;
  /** 应用编码 */
  appId: string;
  /** 机器人编码 */
  robotCode: string;
}> = ({ open, setOpen, appId, robotCode }) => {
  // Table action 的引用，便于自定义触发
  const actionRef = useRef<ActionType>();
  // 正在编辑的行
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const { message } = App.useApp();

  /**
   * 获取数据
   * @param params 参数
   * @param sort 排序
   */
  const getDataSource = async (params: any, sort: any) => {
    const res = await listAppRobotCommand({
      ...params,
      sort,
      appId,
      robotCode,
    });
    return Promise.resolve({
      success: true,
      data: res?.data?.list,
      total: res?.data?.total,
    });
  };

  // 表格列的配置描述
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '命令',
      dataIndex: 'command',
      copyable: true,
      sorter: true,
      editable: false,
    },
    {
      title: 'url',
      dataIndex: 'url',
      copyable: true,
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
          whitespaceForbidden,
        ],
      },
    },
    {
      title: '说明',
      dataIndex: 'description',
      copyable: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      editable: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      editable: false,
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      render: (text, record, index, action) => (
        <Button
          danger
          onClick={() => {
            action?.startEditable?.(record?.command as string);
          }}
        >
          编辑
        </Button>
      ),
    },
  ];

  /**
   * 行保存
   * @param key 行 id，一般是唯一id
   * @param record 当前修改的行的值，只有 form 在内的会被设置
   * @param originRow 原始值，可以用于判断是否修改
   */
  const onSave = async (key: any, record: any, originRow: any) => {
    if (isEqual(record, originRow)) {
      return Promise.reject();
    }

    await updateAppRobotCommand({ ...record, appId, robotCode });
    message.success('修改成功');
    actionRef.current?.reload();
    return Promise.resolve();
  };

  /**
   * 行删除
   * @param key 行 id，一般是唯一id
   */
  const onDelete = async (key: any) => {
    await deleteAppRobotCommand({ command: key, appId, robotCode });
    message.success('删除成功');
    actionRef.current?.reload();
    return Promise.resolve();
  };

  return (
    <Modal
      title="机器人命令管理"
      open={open}
      onCancel={() => setOpen(false)}
      footer={false}
      destroyOnClose
      width={'100%'}
    >
      <ProTable<TableListItem>
        headerTitle="命令列表"
        rowKey="command"
        actionRef={actionRef}
        columns={columns}
        pagination={{
          showQuickJumper: true,
          defaultPageSize: 10,
        }}
        search={{
          layout: 'vertical',
        }}
        toolBarRender={() => [
          <AddAppRobotCommand
            key={'add'}
            actionRef={actionRef}
            appId={appId}
            robotCode={robotCode}
          />,
        ]}
        request={getDataSource}
        editable={{
          type: 'single',
          editableKeys,
          onChange: setEditableRowKeys,
          onSave,
          onDelete,
        }}
      />
    </Modal>
  );
};

export default AppRobotCommandManage;
