import { ProForm, ProFormGroup, ProFormText } from '@ant-design/pro-components';
import { Button, message, Space, Tag } from 'antd';
import type { RowSelectionType } from 'antd/es/table/interface';
import type { FormInstance } from 'antd/lib';
import dayjs from 'dayjs';
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import GroupTagModal from '@/components/GroupTag/GroupTagModal';
import type { TagItem } from '@/components/GroupTag/types';
import type { FileItem } from '@/components/RenameRule';
import {
  createSampleTag,
  createSampleTagGroup,
  deleteSample,
  deleteSampleTag,
  deleteSampleTagGroup,
  deleteSampleTagRelate,
  downloadSample,
  downloadZipFile,
  getSampleTagGroup,
  getSampleTagPage,
  relateSample,
  updateSamples,
  updateSampleTag,
  updateSampleTagGroup,
} from '@/services/ai/sample';
import TagManager from './components/tag-manager';

interface SampleTagDetailProps<T> {
  onRefresh?: (type?: string) => void;
  type: RowSelectionType;
  data?: T[];
}

const SampleTagDetail = <T extends Record<string, any>>(
  props: SampleTagDetailProps<T>,
) => {
  const formRef = useRef<FormInstance>(null);
  const { type = 'radio', data } = props;
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [tagManagerVisible, setTagManagerVisible] = useState<boolean>(false);
  const [value, setValue] = useState<{
    tagId?: number | number[];
    id?: number;
    remark?: string;
    sampleIds?: number[];
    tags?: TagItem[];
    updateTime?: number;
    createTime?: number;
    sampleSize?: number;
    sampleMineType?: string;
    sampleTime?: number;
  }>({});
  const handleAddTag = useCallback(() => {
    setModalVisible(true);
  }, [modalVisible]);

  // const radioData = data && data[0];

  // // 当 radioData 改变时更新表单值
  useEffect(() => {
    if (type === 'radio') {
      const item = data?.[0];
      setValue({ ...item, sampleIds: [item?.id] });
    } else {
      const sampleIds = data?.map((sample) => sample.id) || [];
      const tags = data?.map((sample) => {
        return sample.tags;
      });
      const map = new Map();
      const tags_total = tags
        ?.flat()
        .filter((v) => !map.has(v.id) && map.set(v.id, v));
      setValue({ tags: tags_total as TagItem[], sampleIds });
    }
  }, [type, data]);
  useEffect(() => {
    formRef.current?.setFieldsValue(value);
  }, [value]);

  const tagNames = useMemo<FileItem[]>(() => {
    return (
      data?.map((tag) => {
        return {
          id: tag.id,
          originalName: tag.sampleName,
        };
      }) || []
    );
  }, [data]);

  const onListAddTag = async (tags: TagItem[]) => {
    const sampleIds = data?.map((sample) => sample.id);
    const ids = tags?.map((tag) => tag.id);
    await relateSample({ tagId: ids, sampleIds: sampleIds as number[] });
    setModalVisible(false);
    const map = new Map();
    const newTags = [...(value.tags || []), ...tags];
    const tags_total = newTags
      ?.flat()
      .filter((v) => !map.has(v.id) && map.set(v.id, v));
    setValue({ ...value, tags: tags_total });
    // 执行刷新回调
    message.success('添加标签成功');
    if (props.onRefresh) {
      props.onRefresh();
    }
  };

  const handleDeleteAll = async () => {
    const ids = data?.map((sample) => sample.id);
    if (ids) {
      await deleteSample(ids.join(','));
      message.success('删除成功');

      if (props.onRefresh) {
        props.onRefresh('delete');
      }
    }
  };

  // 下载
  const handleDownloadAll = async () => {
    const ids = data?.map((sample) => sample.id) as number[];
    downloadZipFile(ids);
  };

  const handleTagManager = () => {
    setTagManagerVisible(true);
  };

  const forMap = (tags: TagItem[]) => (
    <div style={{ display: 'inline-block', marginBottom: 10 }}>
      {tags.map((tag) => (
        <Tag
          closable
          key={tag.id}
          style={{ marginBottom: 10 }}
          onClose={async (e) => {
            e.preventDefault();
            await deleteSampleTagRelate({
              sampleIds: value.sampleIds || [],
              tagId: [tag.id],
            });
            message.success('删除成功');
            props?.onRefresh?.();
            setValue({ ...value, tags: tags.filter((t) => t.id !== tag.id) });
          }}
        >
          {tag.tagName}
        </Tag>
      ))}
    </div>
  );

  const onRename = () => {
    props.onRefresh?.();
    setTagManagerVisible(false);
  };

  const onDownload = () => {
    const item = data?.[0];
    const link = document.createElement('a');
    link.href = item?.sampleFilePath;
    link.download = item?.sampleName; // 设置下载的文件名
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
  return (
    <>
      {data!.length > 0 ? (
        <>
          <ProForm name="validate_other" formRef={formRef} submitter={false}>
            {type === 'radio' && (
              <ProFormGroup title="预览">
                {data?.[0].sampleFilePath && (
                  <audio
                    controls
                    preload="true"
                    crossOrigin="anonymous"
                    style={{ marginBottom: 24 }}
                  >
                    <source src={data[0].sampleFilePath} />
                    <track kind="captions" />
                  </audio>
                )}
              </ProFormGroup>
            )}
            <ProFormGroup title="基本信息">
              {type === 'radio' && (
                <ProFormText
                  width="md"
                  name="sampleName"
                  placeholder="请输入样本名称"
                  fieldProps={{
                    onBlur: async (e) => {
                      if (e.target.value) {
                        const newData =
                          data?.map((sample) => {
                            return {
                              id: sample.id,
                              sampleName: e.target.value,
                            };
                          }) || [];
                        await updateSamples(newData);
                        props?.onRefresh?.();
                        message.success('更新样本名称成功');
                      }
                    },
                  }}
                  rules={[{ required: true, message: '样本名称不能为空' }]}
                />
              )}
              <ProFormText
                width="md"
                fieldProps={{
                  onBlur: async (e) => {
                    if (e.target.value) {
                      const newData =
                        data?.map((sample) => {
                          return {
                            id: sample.id,
                            remark: e.target.value,
                          };
                        }) || [];
                      await updateSamples(newData);
                      props?.onRefresh?.();
                      message.success('更新注释成功');
                    }
                  },
                }}
                name="remark"
                placeholder="请输入注释"
              />
            </ProFormGroup>

            <ProFormGroup title="标签">
              {/* <Form.Item name="tag"> */}
              {forMap(value.tags || [])}
            </ProFormGroup>
            <Button
              type="dashed"
              block
              style={{ marginBottom: 24 }}
              onClick={handleAddTag}
            >
              添加标签
            </Button>
            <ProFormGroup title="文本信息" block></ProFormGroup>
            <Space size={10} style={{ width: '100%', marginBottom: 12 }}>
              <span>添加日期: </span>
              <span>
                {dayjs(value.createTime).format('YYYY-MM-DD HH:mm:ss')}
              </span>
            </Space>
            <Space size={10} style={{ width: '100%', marginBottom: 12 }}>
              <span>修改日期</span>
              <span>
                {dayjs(value.updateTime).format('YYYY-MM-DD HH:mm:ss')}
              </span>
            </Space>
            <Space size={10} style={{ width: '100%', marginBottom: 12 }}>
              <span>文件大小: </span>
              <span>{value.sampleSize}</span>
            </Space>
            <Space size={10} style={{ width: '100%', marginBottom: 12 }}>
              <span>格式: </span>
              <span>{value.sampleMineType}</span>
            </Space>

            {type === 'checkbox' && (
              <>
                <ProFormGroup title="其他"></ProFormGroup>
                <Button
                  block
                  style={{ marginBottom: 24 }}
                  onClick={handleTagManager}
                >
                  批量重命名
                </Button>
                <Button
                  block
                  style={{ marginBottom: 24 }}
                  onClick={handleDownloadAll}
                >
                  下载到本地
                </Button>
                <Button
                  block
                  color="danger"
                  style={{ marginBottom: 24 }}
                  onClick={handleDeleteAll}
                >
                  删除样本
                </Button>
              </>
            )}
          </ProForm>
          <GroupTagModal
            visible={modalVisible}
            onCancel={() => setModalVisible(false)}
            onChange={onListAddTag}
            editable={false}
            value={value?.tags}
            request={{
              groupsApi: {
                get: getSampleTagGroup,
                create: createSampleTagGroup,
                delete: deleteSampleTagGroup,
                update: updateSampleTagGroup,
              },
              tagsApi: {
                get: getSampleTagPage,
                create: createSampleTag,
                delete: deleteSampleTag,
                update: updateSampleTag,
              },
            }}
            title="管理技术标签"
            width={800}
            height={500}
          />
          <TagManager
            visible={tagManagerVisible}
            files={tagNames}
            onOk={onRename}
            onCancel={() => setTagManagerVisible(false)}
          ></TagManager>
          {type === 'radio' && (
            <Space
              style={{ width: '100%', justifyContent: 'center', padding: 12 }}
            >
              <Button color="danger" onClick={onDownload}>
                下载
              </Button>
              <Button color="danger" variant="solid" onClick={handleDeleteAll}>
                删除
              </Button>
            </Space>
          )}
        </>
      ) : (
        '暂无数据-请选择样本'
      )}
    </>
  );
};

export default React.memo(SampleTagDetail) as <T extends Record<string, any>>(
  props: SampleTagDetailProps<T>,
) => React.ReactElement;
