<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.school_id"
          placeholder="请选择园所"
          clearable
          filterable
          remote
          style="width: 240px"
        >
          <el-option
            v-for="school in schoolList"
            :key="school._id"
            :label="school.name"
            :value="school._id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="团购名称">
        <el-input
          v-model="queryParams.groupbuy_name"
          placeholder="请输入团购名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="团购状态">
        <el-select
          v-model="queryParams.groupbuy_state"
          placeholder="请选择团购状态"
          clearable
          style="width: 240px"
        >
          <el-option label="进行中" :value="0" />
          <el-option label="未开始" :value="1" />
          <el-option label="已结束" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作 -->
    <el-button
      type="primary"
      icon="Plus"
      @click="handleAdd"
      style="margin: 10px 0"
      >新增团购</el-button
    >

    <!-- 团购表格 -->
    <el-table v-loading="loading" :data="merchandiseList" style="width: 100%">
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
        :index="
          (index) =>
            (queryParams.pageNum - 1) * queryParams.pageSize + index + 1
        "
      />
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-table
            :data="row.specList || []"
            style="width: 90%; margin-left: 5%"
          >
            <el-table-column label="规格" prop="spec" />
            <el-table-column label="原价" prop="old_price" />
            <el-table-column label="价格" prop="price" />
            <el-table-column label="产品详情" prop="details" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-tooltip content="查看详情" placement="top">
                  <el-button link type="primary" icon="Postcard" @click="handleViewSpecDetail(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="editSpec(scope.row, row)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="deleteSpec(scope.row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="学校名称" align="center" prop="schoolName" />
      <el-table-column label="封面图片" align="center" width="100">
        <template #default="{ row }">
          <el-image :src="row.fengmian" style="width: 100%; height: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="团购名称" align="center" prop="tuangouName" />
      <el-table-column label="已拼数量（件）" align="center" prop="count" />
      <el-table-column label="浏览量（人）" align="center" prop="browse" />
      <el-table-column
        label="活动开始时间"
        align="center"
        key="kaishishijian"
        prop="kaishishijian"
      >
        <template #default="scope">
          <span>{{ moment(scope.row.kaishishijian).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="活动结束时间"
        align="center"
        key="jieshushijian"
        prop="jieshushijian"
      >
        <template #default="scope">
          <span>{{ moment(scope.row.jieshushijian).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="收货方式"
        align="center"
        :formatter="(row) => (row.shouhuofangshi === 0 ? '邮寄' : '自提')"
      />
      <el-table-column
        label="团购状态"
        align="center"
        :formatter="
          (row) => ['进行中', '未开始', '已结束'][row.tuangouzhuangtai]
        "
      />
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-tooltip content="规格新增" placement="top">
            <el-button
              link
              type="primary"
              icon="CirclePlus"
              @click="handleAddSpec(scope.row)"
            />
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleAdd(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="dialogTitle" v-model="dialogOpen" width="700px">
      <el-form :model="form" :rules="activeRules" ref="formRef" label-width="100px">
        <!-- 团购表单 -->
        <template v-if="!falog">
          <el-row>
            <el-col :span="12">
              <el-form-item label="选择园所" prop="school_id">
                <el-select v-model="form.school_id" placeholder="请选择园所" clearable
                filterable
                remote>
                  <el-option
                    v-for="school in schoolList"
                    :key="school._id"
                    :label="school.name"
                    :value="school._id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="团购名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入团购名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="封面图片" prop="fengmian">
                <el-upload
                  class="avatar-uploader"
                  list-type="picture-card"
                  :file-list="coverList"
                  :auto-upload="false"
                  :before-upload="beforeUploadCover"
                  :on-change="handleUploadCover"
                  :on-remove="handleRemoveCover"
                  @preview="handlePreview"
                  :limit="1"
                >
                  <el-icon v-if="coverList.length === 0"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货方式" prop="way">
                <el-select v-model="form.way">
                  <el-option label="邮寄" :value="0" />
                  <el-option label="自提" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="团购类型" prop="eventRange">
                <el-select v-model="form.tag_id" placeholder="请选择园所">
                  <el-option
                    v-for="school in tabList"
                    :key="school._id"
                    :label="school.name"
                    :value="school._id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动时间" prop="eventRange">
                <el-date-picker
                  v-model="form.eventRange"
                  type="daterange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 规格表单 -->
        <template v-if="falog">
          <el-row v-for="(spec, index) in form.specList" :key="'spec' + index" :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格" :prop="'specList.' + index + '.spec'">
                <el-input v-model="spec.spec" placeholder="请输入规格" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="原价" :prop="'specList.' + index + '.old_price'">
                <el-input v-model="spec.old_price" type="number" placeholder="请输入原价" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="价格" :prop="'specList.' + index + '.price'">
                <el-input v-model="spec.price" type="number" placeholder="请输入价格" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="详情图片" :prop="'specList.' + index + '.detail_images'">
                <el-upload
                  class="avatar-uploader"
                  list-type="picture-card"
                  :file-list="(spec.detail_images_urls || []).map((url, i) => ({ name: `图片${i+1}`, url,
                  fileID: spec.detail_images[i],
                  status: 'success', }))"
                  :auto-upload="false"
                  multiple
                  :before-upload="beforeUploadCover"
                  @change="(file, fileList) => handleUploadSpecCover(file, fileList, index)"
                  @remove="(file) => handleRemoveSpecCover(index, file)"
                  @preview="handlePreview"
                >
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="产品详情" :prop="'specList.' + index + '.details'">
                <el-input v-model="spec.details" type="textarea" rows="4" placeholder="请输入产品详情" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogOpen = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 查看规格详情弹窗 -->
    <el-dialog title="规格详情" v-model="detailDialogVisible" width="700px">
      <div v-for="(spec, index) in detailData.specList" :key="index" style="margin-bottom: 20px;">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="规格名称">{{ spec.spec }}</el-descriptions-item>
          <el-descriptions-item label="价格">{{ spec.price }}</el-descriptions-item>
          <el-descriptions-item label="原价">{{ spec.old_price }}</el-descriptions-item>
          <el-descriptions-item label="产品详情">{{ spec.details }}</el-descriptions-item>
        </el-descriptions>

        <el-carousel v-if="spec.detail_images_urls?.length" height="200px" trigger="click" style="margin-top: 10px;">
          <el-carousel-item v-for="(img, i) in spec.detail_images_urls" :key="i">
            <el-image :src="img" style="width: 100%; height: 200px;" fit="contain" />
          </el-carousel-item>
        </el-carousel>
      </div>

      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { callCloudFunction } from "@/api/cloud";
import { Plus } from "@element-plus/icons-vue";

import moment from "moment";

const { proxy } = getCurrentInstance();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  school_id: null,
  groupbuy_name: null,
  groupbuy_state: null,
});

const schoolList = ref([]);
const merchandiseList = ref([]);
const total = ref(0);
const loading = ref(false);
const coverList = ref([]);
const detailDialogVisible = ref(false);
const detailData = reactive({
  specList: [], // 每个规格含 { spec, price, old_price, details, detail_images_urls }
});

const form = reactive({
  _id: "",
  school_id: "",
  name: "",
  fengmian: "",
  way: 0,
  eventRange: [],
  specList: [],
});

// 原来的 rules（团购用）
const groupRules = {
  school_id: [{ required: true, message: "请选择园所", trigger: "blur" }],
  name: [{ required: true, message: "请输入团购名称", trigger: "blur" }],
  fengmian: [{ required: true, message: "请上传封面", trigger: "change" }],
  way: [{ required: true, message: "请选择收货方式", trigger: "change" }],
  eventRange: [{ required: true, message: "请选择活动时间", trigger: "change" }],
};

// 规格规则动态生成
function getSpecRules(specList) {
  const specRules = {};
  specList.forEach((item, index) => {
    specRules[`specList.${index}.spec`] = [
      { required: true, message: "请输入规格", trigger: "blur" }
    ];
    specRules[`specList.${index}.old_price`] = [
      { required: true, message: "请输入原价", trigger: "blur" }
    ];
    specRules[`specList.${index}.price`] = [
      { required: true, message: "请输入价格", trigger: "blur" }
    ];
    specRules[`specList.${index}.detail_images`] = [
      { required: true, message: "请上传详情图片", trigger: "change" }
    ];
    specRules[`specList.${index}.details`] = [
      { required: true, message: "请输入产品详情", trigger: "blur" }
    ];
  });
  return specRules;
}

// 根据 falog 切换 rules
const activeRules = computed(() =>
  falog.value ? getSpecRules(form.specList) : groupRules
);

const dialogOpen = ref(false);
const dialogTitle = ref("新增团购");
const falog = ref(false); // 是否是规格弹窗
const formRef = ref(null);
const tabList = ref([]);

onMounted(() => {
  getList();
  gettabList();
  getSchoolList();
});

async function getSchoolList() {
  const { data } = await proxy.$models.wx_school.list({
    filter: { where: {} },
    pageSize: 10000,
    pageNumber: 1,
    getCount: true,
    envType: "prod",
  });
  schoolList.value = data.records;
}

async function gettabList() {
  const { data } = await proxy.$models.tab.list({
    filter: {
      where: {
        position: 4,
      },
    },
    pageSize: 20,
    pageNumber: 1,
    getCount: true,
    envType: "prod",
  });
  tabList.value = data.records.slice(1);
  console.log(tabList.value);
}

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

function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    school_id: null,
    groupbuy_name: null,
    groupbuy_state: null,
  });
  getList();
}

function formatTime(time) {
  if (!time) return "";
  return new Date(time).toLocaleString();
}

function handleAdd(row = null) {
  dialogOpen.value = true;
  falog.value = false;
  dialogTitle.value = row ? "编辑团购" : "新增团购";
  Object.assign(form, {
    _id: row?.id || "",
    school_id: row?.school_id || "",
    name: row?.tuangouName || "",
    fengmian: row?.fengmian || "",
    way: row?.shouhuofangshi ?? 0,
    eventRange: row
    ? [
        moment(row.kaishishijian).format("YYYY-MM-DD HH:mm:ss"),
        moment(row.jieshushijian).format("YYYY-MM-DD HH:mm:ss")
      ]
    : [],
    specList: row?.specList?.map((s) => ({ ...s })) || [],
    tag_id: row?.tag_id || "",
  });

  coverList.value = form.fengmian
    ? [{ name: "封面", url: form.fengmian, uid: Date.now(), status: "success" }]
    : [];
}

function handleAddSpec(row) {
  falog.value = true;
  dialogOpen.value = true;
  dialogTitle.value = "新增规格";
  Object.assign(form, {
    groupbuy_id: row?.id || "",
    specList: [
      { spec: "", old_price: "", price: "", details: "", detail_images: [] },
    ],
  });
}

function editSpec(spec, row) {
  falog.value = true;
  dialogOpen.value = true;
  dialogTitle.value = "编辑规格";
  Object.assign(form, {
    _id: row._id,
    name: row.tuangouName,
    specList: [{ ...spec }],
  });
}

async function deleteSpec(row) {
  try {
    // 1. 先确认是否删除
    await proxy.$modal.confirm(`是否确认删除编号为 "${row._id}" 的数据项？`);
    const res = await callCloudFunction("database", {
      page: "tuangou",
      action: "deleteguigeById",
      data: { id: row._id },
    });
    proxy.$modal.msgSuccess("删除成功");
    getList();
      // proxy.$modal.msgWarning("删除失败，未找到对应记录");
  } catch (err) {
    console.error("删除失败：", err);
  }
}

async function submitForm() {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning("请填写完整信息");
      return;
    }

    if (falog.value) {
      // 规格处理
      for (const s of form.specList) {
        const payload = {
          groupbuy_id: form.groupbuy_id,
          price: s.price,
          old_price: s.old_price,
          spec: s.spec,
          details: s.details,
          detail_images: s.detail_images,
        };
        if (s._id) {
          await callCloudFunction("database", {
            page: "tuangou",
            action: "updateguigeById",
            data: { id: s._id, ...payload },
          });
        } else {
          await callCloudFunction("database", {
            page: "tuangou",
            action: "addguige",
            data: payload,
          });
        }
      }
    } else {
      // 团购处理
      const payload = {
        id: form._id,
        tagId: form.tag_id,
        schoolId: form.school_id,
        name: form.name,
        img: form.fengmian || "",
        startTime: new Date(form.eventRange[0]).getTime(),
        endTime: new Date(form.eventRange[1]).getTime(),
        way: form.way,
      };
      if (form._id) {
        await callCloudFunction("database", {
          page: "tuangou",
          action: "updateGroupBuy",
          data: { ...payload },
        });
      } else {
        await callCloudFunction("database", {
          page: "tuangou",
          action: "addGroupBuy",
          data: { ...payload },
        });
      }
    }

    ElMessage.success("操作成功");
    dialogOpen.value = false;
    getList();
  });
}

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

  // 校验文件名
  if (/[\u4e00-\u9fa5]/.test(rawFile.name)) {
    ElMessage.error("图片名称不能包含中文!");
    return; // 直接返回，不上传
  }

  const res = await uploadToCloud(rawFile, "imgs/groupbuy");
  form.fengmian = res.fileID;
  const tempUrl = await getTempUrls([res.fileID]);
  coverList.value = [
    {
      name: rawFile.name,
      url: tempUrl[0].tempFileURL,
      uid: Date.now(),
      status: "success",
    },
  ];
}

function handleRemoveCover() {
  form.fengmian = "";
  coverList.value = [];
}

// 上传规格图片
async function handleUploadSpecCover(file, fileList, index) {
  const spec = form.specList[index];

  if (!spec.detail_images) spec.detail_images = [];
  if (!spec.detail_images_urls) spec.detail_images_urls = [];

  for (const f of fileList) {
    // 只处理新上传的文件
    if (f.raw && !f.fileID) {
      // 校验文件名
      if (/[\u4e00-\u9fa5]/.test(f.raw.name)) {
        ElMessage.error(`图片名称不能包含中文!`);
        continue; // 跳过该文件，不上传
      }

      const res = await uploadToCloud(f.raw, "imgs/groupbuy/spec");
      spec.detail_images.push(res.fileID); // 存 fileID
      const tempUrl = await getTempUrls([res.fileID]);
      spec.detail_images_urls.push(tempUrl[0].tempFileURL); // 显示
      f.fileID = res.fileID; // 保存 fileID 避免重复上传
    }
  }
}

// 移除单张图片
function handleRemoveSpecCover(index, file) {
  const spec = form.specList[index];
  // 删除数据库 fileID
  spec.detail_images = spec.detail_images.filter(fid => fid !== file.fileID);
  // 删除回显 URL
  spec.detail_images_urls = spec.detail_images_urls.filter(url => url !== file.url);
}

async function uploadToCloud(rawFile, folder) {
  return await proxy.$apps.uploadFile({
    cloudPath: `${folder}/${Date.now()}_${encodeURIComponent(rawFile.name)}`,
    filePath: rawFile,
  });
}

async function getList() {
  loading.value = true;

  // 只传有效的查询条件
  const params = {};
  for (const [key, value] of Object.entries(queryParams)) {
    if (value !== null && value !== "" && value !== undefined) {
      params[key] = value;
    }
  }

  const res = await callCloudFunction("database", {
    page: "tuangou",
    action: "findGroupBuyPage",
    data: params,
  });

  const detailResults = await Promise.all(
    res.records.map(async (item) => {
      const { data } = await callCloudFunction("database", {
        page: "tuangou",
        action: "findguigeBytuangouId",
        data: { tuangou_id: item.id },
      });
      return { ...item, specList: data || [] };
    })
  );

  const allFileIds = [];
  detailResults.forEach((item) => {
    if (item.fengmian) allFileIds.push(item.fengmian);
    item.specList?.forEach((spec) => {
      if (spec.detail_images?.length) allFileIds.push(...spec.detail_images);
    });
  });

  const tempList = await getTempUrls(allFileIds);
  const tempMap = Object.fromEntries(
    tempList.map((t) => [t.fileID, t.tempFileURL])
  );

  merchandiseList.value = detailResults.map((item) => ({
    ...item,
    img: tempMap[item.fengmian] || item.fengmian,
    fengmian: tempMap[item.fengmian] || item.fengmian,
    specList: (item.specList || []).map((spec) => {
      const images = spec.detail_images || [];
      return {
        ...spec,
        detail_images: images, // 后台存的 fileID
        detail_images_urls: images.map(fid => {
          // 如果已经是 URL 就直接用，否则去 tempMap 里找
          return fid.startsWith("http") ? fid : tempMap[fid] || fid;
        }),
      }
    })
  }));
  console.log(merchandiseList, 'merchandiseList');

  total.value = res.total;
  loading.value = false;
}

// 获取临时链接
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,
  }));
}

function beforeUploadCover(file) {
  // 可以加校验逻辑，比如限制图片大小或格式
  // 校验文件名不能包含中文
  const hasChinese = /[\u4e00-\u9fa5]/.test(file.name);
  if (hasChinese) {
    ElMessage.error("图片名称不能包含中文!");
    return false; // 阻止上传
  }
  return true; // 允许上传
}

// 点击预览
function handlePreview(file) {
  window.open(file.url); // 或者使用 ElImage 的 Dialog 预览
}

/** 删除 */
async function handleDelete(row) {
  try {
    // 1. 先确认是否删除
    await proxy.$modal.confirm(`是否确认删除编号为 "${row.id}" 的数据项？`);
    const res = await callCloudFunction("database", {
      page: "tuangou",
      action: "deleteGroupBuy",
      data: { id: row.id },
    });
    proxy.$modal.msgSuccess("删除成功");
    getList();
      // proxy.$modal.msgWarning("删除失败，未找到对应记录");
  } catch (err) {
    console.error("删除失败：", err);
  }
}

async function handleViewSpecDetail(spec) {
  // 如果需要临时链接
  const tempList = await getTempUrls(spec.detail_images || []);
  const tempMap = Object.fromEntries(tempList.map(t => [t.fileID, t.tempFileURL]));

  detailData.specList = [
    {
      ...spec,
      detail_images_urls: (spec.detail_images || []).map(fid => tempMap[fid] || fid)
    }
  ];

  detailDialogVisible.value = true;
}

</script>

<style scoped>
.avatar-uploader .el-upload {
  width: 100px;
  height: 100px;
}
</style>
