/*
 * @Author: 赵伟
 * @Date: 2024-09-06 09:23:15
 * @Description: 数据集、模型详情
 */

import KFIcon from '@/components/KFIcon';
import {
  ResourceData,
  ResourceType,
  ResourceVersionData,
  resourceConfig,
} from '@/pages/Dataset/config';
import GraphLegend from '@/pages/Model/components/GraphLegend';
import ModelEvolution from '@/pages/Model/components/ModelEvolution';
import { praiseResourceReq, unpraiseResourceReq } from '@/services/dataset';
import { VersionChangedMessage } from '@/utils/constant';
import { openAntdModal } from '@/utils/modal';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { useParams, useSearchParams } from '@umijs/max';
import { App, Button, Flex, Select, Tabs } from 'antd';
import classNames from 'classnames';
import { useCallback, useEffect, useState } from 'react';
import AddVersionModal from '../AddVersionModal';
import ResourceIntro from '../ResourceIntro';
import ResourceVersion from '../ResourceVersion';
import VersionCompareModal from '../VersionCompareModal';
import VersionSelectorModal from '../VersionSelectorModal';
import styles from './index.less';

// 这里值小写是因为值会写在 url 中
export enum ResourceInfoTabKeys {
  Introduction = 'introduction', // 简介
  Version = 'version', // 版本
  Evolution = 'evolution', // 演化
}

type ResourceInfoProps = {
  resourceType: ResourceType;
};

const ResourceInfo = ({ resourceType }: ResourceInfoProps) => {
  const [info, setInfo] = useState<ResourceData>({} as ResourceData);
  const locationParams = useParams();
  const [searchParams] = useSearchParams();
  const resourceId = Number(locationParams.id);
  // 模型演化传入的 tab
  const defaultTab = searchParams.get('tab') || ResourceInfoTabKeys.Introduction;
  // 模型演化传入的版本
  const versionParam = searchParams.get('version');
  const name = searchParams.get('name') || '';
  const owner = searchParams.get('owner') || '';
  const identifier = searchParams.get('identifier') || '';
  const is_public = (searchParams.get('is_public') || '') === 'true';
  const [versionList, setVersionList] = useState<ResourceVersionData[]>([]);
  const [version, setVersion] = useState<string | undefined>(undefined);
  const [activeTab, setActiveTab] = useState<string>(defaultTab);
  const config = resourceConfig[resourceType];
  const typeName = config.name; // 数据集/模型
  const { message } = App.useApp();

  // 获取详情
  const getResourceDetail = useCallback(async () => {
    const params = {
      id: resourceId,
      owner,
      name,
      identifier,
      version,
      is_public,
    };
    const request = config.getInfo;
    const [res] = await to(request(params));
    if (res && res.data) {
      setInfo(res.data);
    }
  }, [config, resourceId, owner, name, identifier, version, is_public]);

  // 获取版本列表
  const getVersionList = useCallback(
    async (refresh: boolean) => {
      const request = config.getVersions;
      const [res] = await to(
        request({
          owner,
          identifier,
        }),
      );
      if (res && res.data && res.data.length > 0) {
        setVersionList(res.data);
        if (
          !refresh &&
          versionParam &&
          res.data.find((item: ResourceVersionData) => item.name === versionParam)
        ) {
          setVersion(versionParam);
        } else {
          setVersion(res.data[0].name);
        }
      } else {
        setVersion(undefined);
      }
    },
    [config, owner, identifier, versionParam],
  );

  useEffect(() => {
    if (version) {
      getResourceDetail();
    }
  }, [version, getResourceDetail]);

  useEffect(() => {
    getVersionList(false);
  }, [getVersionList]);

  // 新建版本
  const showModal = () => {
    const { close } = openAntdModal(AddVersionModal, {
      resourceType: resourceType,
      resourceId: resourceId,
      resoureName: info.name,
      owner: info.owner,
      identifier: info.identifier,
      is_public: is_public,
      onOk: () => {
        getVersionList(true);
        close();
        window.postMessage({ type: VersionChangedMessage });
      },
    });
  };

  // 选择版本
  const showVersionSelector = () => {
    const { close } = openAntdModal(VersionSelectorModal, {
      versions: versionList,
      onOk: (version: string[]) => {
        showVersionComparison(version);
        close();
      },
    });
  };

  // 版本对比
  const showVersionComparison = (versions: string[]) => {
    openAntdModal(VersionCompareModal, {
      versions: versions,
      resourceType: resourceType,
      repo_id: resourceId,
      owner: info.owner,
      identifier: info.identifier,
      is_public: is_public,
    });
  };

  // 版本变化
  const handleVersionChange = (value: string) => {
    setVersion(value);
  };

  // 删除版本
  const deleteVersion = async () => {
    const request = config.deleteVersion;
    const params = {
      id: resourceId,
      owner,
      identifier,
      relative_paths: info.relative_paths,
      version,
    };
    const [res] = await to(request(params));
    if (res) {
      message.success('删除成功');
      getVersionList(true);
      window.postMessage({ type: VersionChangedMessage });
    }
  };

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

  // 处理点赞
  const handlePraise = async () => {
    const request = info.praised === true ? unpraiseResourceReq : praiseResourceReq;
    const [res] = await to(request(info.id));
    if (res) {
      message.success('操作成功');
      setInfo({
        ...info,
        praised: !info.praised,
        praises_count: info.praised ? info.praises_count - 1 : info.praises_count + 1,
      });
    }
  };

  const items = [
    {
      key: ResourceInfoTabKeys.Introduction,
      label: `${typeName}简介`,
      icon: <KFIcon type="icon-moxingjianjie" />,
      children: (
        <ResourceIntro
          resourceType={resourceType}
          info={info}
          resourceId={resourceId}
          identifier={identifier}
          owner={owner}
          version={version}
        ></ResourceIntro>
      ),
    },
    {
      key: ResourceInfoTabKeys.Version,
      label: `${typeName}文件`,
      icon: <KFIcon type="icon-moxingwenjian" />,
      children: <ResourceVersion resourceType={resourceType} info={info}></ResourceVersion>,
    },
  ];

  if (resourceType === ResourceType.Model) {
    items.push({
      key: ResourceInfoTabKeys.Evolution,
      label: `模型演化`,
      icon: <KFIcon type="icon-moxingyanhua1" />,
      children: (
        <ModelEvolution
          resourceId={resourceId}
          version={version}
          identifier={identifier}
          isActive={activeTab === ResourceInfoTabKeys.Evolution}
          onVersionChange={handleVersionChange}
        ></ModelEvolution>
      ),
    });
  }

  const typePropertyName = config.typeParamKey as keyof ResourceData;
  const tagPropertyName = config.tagParamKey as keyof ResourceData;

  return (
    <div className={styles['resource-info']}>
      <div className={styles['resource-info__top']}>
        <Flex align="center" gap={10} style={{ marginBottom: '20px' }}>
          <div className={styles['resource-info__top__name']}>{info.name}</div>
          {info[typePropertyName] && (
            <div className={styles['resource-info__top__tag']}>
              {(info[typePropertyName] as string) || '--'}
            </div>
          )}
          {info[tagPropertyName] && (
            <div className={styles['resource-info__top__tag']}>
              {(info[tagPropertyName] as string) || '--'}
            </div>
          )}
          <div
            className={classNames(styles['resource-info__top__praise'], {
              [styles['resource-info__top__praise--praised']]: info.praised,
            })}
            onClick={handlePraise}
          >
            <KFIcon
              type={info.praised ? 'icon-dianzanhou' : 'icon-dianzan'}
              font={16}
              style={{ marginRight: '3px' }}
            />
            <span>{info.praises_count}</span>
          </div>
        </Flex>
        <Flex align="center">
          <span style={{ marginRight: '10px' }}>版本号：</span>
          <Select
            placeholder="请选择版本号"
            style={{ width: '160px', marginRight: '20px' }}
            value={version}
            onChange={handleVersionChange}
            fieldNames={{ label: 'name', value: 'name' }}
            options={versionList}
          />
          <Button type="default" onClick={showModal} icon={<KFIcon type="icon-xinjian2" />}>
            创建新版本
          </Button>
          <Button
            type="default"
            style={{ marginLeft: '20px' }}
            icon={<KFIcon type="icon-banbenduibi" />}
            onClick={showVersionSelector}
          >
            版本对比
          </Button>
          <Button
            type="default"
            style={{ marginLeft: '20px' }}
            onClick={handleDelete}
            icon={<KFIcon type="icon-shanchu" />}
            disabled={!version}
            danger
          >
            删除版本
          </Button>
        </Flex>
      </div>
      <div className={styles['resource-info__bottom']}>
        <Tabs activeKey={activeTab} items={items} onChange={(key) => setActiveTab(key)}></Tabs>
        <div className={styles['resource-info__bottom__legend']}>
          {activeTab === ResourceInfoTabKeys.Evolution && <GraphLegend />}
        </div>
      </div>
    </div>
  );
};
export default ResourceInfo;
