<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!-- 查询 -->
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="展示位置" prop="zhuangtai">
            <el-select
              v-model="queryParams.zhuangtai"
              placeholder="展示位置"
              clearable
              style="width: 240px"
            >
              <el-option label="首页" :value="0" />
              <el-option label="课程" :value="1" />
              <el-option label="培训" :value="2" />
              <el-option label="教学" :value="3" />
              <el-option label="展示" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></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-form-item>
        </el-form>

        <!-- 批量操作 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <!-- 序号 -->
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
            :index="
              (index) =>
                (queryParams.pageNum - 1) * queryParams.pageSize + index + 1
            "
          />
          <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 label="展示位置" align="center" prop="position">
            <template #default="scope">
              <span>
                {{
                  {
                    0: "首页",
                    1: "课程",
                    2: "培训",
                    3: "教学",
                    4: "展示",
                  }[scope.row.position] || "未知"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="展示状态" align="center" key="zhuangtai">
            <template #default="scope">
              <el-switch
                v-model="scope.row.zhuangtai"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            key="remark"
            prop="remark"
            :show-overflow-tooltip="true"
          />
          <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"
            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="['system:user:edit']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user: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-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="展示位置" prop="position">
              <el-select v-model="form.position" placeholder="请选择">
                <el-option label="首页" :value="0" />
                <el-option label="课程" :value="1" />
                <el-option label="培训" :value="2" />
                <el-option label="教学" :value="3" />
                <el-option label="展示" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态" prop="zhuangtai">
              <el-select v-model="form.zhuangtai" placeholder="请选择">
                <el-option label="展示" :value="1" />
                <el-option label="不展示" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传图片" prop="url">
              <el-upload
                class="avatar-uploader"
                list-type="picture-card"
                :file-list="loadlist"
                :auto-upload="false"
                :before-upload="beforeUpload"
                :on-change="handleUpload"
                :on-remove="handleRemove"
                :on-preview="handlePreview"
                :limit="1"
              >
                <el-icon v-if="loadlist.length === 0"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import moment from "moment";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const loadlist = ref([]);
const ids = ref([]);

const data = reactive({
  form: {
    _id: undefined,
    url: "",
    zhuangtai: undefined,
    position: undefined,
    remark: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    position: undefined,
    createdAt: "",
  },
  rules: {
    position: [
      { required: true, message: "展示位置不能为空", trigger: "blur" },
    ],
    zhuangtai: [{ required: true, message: "请选择显示状态", trigger: "blur" }],
    url: [{ required: true, message: "请上传图片", trigger: "blur" }],
  },
});

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

/** 获取临时图片链接 */
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.zhuangtai !== undefined && queryParams.value.zhuangtai !== null) {
    filter.where.position = queryParams.value.zhuangtai;
  }

   console.log(queryParams.value.zhuangtai, 'filter');
  const { data } = await proxy.$models.banner.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.url)
      .filter((url) => url && url.startsWith("cloud://"));
   const urlMap = await getTempUrls(fileIds);

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

    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() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 表单重置 */
function resetForm() {
  form.value = {
    _id: undefined,
    url: "",
    zhuangtai: undefined,
    position: undefined,
    remark: "",
  };
  loadlist.value = [];
  proxy.resetForm("userRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
}

/** 新增 */
function handleAdd() {
  resetForm();
  open.value = true;
  title.value = "新增用户";
}

/** 修改 */
async function handleUpdate(row) {
  resetForm();
  const { data } = await proxy.$models.banner.get({
    filter: { where: { _id: { $eq: row._id } } },
    envType: "prod",
  });
  form.value = data;

  // ✅ 如果 data.url 是 cloud://，获取临时 URL
  if (form.value.url && form.value.url.startsWith("cloud://")) {
    const urlRes = await getTempUrls([form.value.url]);
    form.value.url = urlRes[0].tempFileURL;
  }

  console.log(form.value.url, 'form.value.url');

  // 设置 el-upload 的 file-list
  if (form.value.url) {
    loadlist.value = [
      {
        name: "图片",
        url: form.value.url,
        uid: Date.now(),        // 必填
        status: "success",      // 必填，否则不会显示
      },
    ];
  } else {
    loadlist.value = [];
  }

  open.value = true;
  title.value = "修改用户";
}

/** 删除 */
async function handleDelete(row) {
  const userIds = row._id || ids.value;
  try {
    await proxy.$modal.confirm(`是否确认删除用户编号为"${userIds}"的数据项？`);
    const { data } = await proxy.$models.banner.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 beforeUpload(file) {
  // 中文名判断
  if (/[\u4e00-\u9fa5]/.test(file.name)) {
    proxy.$message.error("文件名不能包含中文！");
    return false; // ⚠️ 返回 false 阻止加入 file-list 和上传
  }

  // 类型校验
  const isValidType = file.type === "image/jpeg" || file.type === "image/png";
  if (!isValidType) proxy.$message.error("只能上传 JPG/PNG 格式!");
  
  // 大小校验
  const isValidSize = file.size / 1024 / 1024 < 2;
  if (!isValidSize) proxy.$message.error("图片大小不能超过 2MB!");

  return isValidType && isValidSize; // 返回 false 就阻止
}

/** 图片上传 */
async function handleUpload(file) {
  const rawFile = file.raw;

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

  try {
    const res = await proxy.$apps.uploadFile({
      cloudPath: `imgs/banner/${Date.now()}_${encodeURIComponent(rawFile.name)}`,
      filePath: rawFile,
    });

    form.value.url = res.fileID;

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

/** 删除图片 */
function handleRemove() {
  form.value.url = "";
  loadlist.value = [];
}

function handlePreview(file) {
  window.open(file.url); // 或者使用自定义弹窗展示
}


/** 提交表单 */
function submitForm() {
  proxy.$refs["userRef"].validate(async (valid) => {
    if (!valid) return;

    const payload = {
      remark: form.value.remark,
      url: form.value.url,
      position: form.value.position,
      zhuangtai: form.value.zhuangtai,
    };

    if (form.value._id) {
      // 更新
      const { data } = await proxy.$models.banner.update({
        data: payload,
        filter: { where: { _id: { $eq: form.value._id } } },
        envType: "prod",
      });
      if (data.count > 0) proxy.$modal.msgSuccess("修改成功");
    } else {
      // 新增
      const { data } = await proxy.$models.banner.create({
        data: payload,
        envType: "prod",
      });
      proxy.$modal.msgSuccess("新增成功");
    }

    open.value = false;
    getList();
  });
}

/** 选择条数 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item._id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 初始化
getList();
</script>

<style lang='scss' scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 4px;
}
</style>