<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="80px"
    >
      <!-- <el-form-item label="课件类型">
        <el-select
          v-model="queryParams.tag_id"
          placeholder="请选择课件类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="tab in tablist"
            :key="tab._id"
            :label="tab.name"
            :value="tab._id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="课件类型">
        <el-cascader
          v-model="queryParams.tag_id"
          :options="treeData"
          placeholder="请选择课件类型"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="文件类型">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择文件类型"
          clearable
          style="width: 240px"
        >
          <el-option label="视频" :value="0" />
          <el-option label="音频" :value="1" />
          <el-option label="PDF" :value="2" />
          <el-option label="PPT" :value="3" />
          <el-option label="图文" :value="4" />
          <el-option label="Excel" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="发布者">
        <el-input
          v-model="queryParams.publisher"
          placeholder="请输入发布者"
          clearable
        />
      </el-form-item>
      <el-form-item label="文件名">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名"
          clearable
        />
      </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-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col> -->
    </el-row>

    <!-- 文件表格 -->
    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
      row-key="_id"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column
        type="index"
        label="序号"
        width="60"
        :index="
          (index) =>
            (queryParams.pageNum - 1) * queryParams.pageSize + index + 1
        "
      />
      <!-- 展开二级表格 -->
      <el-table-column type="expand">
        <template #default="scope">
          <el-table
            v-if="scope.row.type === 4"
            :data="scope.row.children"
            border
            style="width: 85%; margin-left: 7.5%"
          >
            <el-table-column
              label="图片"
              align="center"
              key="url"
              prop="url"
              width="130"
            >
              <template #default="scope">
                <el-image
                  style="
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    border-radius: 4px;
                  "
                  :src="scope.row.url"
                  fit="cover"
                />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="describe" label="描述" />
            <el-table-column align="center" prop="sort" label="排序" />
            <el-table-column align="center" prop="createdAt" label="创建时间" />
            <el-table-column label="操作" align="center" width="150">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleUpdate2(scope.row)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete2(scope.row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="课件类型" align="center">
        <template #default="scope">
          {{
            tablist.find((tab) => tab._id === scope.row.tag_id)?.name ||
            "未知类型"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="封面图片"
        align="center"
        key="url"
        prop="cover"
        width="130"
      >
        <template #default="scope">
          <el-image
            style="
              width: 100%;
              height: 100%;
              object-fit: cover;
              border-radius: 4px;
            "
            :src="scope.row.cover"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="课件名称" />
      <el-table-column prop="publisher" label="发布者" />
      <el-table-column label="文件类型" align="center">
        <template #default="scope">
          {{ fileTypeMap[scope.row.type] || "未知类型" }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" />
      <el-table-column prop="download_count" label="下载人数" />
      <el-table-column
        label="创建时间"
        align="center"
        key="createdAt"
        prop="createdAt"
      >
        <template #default="scope">
          <span>{{ formatTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-tooltip
            content="图文新增"
            v-if="scope.row.type === 4"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="CirclePlus"
              @click="handleAddChild(scope.row)"
            />
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
            />
          </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-dialog :title="title" v-model="open" width="600px">
      <el-form :model="form" :rules="rules" ref="userRef" label-width="100px">
        <el-form-item v-if="!tuwenadd" label="课件类型" prop="tag_id">
        <el-cascader
          v-model="form.tag_id"
          :options="treeData"
          placeholder="请选择课件类型"
          clearable
          style="width: 240px"
          :disabled="isEdit"
        />
      </el-form-item>
        <!-- <el-form-item v-if="!tuwenadd" label="课件类型" prop="tag_id">
          <el-select
            v-model="form.tag_id"
            placeholder="请选择"
            clearable
            style="width: 240px"
            :disabled="isEdit"
          >
            <el-option
              v-for="tab in tablist"
              :key="tab._id"
              :label="tab.name"
              :value="tab._id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item v-if="!tuwenadd" label="文件类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择"
            clearable
            style="width: 240px"
            :disabled="isEdit"
          >
            <el-option label="视频" :value="0" />
            <el-option label="音频" :value="1" />
            <el-option label="PDF" :value="2" />
            <el-option label="PPT" :value="3" />
            <el-option label="图文" :value="4" />
            <el-option label="Excel" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!tuwenadd && showDan" label="等级" prop="dan">
          <el-select v-model="form.dan" placeholder="请选择">
            <el-option label="初级" :value="0" />
            <el-option label="中级" :value="1" />
            <el-option label="高级" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!tuwenadd" label="适用范围" prop="range">
          <el-select 
            v-model="form.range" 
            placeholder="请选择" 
            multiple 
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option label="小班" value="小班" />
            <el-option label="中班" value="中班" />
            <el-option label="大班" value="大班" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!tuwenadd && showLevel" label="段位" prop="level">
          <el-select v-model="form.level" placeholder="请选择">
            <el-option label="1段" :value="1" />
            <el-option label="2段" :value="2" />
            <el-option label="3段" :value="3" />
            <el-option label="4段" :value="4" />
            <el-option label="5段" :value="5" />
            <el-option label="6段" :value="6" />
            <el-option label="7段" :value="7" />
            <el-option label="8段" :value="8" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!tuwenadd" label="发布者" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入发布者" />
        </el-form-item>
        <el-form-item v-if="!tuwenadd" label="文件名" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名" />
        </el-form-item>
        <!-- 封面上传 -->
        <el-form-item :label="tuwenadd ? '图文详情' : '封面'" prop="cover">
          <el-upload
            class="avatar-uploader"
            list-type="picture-card"
            :file-list="coverList"
            :auto-upload="false"
            :before-upload="beforeUploadCover"
            :on-change="handleUploadCover"
            :on-remove="handleRemoveCover"
            :on-preview="handlePreview"
            :limit="1"
          >
            <el-icon v-if="coverList.length === 0"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <!-- 文件上传 -->
        <el-form-item
          v-if="form.tag_id !== 'C05HFKY0YY' && !tuwenadd"
          label="文件上传"
          prop="url"
        >
          <el-upload
            class="avatar-uploader"
            list-type="text"
            :file-list="fileList"
            :auto-upload="false"
            :before-upload="beforeUploadFile"
            :on-change="handleUploadFile"
            :on-remove="handleRemoveFile"
            :on-preview="handlePreview"
            :limit="1"
          >
            <el-button>选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="!tuwenadd" label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="tuwenadd" label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item v-if="tuwenadd" label="描述">
          <el-input
            v-model="form.describe"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import moment from "moment";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const tablist = ref([]); // 课件类型 平面数据
const treeData = ref([]); // 课件类型 树形数据
const open = ref(false);
const loading = ref(false);
const total = ref(0);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const fileList = ref([]);
const userRef = ref(null);
const loadlist = ref([]);
const coverList = ref([]);
const tuwenadd = ref(false);
const isEdit = ref(false);

// 动手动脑图库对应 tag_id 为 'C05HDKNBDS', 全脑对应 'C05HFKY0YY'
const showDan = computed(() => {
  return form.value.tag_id === "C05HDKNBDS";
});
const showLevel = computed(() => {
  return (
    form.value.tag_id === "C05HDKNBDS" || form.value.tag_id === "C05HFKY0YY"
  );
});

const fileTypeMap = ref({
  0: "视频",
  1: "音频",
  2: "PDF",
  3: "PPT",
  4: "图文",
  5: "Excel",
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tag_id: null,
    type: undefined,
    publisher: "",
    name: "",
  },
  form: {
    _id: undefined,
    tag_id: undefined,
    type: undefined,
    dan: undefined,
    range: [],
    level: undefined,
    remark: "",
    publisher: "",
    name: "",
    cover: "",
    url: [],
    children: [],
  },
  rules: {
    tag_id: [{ required: true, message: "展示位置不能为空", trigger: "blur" }],
    type: [{ required: true, message: "请选择文件类型", trigger: "blur" }],
    dan: [{ required: true, message: "请选择等级", trigger: "blur" }],
    range: [{ required: true, message: "请选择使用范围", trigger: "blur" }],
    level: [{ required: true, message: "请选择段位", trigger: "blur" }],
    publisher: [
      { required: true, message: "请输入发布者（原创）", trigger: "blur" },
    ],
    name: [{ required: true, message: "请输入课件名称", trigger: "blur" }],
    cover: [{ required: true, message: "请上传图片", trigger: "blur" }],
    url: [{ required: true, message: "请上传课件文件", trigger: "blur" }],
    sort: [{ required: true, message: "请选择排序", trigger: "blur" }],
  },
});

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

// 获取课件类型
async function gettab() {
  const { data } = await proxy.$models.tab.list({
    filter: {
      where: {
        position: proxy.$_.neq(4),
      },
    },
    pageSize: 100,
    pageNumber: 1,
    getCount: true,
    envType: "prod",
  });
  const records = data.records || [];
  tablist.value = records;
  // 树形结构数据转换完成
  treeData.value = buildTree(records);

  console.log(treeData.value, 'treeData.valuetreeData.value');
  console.log(tablist.value, 'tablist.valuetablist.value');
}

// 把 name 字段转换成树（保持叶子为原始 _id）
function buildTree(dataList) {
  const root = [];

  dataList.forEach(item => {
    const name = (item.name || "").trim();
    if (!name) return;

    // 情况 1：含斜杠 " / "（优先处理为 顶级 / 副部分）
    if (name.includes("/")) {
      const [topRaw, restRaw] = name.split("/").map(s => s.trim());
      const topLabel = topRaw;
      const rest = (restRaw || "").trim();

      // rest 可能包含 "-"，拆成 二级 / 三级
      let midLabel = rest;
      let leafLabel = null;
      if (rest.includes("-")) {
        const parts = rest.split("-").map(s => s.trim());
        midLabel = parts[0];
        leafLabel = parts.slice(1).join("-").trim(); // 防止中间有多余 '-'
      }

      // 找或创建顶级节点
      let topNode = root.find(n => n.label === topLabel);
      if (!topNode) {
        topNode = { label: topLabel, value: topLabel, children: [] };
        root.push(topNode);
      }

      if (leafLabel) {
        // 顶级 -> 二级 -> 三级(叶子，用原始 _id)
        let midNode = topNode.children.find(n => n.label === midLabel);
        if (!midNode) {
          midNode = { label: midLabel, value: `${topLabel}/${midLabel}`, children: [] };
          topNode.children.push(midNode);
        }
        // 叶子节点（value 为原始 item._id）
        if (!midNode.children.find(n => n.label === leafLabel)) {
          midNode.children.push({ label: leafLabel, value: item._id });
        }
      } else {
        // 没有 '-'，把 rest 当作二级并直接作为叶子（value = _id）
        let midNode = topNode.children.find(n => n.label === midLabel);
        if (!midNode) {
          midNode = { label: midLabel, value: item._id, children: [] };
          topNode.children.push(midNode);
        } else {
          // 如果之前存在且是容器（有 children），就保留；否则覆盖 value 为 _id（确保能作为叶子）
          if (!midNode.children || midNode.children.length === 0) {
            midNode.value = item._id;
          }
        }
      }

    } else if (name.includes("-")) {
      // 情况 2：没有 '/'，但有 '-' -> 当作 二级结构 "X - Y"
      const parts = name.split("-").map(s => s.trim());
      const topLabel = parts[0];
      const leafLabel = parts.slice(1).join("-").trim();

      let topNode = root.find(n => n.label === topLabel);
      if (!topNode) {
        topNode = { label: topLabel, value: topLabel, children: [] };
        root.push(topNode);
      }
      if (!topNode.children.find(n => n.label === leafLabel)) {
        topNode.children.push({ label: leafLabel, value: item._id });
      }

    } else {
      // 情况 3：单层（直接叶子）
      let node = root.find(n => n.label === name);
      if (!node) {
        root.push({ label: name, value: item._id, children: [] });
      } else {
        // 如果已存在且之前是占位（无 value 或不是 id），尽量保留 children，不随便覆盖为 _id
        if ((!node.children || node.children.length === 0) && node.value !== item._id) {
          node.value = item._id;
        }
      }
    }
  });

  return root;
}

/** 获取临时图片链接 */
async function getTempUrls(fileIds) {
  if (!fileIds?.length) return [];
  const res = await proxy.$apps.getTempFileURL({ fileList: fileIds });
  return res.fileList.map((item) => ({
    fileID: item.fileID,
    tempFileURL: item.tempFileURL,
  }));
}

// 获取文件列表
async function getList() {
  loading.value = true;
  const filter = { where: {} };
  // if (queryParams.value.tag_id) filter.where.tag_id = queryParams.value.tag_id;
  if (queryParams.value.tag_id && Array.isArray(queryParams.value.tag_id) && queryParams.value.tag_id.length > 0) {
  filter.where.tag_id = queryParams.value.tag_id[queryParams.value.tag_id.length - 1];
}
  if (queryParams.value.type !== undefined)
    filter.where.type = queryParams.value.type;
  if (queryParams.value.publisher)
    filter.where.publisher = queryParams.value.publisher;
  if (queryParams.value.name) filter.where.name = queryParams.value.name;

  const { data } = await proxy.$models.file_manage.list({
    filter,
    pageSize: queryParams.value.pageSize,
    pageNumber: queryParams.value.pageNum,
    getCount: true,
    envType: "prod",
  });

  if (data.records?.length) {
    // 获取 cloud:// 临时链接
    const fileIds = data.records
      .map((r) => r.cover)
      .filter((cover) => cover && cover.startsWith("cloud://"));
    const urlMap = await getTempUrls(fileIds);

    data.records.forEach((r) => {
      const match = urlMap.find((u) => u.fileID === r.cover);
      if (match) r.cover = match.tempFileURL;
    });

    // 获取 wx_details 数据
    const fileIdList = data.records.map((r) => r._id);
    const { data: detailsData } = await proxy.$models.wx_details.list({
      filter: { where: { file_manage_id: proxy.$_.in(fileIdList) } },
      pageSize: 100000,
      pageNumber: 1,
      getCount: true,
      envType: "prod",
    });

    // 获取 wx_details 中 url 的临时链接
    const wxFileIds = detailsData.records
      .map((d) => d.url)
      .filter((url) => url && url.startsWith("cloud://"));

    const wxUrlMap = await getTempUrls(wxFileIds);

    // 挂载 children
    data.records.forEach((r) => {
      r.children =
        detailsData.records
          .filter((d) => d.file_manage_id === r._id)
          .map((d) => {
            const match = wxUrlMap.find((u) => u.fileID === d.url);
            if (match) d.url = match.tempFileURL;
            return d;
          }) || [];
    });

    userList.value = data.records;
    total.value = data.total;
  } else {
    userList.value = [];
    total.value = 0;
  }
  loading.value = false;
}

/** 时间格式化 */
function formatTime(timestamp) {
  return timestamp ? moment(timestamp).format("YYYY-MM-DD HH:mm:ss") : "";
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    tag_id: null,
    type: undefined,
    publisher: "",
    name: "",
  };
  getList();
}

function handleSelectionChange(selection) {
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  Object.assign(form.value, {
    _id: undefined,
    tag_id: undefined,
    type: undefined,
    dan: undefined,
    range: [],
    level: undefined,
    remark: "",
    publisher: "",
    name: "",
    cover: "",
    url: [],
    children: [],
    describe: "",
    file_manage_id: undefined,
    sort: undefined,
  });
  coverList.value = [];
  fileList.value = [];
  open.value = true;
  tuwenadd.value = false;
  isEdit.value = false;
  title.value = "新增文件";
}

function handleUpdate(row) {
  Object.assign(form.value, {
    _id: undefined,
    tag_id: undefined,
    type: undefined,
    dan: undefined,
    range: [],
    level: undefined,
    remark: "",
    publisher: "",
    name: "",
    cover: "",
    url: [],
    children: [],
    describe: "",
    file_manage_id: undefined,
    sort: undefined,
  });
  coverList.value = [];
  fileList.value = [];

  Object.assign(form.value, row);
  open.value = true;
  tuwenadd.value = false;
  isEdit.value = true;
  title.value = "修改文件";

  // 处理封面回显
  coverList.value = [];
  if (row.cover) {
    const isCloud = row.cover.startsWith("cloud://");
    if (isCloud) {
      getTempUrls([row.cover]).then((urls) => {
        coverList.value = [
          {
            name: "封面图",
            url: urls[0].tempFileURL,
            uid: Date.now(),
            status: "success",
          },
        ];
      });
    } else {
      coverList.value = [
        {
          name: "封面图",
          url: row.cover,
          uid: Date.now(),
          status: "success",
        },
      ];
    }
  }

  // 处理文件回显
  fileList.value = [];
  if (row.url && row.url.length) {
    const fileId = row.url[0];
    const isCloud = fileId.startsWith("cloud://");
    if (isCloud) {
      getTempUrls([fileId]).then((urls) => {
        fileList.value = [
          {
            name: row.name || "课件文件",
            url: urls[0].tempFileURL,
            uid: Date.now(),
            status: "success",
          },
        ];
      });
    } else {
      fileList.value = [
        {
          name: row.name || "课件文件",
          url: fileId,
          uid: Date.now(),
          status: "success",
        },
      ];
    }
  }
}

// 图文编辑
function handleUpdate2(row) {
  Object.assign(form.value, {
    _id: undefined,
    tag_id: undefined,
    type: undefined,
    dan: undefined,
    range: [],
    level: undefined,
    remark: "",
    publisher: "",
    name: "",
    cover: "",
    url: [],
    children: [],
    describe: "",
    file_manage_id: undefined,
    sort: undefined,
  });
  coverList.value = [];
  fileList.value = [];

  Object.assign(form.value, row);
  form.value.cover = row.url;
  open.value = true;
  tuwenadd.value = true;
  isEdit.value = false;
  title.value = "修改文件";

  // 处理封面回显
  coverList.value = [];
  if (row.url) {
    const isCloud = row.url.startsWith("cloud://");
    if (isCloud) {
      getTempUrls([row.url]).then((urls) => {
        coverList.value = [
          {
            name: "图片",
            url: urls[0].tempFileURL,
            uid: Date.now(),
            status: "success",
          },
        ];
      });
    } else {
      coverList.value = [
        {
          name: "图片",
          url: row.url,
          uid: Date.now(),
          status: "success",
        },
      ];
    }
  }
}

/** 删除 */
async function handleDelete(row) {
  const userIds = row._id || ids.value;

  try {
    // 1. 先确认是否删除
    await proxy.$modal.confirm(`是否确认删除编号为 "${userIds}" 的数据项？`);

    // 2. 查找该用户
    const targetItem = userList.value.find((item) => item._id === userIds);

    // 3. 删除 children（如果有）
    if (targetItem?.children?.length) {
      await proxy.$models.wx_details.deleteMany({
        filter: {
          where: { file_manage_id: { $eq: userIds } },
        },
        envType: "prod",
      });
    }

    // 4. 删除父项
    const { data } = await proxy.$models.file_manage.delete({
      filter: { where: { _id: { $eq: userIds } } },
      envType: "prod",
    });

    // 5. 根据返回结果提示
    if (data.count > 0) {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    } else {
      proxy.$modal.msgWarning("删除失败，未找到对应记录");
    }
  } catch (err) {
    console.error("删除失败：", err);
  }
}

/** 图文删除 */
async function handleDelete2(row) {
  const userIds = row._id;
  try {
    await proxy.$modal.confirm(`是否确认删除用户编号为"${userIds}"的数据项？`);
    const { data } = await proxy.$models.wx_details.delete({
      filter: { where: { _id: { $eq: userIds } } },
      envType: "prod",
    });
    if (data.count > 0) {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    } else proxy.$modal.msgWarning("删除失败，未找到对应记录");
  } catch (err) {
    console.error(err);
  }
}

function submitForm() {
  // 复制原始 rules
  const dynamicRules = { ...rules.value };

  // 图文新增规则覆盖
  if (tuwenadd.value) {
    // 只校验 children 和 sort
    Object.keys(dynamicRules).forEach((key) => delete dynamicRules[key]); // 清空旧规则
    dynamicRules.children = [
      {
        validator: (rule, value, callback) => {
          if (
            !value ||
            !value.length ||
            value.some((item) => !item.title || !item.content)
          ) {
            callback(
              new Error("图文章节不能为空，且每个章节必须填写标题和内容")
            );
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ];
    dynamicRules.sort = [
      { required: true, message: "请选择排序", trigger: "blur" },
    ];
  } else {
    // 普通文件类型，根据类型动态控制等级/段位必填
    if (showDan.value) {
      dynamicRules.dan = [
        { required: true, message: "请选择等级", trigger: "blur" },
      ];
    }
    if (showLevel.value) {
      dynamicRules.level = [
        { required: true, message: "请选择段位", trigger: "blur" },
      ];
    }
    if (form.value.type !== 4) {
      dynamicRules.cover = [
        { required: true, message: "请上传封面", trigger: "blur" },
      ];
      dynamicRules.url = [
        { required: true, message: "请上传课件文件", trigger: "blur" },
      ];
    } else {
      // 图文类型但不是新增，校验 children
      dynamicRules.children = [
        {
          validator: (rule, value, callback) => {
            if (
              !value ||
              !value.length ||
              value.some((item) => !item.title || !item.content)
            ) {
              callback(
                new Error("图文章节不能为空，且每个章节必须填写标题和内容")
              );
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ];
    }
  }

  // 临时覆盖表单 rules
  userRef.value.rules = dynamicRules;

  // 校验并提交
  userRef.value.validate(async (valid) => {
    if (!valid) return;

    if (!tuwenadd.value && form.value._id) {
      const datalistss = {
        ...form.value,
        tag_id: Array.isArray(form.value.tag_id) && form.value.tag_id.length > 0
          ? form.value.tag_id[form.value.tag_id.length - 1]
          : ''
      }
      const { data } = await proxy.$models.file_manage.update({
        filter: { where: { _id: { $eq: form.value._id } } },
        data: form.value,
        // data: datalistss,
        envType: "prod",
      });
      if(data.count > 0) {
        proxy.$modal.msgSuccess("修改成功");
      } else {
        proxy.$modal.msgWarning("修改失败");
      }
    } else if (tuwenadd.value && form.value._id === undefined) {
      // 新增图文逻辑
      const datalist = {
        url: form.value.cover,
        describe: form.value.describe,
        file_manage_id: form.value.file_manage_id,
        sort: form.value.sort,
        size: form.value.size,
      };
      const { data } = await proxy.$models.wx_details.create({ data: datalist, envType: "prod" });
      if (data?.id) {
        ElMessage.success("新增成功");
      } else {
        ElMessage.warning("新增失败");
      }
    } else if (tuwenadd.value && form.value._id && form.value.file_manage_id) {
      const datalist = {
        url: form.value.cover,
        describe: form.value.describe,
        sort: form.value.sort,
        size: form.value.size,
      };
      const { data} = await proxy.$models.wx_details.update({
        data: datalist,
        filter: { where: { _id: { $eq: form.value._id } } },
        envType: "prod",
      });
      if(data.count > 0) {
        proxy.$modal.msgSuccess("修改成功");
      } else {
        proxy.$modal.msgWarning("修改失败");
      }
    } else {
      const datalistss = {
        ...form.value,
        tag_id: Array.isArray(form.value.tag_id) && form.value.tag_id.length > 0
          ? form.value.tag_id[form.value.tag_id.length - 1]
          : ''
      }
      const { data } = await proxy.$models.file_manage.create({ data: datalistss, envType: "prod" });
      if (data?.id) {
        ElMessage.success("新增成功");
      } else {
        ElMessage.warning("新增失败");
      }
    }

    open.value = false;
    fileList.value = [];
    getList();
  });
}

function cancel() {
  open.value = false;
  fileList.value = [];
}

// 上传封面
async function handleUploadCover(file) {
  const rawFile = file.raw;

  // ✅ 中文名判断：如果包含中文，直接阻止上传
  const hasChinese = /[\u4e00-\u9fa5]/.test(rawFile.name);
  if (hasChinese) {
    proxy.$message.error("文件名不能包含中文！");
    return;
  }

  try {
    const res = await uploadToCloud(rawFile, "imgs/kjcover");
    form.value.cover = res.fileID; // ✅这里必须加 .value

    const urlRes = await getTempUrls([res.fileID]);
    coverList.value = [
      {
        name: rawFile.name,
        url: urlRes[0].tempFileURL,
        uid: Date.now(),
        status: "success",
      },
    ];
  } catch (err) {
    proxy.$message.error("上传失败");
    console.error(err);
  }
}

// 上传文件
async function handleUploadFile(file) {
  // 文件类型映射表
  const fileTypeMap = {
    0: ["mp4", "avi", "mov", "mkv"], // 视频
    1: ["mp3", "wav", "aac", "flac"], // 音频
    2: ["pdf"], // PDF
    3: ["ppt", "pptx"], // PPT
    4: ["jpg", "jpeg", "png", "gif", "bmp", "webp"], // 图文
    5: ["xls", "xlsx"], 
  };

  const rawFile = file.raw;

  // ✅ 中文名判断：如果包含中文，直接阻止上传
  const hasChinese = /[\u4e00-\u9fa5]/.test(rawFile.name);
  if (hasChinese) {
    proxy.$message.error("文件名不能包含中文！");
    return false; // 阻止上传
  }

  // ✅ 判断是否选择了上传类型
  if (form.value.type === undefined || form.value.type === null) {
    proxy.$message.error("请先选择文件类型！");
    return false;
  }

  // ✅ 获取当前选择的类型允许的后缀
  const allowExts = fileTypeMap[form.value.type];
  const fileExt = rawFile.name.split(".").pop().toLowerCase();

  if (!allowExts.includes(fileExt)) {
    proxy.$message.error(`文件类型不符合要求！只能上传: ${allowExts.join(", ")}`);
    return false;
  }

  try {
    const res = await uploadToCloud(rawFile, "imgs/files");

    // 保证 form.url 和 fileList 同步
    form.value.url = [res.fileID];
    // 获取文件大小
    const fileSizeMB = rawFile.size / 1024 / 1024;
    form.value.size = `${fileSizeMB.toFixed(2)}MB`; // ✅ 赋值给 form.value.size

    const urlRes = await getTempUrls([res.fileID]);
    fileList.value = [
      {
        name: rawFile.name,
        url: urlRes[0].tempFileURL,
        uid: Date.now(),
        status: "success",
      },
    ];
  } catch (err) {
    proxy.$message.error("上传失败");
    console.error(err);
  }
}

// 删除封面
function handleRemoveCover() {
  form.value.cover = "";
  coverList.value = [];
}

// 删除文件
function handleRemoveFile(file) {
  fileList.value = [];
  form.value.url = [];
}

// 公共上传方法
async function uploadToCloud(rawFile, folder) {
  const res = await proxy.$apps.uploadFile({
    cloudPath: `${folder}/${Date.now()}_${encodeURIComponent(rawFile.name)}`,
    filePath: rawFile,
  });
  return res;
}

// 上传封面前校验
function beforeUploadCover(file) {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片文件");
    return Promise.reject();
  }
  const hasChinese = /[\u4e00-\u9fa5]/.test(file.name);
  if (hasChinese) {
    ElMessage.error("文件名不能包含中文！");
    return Promise.reject();
  }
  return true;
}

// 上传文件前校验
function beforeUploadFile(file) {
  if (fileList.value.length >= 1) {
    ElMessage.warning("只能上传一个文件");
    return Promise.reject();
  }
  const hasChinese = /[\u4e00-\u9fa5]/.test(file.name);
  if (hasChinese) {
    ElMessage.error("文件名不能包含中文！");
    return Promise.reject();
  }
  return true; // ✅ 简单直接允许上传
}

// 图片预览
function handlePreview(file) {
  window.open(file.url || file.response?.url);
}

// 图文子表新增
function handleAddChild(row) {
  Object.assign(form.value, {
    _id: undefined,
    tag_id: undefined,
    type: undefined,
    dan: undefined,
    range: undefined,
    level: undefined,
    remark: "",
    publisher: "",
    name: "",
    cover: "",
    url: [],
    children: [],
    describe: "",
    file_manage_id: undefined,
    sort: undefined,
  });
  coverList.value = [];
  fileList.value = [];

  open.value = true;
  tuwenadd.value = true;
  isEdit.value = false;
  title.value = "新增图文章节";
  form.value.file_manage_id = row._id;
}

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

<style scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
