<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" :style="{ height: '70px' }">
          <el-row :gutter="20" align="middle">
            <!-- 内容总数 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="totalNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">文件总数</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 图片总数 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="imageNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">图片总数</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 视频总数 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="videoNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">视频总数</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 其它文件 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="otherNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">其它</div>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </el-card>
        <el-card shadow="hover" :style="{ marginTop: '10px', height: '60px' }">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="40px">
            <el-form-item label="名称" prop="originalName">
              <el-input v-model="queryParams.originalName" placeholder="请输入文件名" clearable style="width: 150px" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="queryParams.type" style="width: 150px" placeholder="请选择类型" clearable>
                <el-option v-for="dict in smsb_source_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="分类" prop="tag">
              <el-select v-model="queryParams.tag" style="width: 150px" placeholder="请选择分类" clearable>
                <el-option v-for="dict in smsb_source_classify" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="目录" prop="treeId">
              <el-tree-select v-model="queryParams.treeId" :data="sourceTreeOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择归属目录"
                check-strictly @change="handleQuery" style="width: 200px" clearable />
            </el-form-item>
            <el-form-item label="时间" style="width: 250px">
              <el-date-picker v-model="dateRangeCreateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['source:minioData:add']"> 上传
              </el-button>
              <el-button type="primary" plain icon="Switch" @click="handleTrans" v-hasPermi="['source:minioData:add']">
                转码进度
              </el-button>
              <!--              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['source:minioData:edit']"
                              >修改
                            </el-button>
                            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['source:minioData:remove']"
                              >删除
                            </el-button>-->
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <div class="table-content">
        <el-table v-loading="loading" :data="minioDataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="资源" align="left" prop="keyName" width="200" :show-overflow-tooltip="true" />
          <el-table-column label="类型" align="center" prop="type" width="120">
            <template #default="scope">
              <dict-tag :options="smsb_source_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="原名" align="left" prop="originalName" width="150" :show-overflow-tooltip="true" />
          <el-table-column label="大小" align="left" prop="size" />
          <el-table-column label="分辨率" align="left" prop="resolution" />
          <el-table-column label="码率(kbps)" align="left" prop="codeRate" />
          <el-table-column label="时长" align="left" prop="durationStr" />
          <el-table-column label="预览" align="center" prop="screenshot">
            <template #default="scope">
              <div v-if="scope.row.type === 1">
                <!-- 图片类型 -->
                <image-preview :src="scope.row.screenshot" style="width: 40px; height: 40px; cursor: pointer" />
              </div>
              <div v-else-if="scope.row.type === 2">
                <!-- 视频类型 -->
                <!-- <image-preview :src="scope.row.screenshot" style="width: 40px; height: 40px; cursor: pointer" -->
                <!-- @click="viewVideo(scope.row.url)" /> -->
                <el-icon class="VideoPlay" @click="viewVideo(scope.row.screenshot)" size="40" style="cursor: pointer">
                  <VideoPlay />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="转码" align="center" prop="transState">
            <template #default="scope">
              <dict-tag :options="smsb_trans_result" :value="scope.row.transState" />
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center" prop="tag">
            <template #default="scope">
              <dict-tag :options="smsb_source_classify" :value="scope.row.tag" />
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="left" prop="createUser" />
          <el-table-column label="创建时间" align="left" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{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="['source:minioData:edit']"></el-button>
                        </el-tooltip>-->
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['source:minioData:remove']"></el-button>
              </el-tooltip>
              <el-tooltip content="引用情况" placement="top">
                <el-button link type="primary" icon="List" @click="handleUse(scope.row)"
                  v-hasPermi="['source:minioData:edit']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <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" append-to-body
      :style="{ maxWidth: '90vw', maxHeight: '90vh' }">
      <el-row :gutter="20" style="display: flex">
        <el-col :span="10" style="height: 100%; overflow: auto; border-right: 1px solid #eee; padding-right: 10px">
          <el-tree ref="sourceTreeRef" :data="sourceTreeOptions" show-checkbox node-key="id"
            :props="{ value: 'id', label: 'name', children: 'children' }" :check-strictly="true"
            :default-expand-all="true" @check="handleTreeCheck" style="height: 100%"></el-tree>
        </el-col>
        <el-col :span="14"
          style="height: 100%; display: flex; flex-direction: column; overflow: auto; padding-left: 10px">
          <el-form ref="minioDataFormRef" :model="form" :rules="rules" label-width="80px"
            style="flex: 1 1 auto; height: 100%; display: flex; flex-direction: column">
            <el-form-item label="分类" prop="tag">
              <el-select v-model="form.tag" placeholder="请选择分类">
                <el-option v-for="dict in smsb_source_classify" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label=""
              style="flex: 1 1 auto; display: flex; flex-direction: column; justify-content: flex-start">
              <!-- 原始上传组件保留，供参考：
              <smsb-file-upload v-model="form.ossId" />
              -->
              <!-- 替换为新版上传组件 SmsbFileUploader -->
              <SmsbFileUploader ref="fileUploaderRef" v-model="form.ossId" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <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>

    <!-- 转码进度弹窗 -->
    <el-dialog :title="trans.title" v-model="trans.visible" width="1000px" append-to-body :style="{ height: '700px' }">
      <el-card shadow="never">
        <div class="table-content">
          <el-table v-loading="loading" :data="transRecordList">
            <el-table-column label="资源名称" align="left" prop="fileName" width="200" :show-overflow-tooltip="true" />
            <el-table-column label="转码类型" align="center" prop="transType">
              <template #default="scope">
                <dict-tag :options="smsb_trans_type" :value="scope.row.transType" />
              </template>
            </el-table-column>
            <el-table-column label="转码进度" align="center" prop="transProgress">
              <template #default="scope">
                <dict-tag :options="smsb_trans_progress" :value="scope.row.transProgress" />
              </template>
            </el-table-column>
            <el-table-column label="转码结果" align="center" prop="result">
              <template #default="scope">
                <dict-tag :options="smsb_trans_result" :value="scope.row.result" />
              </template>
            </el-table-column>
            <el-table-column label="用户名" align="left" prop="createUser" width="100" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="left" prop="createTime" width="160" />
          </el-table>
        </div>
        <pagination v-show="transTotal > 0" :total="transTotal" v-model:page="transQueryParams.pageNum"
          v-model:limit="transQueryParams.pageSize" @pagination="getTransList" />
      </el-card>
    </el-dialog>

    <!-- 用于展示播放的视频 -->
    <el-dialog v-model="videoDialogVisible">
      <video width="100%" controls :src="videoUrl"></video>
    </el-dialog>

    <!-- 引用情况弹窗 -->
    <el-dialog :title="useDialog.title" v-model="useDialog.visible" width="1000px" append-to-body
      :style="{ height: '700px' }">
      <el-card shadow="never">
        <div class="table-content" style="min-height: 525px">
          <el-table v-loading="loading" :data="itemRecordList">
            <el-table-column label="名称" align="left" prop="itemName" />
            <el-table-column label="类型" align="center" prop="itemType" width="100">
              <template #default="scope">
                <dict-tag :options="smsb_item_type" :value="scope.row.itemType" />
              </template>
            </el-table-column>
            <el-table-column label="分屏" align="center" prop="splitScreen" width="100">
              <template #default="scope">
                <span v-if="scope.row.splitScreen == 0"> --- </span>
                <dict-tag v-else :options="smsb_split_screen" :value="scope.row.splitScreen" />
              </template>
            </el-table-column>
            <el-table-column label="资源数量" align="center" prop="sourceNum" width="100" />
            <el-table-column label="创建人" align="left" prop="createUser" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="left" prop="createTime" width="160" />
          </el-table>
        </div>
        <pagination v-show="itemTotal > 0" :total="itemTotal" v-model:page="dialogQueryParams.pageNum"
          v-model:limit="dialogQueryParams.pageSize" @pagination="getItemListByFileId" />
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup name="MinioData" lang="ts">
import SmsbFileUploader from '@/components/SmsbFileUpload/SmsbFileUploader.vue';
import { listMinioData, getMinioData, delMinioData, addMinioData, updateMinioData, fileStatistics } from '@/api/smsb/source/minioData';
import { MinioDataVO, MinioDataQuery, MinioDataForm } from '@/api/smsb/source/minioData_type';
import { listSourceTree } from '@/api/smsb/source/sourceTree';
import { listMinioTransRecord } from '@/api/smsb/source/transRecord';
import { MinioTransRecordQuery, MinioTransRecordVO } from '@/api/smsb/source/transRecord_type';
import { ItemQuery, ItemVO } from '@/api/smsb/source/item_type';
import { itemListByFileId } from '@/api/smsb/source/item';

type SourceTreeOption = {
  id: number;
  name: string;
  children?: SourceTreeOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { smsb_source_classify, smsb_source_type, smsb_trans_type, smsb_trans_progress, smsb_trans_result, smsb_item_type, smsb_split_screen } =
  toRefs<any>(
    proxy?.useDict(
      'smsb_source_classify',
      'smsb_source_type',
      'smsb_trans_type',
      'smsb_trans_progress',
      'smsb_trans_result',
      'smsb_item_type',
      'smsb_split_screen'
    )
  );
const minioDataList = ref<MinioDataVO[]>([]);
const transRecordList = ref<MinioTransRecordVO[]>([]);
const itemRecordList = ref<ItemVO[]>([]);
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 transTotal = ref(0);
const itemTotal = ref(0);
const sourceTreeOptions = ref<SourceTreeOption[]>([]);
const queryFormRef = ref<ElFormInstance>();
const minioDataFormRef = ref<ElFormInstance>();
const totalNum = ref(0);
const imageNum = ref(0);
const videoNum = ref(0);
const otherNum = ref(0);
const videoDialogVisible = ref(false);
const videoUrl = ref('');
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const trans = reactive<DialogOption>({
  visible: false,
  title: ''
});
const useDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MinioDataForm = {
  tag: 1,
  marketing: undefined,
  ossId: undefined,
  sourceTreeIds: undefined
};
const data = reactive<PageData<MinioDataForm, MinioDataQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    originalName: undefined,
    type: undefined,
    tag: undefined,
    marketing: undefined,
    treeId: undefined,
    params: {}
  },
  rules: {}
});
const transData = reactive<TransPageData<MinioTransRecordQuery>>({
  transQueryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {}
  }
});
const itemData = reactive<DialogPageData<ItemQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 10,
    fileId: undefined,
    params: {}
  }
});
const { queryParams, form, rules } = toRefs(data);
const { transQueryParams } = toRefs(transData);
const { dialogQueryParams } = toRefs(itemData);

// 播放视频
const viewVideo = (url: string) => {
  videoUrl.value = url;
  console.log(videoUrl.value);
  videoDialogVisible.value = true;
};

/** 查询文件资源列表 */
const getList = async () => {
  loading.value = true;
  // const res = await listMinioData(queryParams.value);
  const res = await listMinioData(proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime'));
  minioDataList.value = res.rows;
  minioDataList.value.forEach((data) => {
    data.size = parseFloat(data.size / 1024).toFixed(3) + 'MB';
    const minutes = Math.floor(data.duration / 60); // 获取分钟数
    const remainingSeconds = data.duration % 60; // 获取剩余的秒数
    data.durationStr = `${minutes}分${remainingSeconds}秒`;
  });
  total.value = res.total;
  loading.value = false;
};

const getTransList = async () => {
  const res = await listMinioTransRecord(transQueryParams.value);
  transRecordList.value = res.rows;
  transTotal.value = res.total;
};

const getItemListByFileId = async () => {
  const res = await itemListByFileId(dialogQueryParams.value);
  itemRecordList.value = res.rows;
  itemTotal.value = res.total;
};

/** 查询文件目录下拉树结构 */
const getTreeselect = async () => {
  const res = await listSourceTree();
  sourceTreeOptions.value = [];
  const data: SourceTreeOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<SourceTreeOption>(res.data, 'id', 'parentId');
  sourceTreeOptions.value.push(data);
};

const handleTreeCheck = (_, { checkedKeys }) => {
  // 获取用户选中的节点（父节点和子节点不会关联）
  form.value.sourceTreeIds = checkedKeys;
  console.log('当前选中的文件:', form.value.sourceTreeIds);
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  videoDialogVisible.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  minioDataFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: MinioDataVO[]) => {
  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 handleTrans = () => {
  trans.visible = true;
  trans.title = '转码进度';
  getTransList();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MinioDataVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMinioData(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改文件资源';
};

const handleUse = async (row?: MinioDataVO) => {
  const fileId = row.id;
  useDialog.title = '资源引用';
  useDialog.visible = true;
  dialogQueryParams.value.fileId = fileId;
  getItemListByFileId();
};

/** 提交按钮 */
// 通过ref访问SmsbFileUploader实例
import { ref as vueRef } from 'vue';
const fileUploaderRef = vueRef();

const submitForm = () => {
  minioDataFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 调用文件上传逻辑（不关闭dialog）
      console.log('[submitForm] 尝试调用handleUpload', fileUploaderRef.value);
      if (fileUploaderRef.value && typeof fileUploaderRef.value.handleUpload === 'function') {
        await fileUploaderRef.value.handleUpload();
        console.log('[submitForm] handleUpload已调用');
      }
      // 下面的逻辑可以根据需要决定是否保留
      // if (form.value.id) {
      //   await updateMinioData(form.value).finally(() => (buttonLoading.value = false));
      // } else {
      //   await addMinioData(form.value).finally(() => (buttonLoading.value = false));
      // }
      buttonLoading.value = false;
      // 强制保持弹窗不关闭
      dialog.visible = true;
      // proxy?.$modal.msgSuccess('操作成功');
      // dialog.visible = false;
      // await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MinioDataVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除文件资源编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMinioData(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'source/minioData/export',
    {
      ...queryParams.value
    },
    `minioData_${new Date().getTime()}.xlsx`
  );
};
const getFileStatistics = async () => {
  const res = await fileStatistics();
  console.log(res.data);
  totalNum.value = res.data.totalNum;
  imageNum.value = res.data.imageNum;
  videoNum.value = res.data.videoNum;
  otherNum.value = res.data.otherNum;
};

onMounted(() => {
  getList();
  getTreeselect();
  getFileStatistics();
});
</script>

<style scoped>
:deep(.el-card__body) {
  padding: 10px !important;
}
</style>
