import CommonTableCell from '@/components/CommonTableCell';
import DateTableCell from '@/components/DateTableCell';
import KFIcon from '@/components/KFIcon';
import { useEffectWhen } from '@/hooks';
import AddVersionModal from '@/pages/Dataset/components/AddVersionModal';
import {
  ResourceFileData,
  ResourceType,
  ResourceVersionData,
  resourceConfig,
} from '@/pages/Dataset/config';
import { downLoadZip } from '@/utils/downloadfile';
import { openAntdModal } from '@/utils/modal';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { App, Button, Flex, Select, Table } from 'antd';
import { useState } from 'react';
import styles from './index.less';

type ResourceVersionProps = {
  resourceType: ResourceType;
  resourceId: number;
  resourceName: string;
  isPublic: boolean;
  versionList: ResourceVersionData[];
  version?: string;
  isActive: boolean;
  getVersionList: () => void;
  onVersionChange: (version: string) => void;
};
function ResourceVersion({
  resourceType,
  resourceId,
  resourceName,
  isPublic,
  versionList,
  version,
  isActive,
  getVersionList,
  onVersionChange,
}: ResourceVersionProps) {
  const [fileList, setFileList] = useState<ResourceFileData[]>([]);
  const { message } = App.useApp();
  const config = resourceConfig[resourceType];

  // 获取版本文件列表
  useEffectWhen(
    () => {
      if (version) {
        getFileList(version);
      } else {
        setFileList([]);
      }
    },
    [resourceId, version],
    isActive,
  );

  // 获取版本下的文件列表
  const getFileList = async (version: string) => {
    const params = {
      version,
      [config.fileReqParamKey]: resourceId,
    };
    const request = config.getFiles;
    const [res] = await to(request(params));
    if (res) {
      setFileList(res?.data?.content ?? []);
    }
  };

  // 删除版本
  const deleteVersion = async () => {
    const request = config.deleteVersion;
    const params = {
      [config.idParamKey]: resourceId,
      version,
    };
    const [res] = await to(request(params));
    if (res) {
      getVersionList();
      message.success('删除成功');
    }
  };

  // 新建版本
  const showModal = () => {
    const { close } = openAntdModal(AddVersionModal, {
      resourceType: resourceType,
      resourceId: resourceId,
      initialName: resourceName,
      onOk: () => {
        getVersionList();
        close();
      },
    });
  };

  // 处理删除
  const hanldeDelete = () => {
    modalConfirm({
      title: '删除后，该版本将不可恢复',
      content: '是否确认删除?',
      okText: '确认',
      cancelText: '取消',

      onOk: () => {
        deleteVersion();
      },
    });
  };

  // 全部导出
  const handleExport = async () => {
    const url = config.downloadAllAction;
    downLoadZip(url, { models_id: resourceId, version });
  };

  // 单个导出
  const downloadAlone = (record: ResourceFileData) => {
    const url = config.downloadSingleAction;
    downLoadZip(`${url}/${record.id}`);
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render(_text: string, _record: ResourceFileData, index: number) {
        return <span>{index + 1}</span>;
      },
    },
    {
      title: '文件名称',
      dataIndex: 'file_name',
      key: 'file_name',
      render: (text: string, record: ResourceFileData) => (
        <a className="kf-table-row-link" onClick={() => downloadAlone(record)}>
          {text}
        </a>
      ),
    },
    {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
      render: CommonTableCell(),
    },
    {
      title: '文件大小',
      dataIndex: 'file_size',
      key: 'file_size',
      render: CommonTableCell(),
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'update_time',
      render: DateTableCell,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '100px',
      key: 'option',
      render: (_: any, record: ResourceFileData) => [
        <Button
          type="link"
          size="small"
          key="download"
          icon={<KFIcon type="icon-xiazai" />}
          onClick={() => downloadAlone(record)}
        >
          下载
        </Button>,
      ],
    },
  ];

  return (
    <div className={styles['resource-version']}>
      <Flex justify="space-between" align="center" style={{ margin: '30px 0' }}>
        <Flex align="center">
          <span style={{ marginRight: '10px' }}>版本号：</span>
          <Select
            placeholder="请选择版本号"
            style={{ width: '160px', marginRight: '20px' }}
            value={version}
            onChange={onVersionChange}
            options={versionList}
          />
          <Button type="default" onClick={showModal} icon={<KFIcon type="icon-xinjian2" />}>
            创建新版本
          </Button>
        </Flex>
        <Flex align="center">
          {!isPublic && (
            <Button
              type="default"
              style={{ marginRight: '20px' }}
              onClick={hanldeDelete}
              icon={<KFIcon type="icon-shanchu" />}
            >
              删除
            </Button>
          )}
          <Button
            type="default"
            disabled={!version}
            onClick={handleExport}
            icon={<KFIcon type="icon-xiazai" />}
          >
            下载
          </Button>
        </Flex>
      </Flex>
      <div style={{ marginBottom: '30px', fontSize: '15px' }}>
        {fileList.length > 0 && fileList[0].description
          ? '版本描述：' + fileList[0].description
          : null}
      </div>
      <Table columns={columns} dataSource={fileList} pagination={false} rowKey="id" />
    </div>
  );
}

export default ResourceVersion;
