<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover"> </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="File" @click="handleAdd" v-hasPermi="['physical:mediaResource:add']">上传文件</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:mediaResource:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:mediaResource:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="mediaResourceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="true" />
        <el-table-column label="业务类型" align="center">
          <template #default="{ row }">
            <span v-if="row.bizType === 'member_type'">会员</span>
            <span v-else-if="row.bizType === 'charge_points'">视频点</span>
            <span v-else>{{ row.bizType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.fileType === 'IMAGE' && scope.row.fileUrl"
              :src="scope.row.fileUrl"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.fileUrl]"
              :preview-teleported="true"
              fit="cover"
            />
            <video
              v-else-if="scope.row.fileType === 'VIDEO' && scope.row.fileUrl"
              :src="scope.row.fileUrl"
              controls
              style="width: 80px; height: 60px"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="文件类型" align="center">
          <template #default="{ row }">
            <span v-if="row.fileType === 'IMAGE'">图片</span>
            <span v-else-if="row.fileType === 'VIDEO'">视频</span>
            <span v-else>{{ row.fileType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" align="center" prop="fileName" />
        <el-table-column label="文件大小" align="center">
          <template #default="{ row }">
            <span>{{ (row.fileSize / 1024).toFixed(2) }} KB</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['physical:mediaResource:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['physical:mediaResource:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改通用媒体资源对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="mediaResourceFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件" prop="fileUrl">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleFileUrlChange"
              :on-remove="handleFileUrlRemove"
              :file-list="fileUrlFileList"
              :auto-upload="false"
              :limit="1"
              :accept="queryParams.fileType === 'IMAGE' ? 'image/*' : queryParams.fileType === 'VIDEO' ? 'video/*' : 'image/*,video/*'"
            >
              <template #trigger>
                <el-button type="primary">点击选择文件</el-button>
              </template>

              <template #default>
                <div class="preview-area">
                  <img
                    v-if="fileType === 'IMAGE' && (fileUrlPreviewUrl || form.tempFileUrl)"
                    :src="fileUrlPreviewUrl || form.tempFileUrl"
                    alt="预览图"
                    style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer"
                    @click="handleFileUrlPreviewClick"
                  />
                  <video
                    v-else-if="fileType === 'VIDEO' && (fileUrlPreviewUrl || form.tempFileUrl)"
                    :src="fileUrlPreviewUrl || form.tempFileUrl"
                    controls
                    style="max-width: 300px; max-height: 200px; margin-top: 10px"
                  />
                  <div v-else style="margin-top: 10px; color: #999">无文件</div>
                </div>
              </template>

              <template #tip>
                <div class="el-upload__tip">
                  <span v-if="fileUrlFileList.length > 0">当前已选文件：{{ fileUrlFileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MediaResource" lang="ts">
import { listMediaResource, getMediaResource, delMediaResource, addMediaResource, updateMediaResource } from '@/api/system/physical/mediaResource';
import { MediaResourceVO, MediaResourceQuery, MediaResourceForm } from '@/api/system/physical/mediaResource/types';
import { uploadTournament } from '@/api/system/business/tournaments';
import { uploadVideo } from '@/api/system/physical/videoContent';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const mediaResourceList = ref<MediaResourceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const mediaResourceFormRef = ref<ElFormInstance>();
// 文件上传相关
const fileUrlFileList = ref<any[]>([]);
const fileUrlPreviewUrl = ref('');
const fileType = ref('');
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MediaResourceForm = {
  id: undefined,
  bizType: undefined,
  bizId: undefined,
  fileType: undefined,
  fileUrl: undefined,
  fileName: undefined,
  fileSize: undefined,
  mimeType: undefined,
  width: undefined,
  height: undefined,
  status: undefined,
  createdAt: undefined,
  updatedAt: undefined
};
const data = reactive<PageData<MediaResourceForm, MediaResourceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bizType: undefined,
    bizId: undefined,
    fileType: undefined,
    fileUrl: undefined,
    fileName: undefined,
    fileSize: undefined,
    mimeType: undefined,
    width: undefined,
    height: undefined,
    status: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    bizType: [{ required: true, message: '业务类型，如 recharge_proof, member_avatar不能为空', trigger: 'change' }],
    fileType: [{ required: true, message: '文件类型：IMAGE, VIDEO不能为空', trigger: 'change' }],
    fileUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '1=有效，2=已删除不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询通用媒体资源列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMediaResource(queryParams.value);
  mediaResourceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  mediaResourceFormRef.value?.resetFields();
  fileUrlFileList.value = [];
  fileUrlPreviewUrl.value = '';
  fileType.value = '';
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MediaResourceVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MediaResourceVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMediaResource(_id);
  Object.assign(form.value, res.data);
  fileType.value = res.data.fileType;

  if (res.data.fileUrl) {
    fileUrlFileList.value = [
      {
        name: '已上传文件',
        url: res.data.fileUrl,
        status: 'success'
      }
    ];
    fileUrlPreviewUrl.value = res.data.fileUrl;
  }

  dialog.visible = true;
  dialog.title = '修改';
};

/** 提交按钮 */
const submitForm = () => {
  mediaResourceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 补充文件信息
        if (fileUrlFileList.value.length > 0) {
          const fileItem = fileUrlFileList.value[0];
          form.value.fileType = fileType.value;
          form.value.fileName = fileItem.name;
          form.value.fileSize = fileItem.size || 0;
          form.value.mimeType = fileItem.raw?.type || '';
        }
        form.value.bizType = queryParams.value.bizType;
        if (form.value.id) {
          await updateMediaResource(form.value).finally(() => (buttonLoading.value = false));
        } else {
          await addMediaResource(form.value).finally(() => (buttonLoading.value = false));
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('提交失败:', error);
        proxy?.$modal.msgError('提交失败，请重试');
        buttonLoading.value = false;
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: MediaResourceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMediaResource(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/mediaResource/export',
    {
      ...queryParams.value
    },
    `mediaResource_${new Date().getTime()}.xlsx`
  );
};
onMounted(() => {
  const route = proxy?.$route;
  if (route.query.fileType) {
    queryParams.value.fileType = String(route.query.fileType);
  }
  if (route.query.bizType) {
    queryParams.value.bizType = String(route.query.bizType);
  }
  getList();
});
watch(
  () => proxy?.$route.query,
  (newQuery, oldQuery) => {
    if (newQuery && newQuery !== oldQuery) {
      if (newQuery.fileType) {
        queryParams.value.fileType = String(newQuery.fileType);
      } else {
        queryParams.value.fileType = undefined;
      }
      if (newQuery.bizType) {
        queryParams.value.bizType = String(newQuery.bizType);
      } else {
        queryParams.value.bizType = undefined;
      }
      queryParams.value.pageNum = 1;
      getList();
    }
  },
  { deep: true }
);
// 文件移除处理
const handleFileUrlRemove = () => {
  fileUrlFileList.value = [];
  fileUrlPreviewUrl.value = '';
  fileType.value = '';
  form.value.fileUrl = '';
};
// 文件预览点击
const handleFileUrlPreviewClick = () => {
  if (fileUrlPreviewUrl.value || form.value.fileUrl) {
    if (fileType.value === 'IMAGE') {
      ElMessageBox.alert(`<img src="${fileUrlPreviewUrl.value || form.value.fileUrl}" style="max-width: 100%;" />`, '文件预览', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      });
    } else if (fileType.value === 'VIDEO') {
      ElMessageBox.alert(`<video src="${fileUrlPreviewUrl.value || form.value.fileUrl}" controls style="max-width: 100%;"></video>`, '文件预览', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      });
    }
  }
};
// 文件上传处理
const handleFileUrlChange = async (file: any) => {
  const index = fileUrlFileList.value.findIndex((f) => f.uid === file.uid);
  fileUrlFileList.value = [];
  if (queryParams.value.fileType === 'VIDEO' && queryParams.value.bizType === 'charge_points') {
    const hasVideo = mediaResourceList.value.some((item) => item.fileType === 'VIDEO' && item.bizType === 'charge_points');
    if (hasVideo) {
      proxy?.$modal.msgWarning('视频不允许上传多条，已存在一条，请先删除现有视频后再上传');
      form.value.fileUrl = undefined;
      return;
    }
  }
  if (file.raw) {
    fileUrlPreviewUrl.value = URL.createObjectURL(file.raw);
    // 判断文件类型
    if (file.raw.type.startsWith('image/')) {
      fileType.value = 'IMAGE';
    } else if (file.raw.type.startsWith('video/')) {
      fileType.value = 'VIDEO';
    }
  }

  if (index === -1) {
    fileUrlFileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    // 根据文件类型选择不同的上传接口
    let res;
    if (fileType.value === 'VIDEO') {
      res = await uploadVideo(rawFile);
    } else {
      res = await uploadTournament(rawFile);
    }
    if (res.code === 200) {
      // 根据文件类型选择不同的 URL 字段 res.data.tempUrl
      let fileUrl;
      let tempFileUrl;
      if (fileType.value === 'VIDEO') {
        tempFileUrl = res.data.tempUrl;
        fileUrl = res.data.url;
      } else {
        tempFileUrl = res.data.url;
        fileUrl = res.data.url;
      }
      fileUrlFileList.value[index] = {
        ...file,
        status: 'success',
        response: tempFileUrl
      };
      form.value.fileUrl = fileUrl;
      form.value.tempFileUrl = tempFileUrl;
      form.value.fileType = fileType.value;
      form.value.ossId = res.data.ossId;
      fileUrlPreviewUrl.value = fileUrlFileList.value[index].response;
      proxy?.$modal.msgSuccess('文件上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    fileUrlFileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    proxy?.$modal.msgError('文件上传失败，请重试');
  }
};
</script>
