<template>
  <div class="service-management-container">
    <!-- 标签页 -->
    <div class="header-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane v-for="tab in tabs" :key="tab.value" :label="tab.label" :name="tab.value" />
      </el-tabs>
      <div class="action-buttons">
        <el-button type="primary" @click="openCreateDialog"> 新增 </el-button>
        <el-button type="primary" @click="handleBatchImport"> 批量导入 </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table :data="paginatedList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column label="图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.imageUrl"
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="image-placeholder">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="收费标准(元)" width="120" align="center" />
        <el-table-column prop="openingHours" label="开放时间" width="150" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? "显示" : "隐藏" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="toggleStatus(row)">
              {{ row.status === 1 ? "隐藏" : "显示" }}
            </el-button>
            <el-button type="primary" link @click="editItem(row)"> 编辑 </el-button>
            <el-button type="primary" link @click="deleteItem(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pageable.pageNum"
          v-model:page-size="pageable.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="选择区域*" prop="areaType">
          <el-select v-model="formData.areaType" placeholder="请选择" style="width: 100%">
            <el-option v-for="tab in tabs" :key="tab.value" :label="tab.label" :value="tab.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称*" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" maxlength="50" clearable />
        </el-form-item>
        <el-form-item label="收费标准(元)*" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :max="99999.99"
            :precision="2"
            :step="0.01"
            placeholder="请输入"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="开放时间" prop="openingHoursType">
          <el-radio-group v-model="formData.openingHoursType">
            <el-radio label="allDay"> 全天 </el-radio>
            <el-radio label="custom"> 选择时间 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.openingHoursType === 'custom'" label="选择时间*" prop="openingHours">
          <el-time-picker
            v-model="formData.openingHours"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="图片*" prop="imageUrl">
          <UploadImg
            v-model:image-url="formData.imageUrl"
            :width="'150px'"
            :height="'150px'"
            :file-size="9999"
            :api="formData => uploadFormDataToOss(formData, 'image')"
            :file-type="['image/jpeg', 'image/png', 'image/gif', 'image/webp']"
            :border-radius="'8px'"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1"> 显示 </el-radio>
            <el-radio :label="0"> 隐藏 </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false"> 取消 </el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ editId ? "确定" : "新增" }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量导入弹窗 -->
    <el-dialog v-model="batchImportVisible" title="批量导入" width="500px">
      <div class="import-steps">
        <div class="import-step">
          <div class="step-header">
            <div class="step-number">1</div>
            <div class="step-title">下载模板</div>
          </div>
          <el-button type="primary" @click="downloadTemplate"> 下载excel模板 </el-button>
        </div>
        <div class="import-step">
          <div class="step-header">
            <div class="step-number">2</div>
            <div class="step-title">上传文件</div>
          </div>
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :limit="1"
            accept=".xlsx,.xls"
            drag
            class="import-upload"
          >
            <el-icon class="el-icon--upload">
              <UploadFilled />
            </el-icon>
            <div class="el-upload__text">点击上传文件或拖拽上传文件</div>
          </el-upload>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchImportVisible = false"> 取消 </el-button>
          <el-button type="primary" :loading="importLoading" @click="handleImportSubmit"> 导入 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules, UploadFile } from "element-plus";
import { Picture, UploadFilled } from "@element-plus/icons-vue";
import UploadImg from "@/components/Upload/Img.vue";
import { uploadFormDataToOss } from "@/api/upload.js";
import { localGet } from "@/utils";
import {
  getServiceList,
  createOrUpdateService,
  getServiceDetail,
  deleteService,
  downloadServiceTemplate,
  importServiceExcel,
  getListByStoreIdAndCategory,
  saveOfficialImg
} from "@/api/modules/storeDecoration";

// 服务接口
interface Service {
  id?: string | number;
  areaType: string;
  name: string;
  price: number;
  openingHoursType?: "allDay" | "custom";
  openingHours: string | string[]; // 表格显示时为字符串，表单编辑时为数组
  imageUrl: string;
  status: number; // 0:隐藏, 1:显示
  createTime?: string;
  storeId?: number; // 店铺ID
  // 新API字段
  facilityCategory?: number; // 区域分类
  facilityName?: string; // 名称
  chargingStandard?: string; // 收费标准
  usageTimeType?: number; // 使用时间类型
  usageStartTime?: string; // 使用开始时间
  usageEndTime?: string; // 使用结束时间
  imgUrl?: string; // 图片id
  displayInStoreDetail?: number; // 是否显示在店铺详情
}

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const activeTab = ref("bath"); // 洗浴区
const editId = ref<string | number | null>(null);
const batchImportVisible = ref(false);
const importLoading = ref(false);
const uploadRef = ref();
const importFile = ref<UploadFile | null>(null);

// 标签页配置
const tabs = [
  { label: "洗浴区", value: "bath" },
  { label: "汗蒸区", value: "sauna" },
  { label: "休闲区", value: "leisure" },
  { label: "餐饮区", value: "dining" }
];

// 服务列表
const serviceList = ref<Service[]>([]);

// 分页数据
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 分页后的列表
const paginatedList = computed(() => {
  const list = serviceList.value.filter(item => item.areaType === activeTab.value);
  const start = (pageable.pageNum - 1) * pageable.pageSize;
  const end = start + pageable.pageSize;
  return list.slice(start, end);
});

// 弹窗标题
const dialogTitle = computed(() => (editId.value !== null ? "编辑" : "新建"));

// 表单数据
const formData = reactive({
  areaType: "bath",
  name: "",
  price: 0,
  openingHoursType: "allDay" as "allDay" | "custom",
  openingHours: [] as string[],
  imageUrl: "",
  status: 1
});

// 表单校验规则
const rules = reactive<FormRules>({
  areaType: [{ required: true, message: "请选择区域", trigger: "change" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入收费标准", trigger: "blur" }],
  openingHours: [
    {
      validator: (rule, value, callback) => {
        if (formData.openingHoursType === "custom" && (!value || value.length !== 2)) {
          callback(new Error("请选择开放时间"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  imageUrl: [{ required: true, message: "请上传图片", trigger: "change" }]
});

// Tab切换
const handleTabClick = async () => {
  pageable.pageNum = 1;
  await loadServiceList();
  updatePagination();
};

// 更新分页总数
const updatePagination = () => {
  const list = serviceList.value.filter(item => item.areaType === activeTab.value);
  pageable.total = list.length;
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pageable.pageSize = size;
  pageable.pageNum = 1;
  updatePagination();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pageable.pageNum = page;
};

// 打开新建弹窗
const openCreateDialog = () => {
  editId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const editItem = async (item: Service) => {
  if (!item.id) {
    ElMessage.warning("服务ID不存在");
    return;
  }

  try {
    const res: any = await getServiceDetail({ id: item.id });
    if (res && (res.code === 200 || res.code === "200") && res.data) {
      const detail = res.data;
      editId.value = detail.id;
      // 区域分类映射：1-洗浴区, 2-汗蒸区, 3-休闲区, 4-餐饮区
      formData.areaType = detail.facilityCategory
        ? detail.facilityCategory === 1
          ? "bath"
          : detail.facilityCategory === 2
            ? "sauna"
            : detail.facilityCategory === 3
              ? "leisure"
              : "food"
        : "bath";
      formData.name = detail.facilityName || "";
      formData.price = detail.chargingStandard || 0;
      formData.openingHoursType = detail.usageTimeType === 0 ? "allDay" : "custom";
      if (detail.usageTimeType === 1 && detail.usageStartTime && detail.usageEndTime) {
        formData.openingHours = [detail.usageStartTime, detail.usageEndTime];
      } else {
        formData.openingHours = [];
      }
      formData.imageUrl = detail.imgUrl || "";
      formData.status = 1; // 新API中没有status字段，默认为1
      dialogVisible.value = true;
    } else {
      ElMessage.error(res?.msg || "获取服务详情失败");
    }
  } catch (error: any) {
    console.error("获取服务详情失败:", error);
    ElMessage.error(error?.msg || "获取服务详情失败，请重试");
  }
};

// 删除
const deleteItem = async (item: Service) => {
  try {
    await ElMessageBox.confirm("确认删除该服务吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    if (!item.id) {
      ElMessage.error("服务ID不存在");
      return;
    }

    const res: any = await deleteService({ id: item.id });
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("删除成功");
      await loadServiceList();
      updatePagination();
    } else {
      ElMessage.error(res?.msg || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除服务失败:", error);
      ElMessage.error(error?.msg || "删除失败，请重试");
    }
  }
};

// 切换状态
const toggleStatus = async (item: Service) => {
  try {
    if (!item.id) {
      ElMessage.error("服务ID不存在");
      return;
    }

    const newStatus = item.status === 1 ? 0 : 1;
    // 构建符合新接口的参数
    const params: any = {
      id: item.id,
      storeId: item.storeId,
      facilityCategory: item.facilityCategory,
      facilityName: item.facilityName || item.name,
      chargingStandard: item.chargingStandard || item.price,
      usageTimeType: item.usageTimeType || (item.openingHoursType && item.openingHoursType === "allDay" ? 0 : 1),
      usageStartTime: item.usageStartTime,
      usageEndTime: item.usageEndTime,
      imgUrl: item.imgUrl || item.imageUrl,
      displayInStoreDetail: newStatus // 新的状态字段
    };

    const res: any = await createOrUpdateService(params);
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success(newStatus === 1 ? "已显示" : "已隐藏");
      await loadServiceList();
      updatePagination();
    } else {
      ElMessage.error(res?.msg || "操作失败");
    }
  } catch (error: any) {
    console.error("切换状态失败:", error);
    ElMessage.error(error?.msg || "操作失败，请重试");
  }
};

// 重置表单
const resetForm = () => {
  formData.areaType = activeTab.value;
  formData.name = "";
  formData.price = 0;
  formData.openingHoursType = "allDay";
  formData.openingHours = [];
  formData.imageUrl = "";
  formData.status = 1;
  editId.value = null;
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.warning("请完善必填项");
    return;
  }

  submitLoading.value = true;
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      submitLoading.value = false;
      return;
    }

    // 将areaType转换为facilityCategory
    const categoryMap: Record<string, number> = {
      bath: 1, // 洗浴区
      sauna: 2, // 汗蒸区
      leisure: 3, // 休闲区
      dining: 4 // 餐饮区
    };

    // 解析开放时间
    let usageStartTime = "";
    let usageEndTime = "";
    if (formData.openingHoursType !== "allDay" && formData.openingHours && formData.openingHours.length === 2) {
      usageStartTime = formData.openingHours[0];
      usageEndTime = formData.openingHours[1];
    }

    const params: any = {
      storeId: Number(storeId),
      facilityCategory: categoryMap[formData.areaType], // 区域分类
      facilityName: formData.name, // 名称
      chargingStandard: formData.price, // 收费标准
      usageTimeType: formData.openingHoursType === "allDay" ? 0 : 1, // 使用时间类型
      usageStartTime: usageStartTime, // 使用开始时间
      usageEndTime: usageEndTime, // 使用结束时间
      imgUrl: formData.imageUrl, // 图片id
      displayInStoreDetail: formData.status // 是否显示在店铺详情
    };

    if (editId.value) {
      params.id = editId.value;
    }

    const res: any = await createOrUpdateService(params);
    if (res && (res.code === 200 || res.code === "200")) {
      // 获取保存后的设施ID
      const facilityId = res.data?.id || (editId.value ? editId.value : null);

      // 如果有图片URL，调用saveOfficialImg接口上传图片信息
      if (facilityId && formData.imageUrl) {
        const userInfo: any = localGet("geeker-user")?.userInfo || {};
        const storeId = userInfo.storeId;
        if (storeId) {
          // 准备图片数据
          const imageData = [
            {
              imgUrl: formData.imageUrl,
              imgType: 29, // 设施图片类型
              businessId: facilityId, // 设施ID
              storeId: Number(storeId),
              imgSort: 0 // 图片排序，这里只有一张图片，所以是0
            }
          ];

          // 调用saveOfficialImg接口
          const saveRes: any = await saveOfficialImg(imageData);
          if (!(saveRes && (saveRes.code === 200 || saveRes.code === "200"))) {
            console.error("保存图片信息失败:", saveRes);
            ElMessage.warning("图片信息保存失败，请稍后重试");
          }
        }
      }

      ElMessage.success(editId.value ? "编辑成功" : "新增成功");
      dialogVisible.value = false;
      resetForm();
      await loadServiceList();
      updatePagination();
    } else {
      ElMessage.error(res?.msg || (editId.value ? "编辑失败" : "新增失败"));
    }
  } catch (error: any) {
    console.error("操作失败:", error);
    ElMessage.error(error?.msg || "操作失败，请重试");
  } finally {
    submitLoading.value = false;
  }
};

// 加载服务列表
const loadServiceList = async () => {
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      console.warn("未找到店铺ID");
      return;
    }

    // 将areaType转换为facilityCategory
    const categoryMap: Record<string, number> = {
      bath: 1, // 洗浴区
      sauna: 2, // 汗蒸区
      leisure: 3, // 休闲区
      dining: 4 // 餐饮区
    };
    const facilityCategory = categoryMap[activeTab.value];

    const res: any = await getListByStoreIdAndCategory({
      storeId: Number(storeId),
      facilityCategory
    });
    if (res && (res.code === 200 || res.code === "200") && res.data) {
      const dataList = Array.isArray(res.data) ? res.data : [];
      serviceList.value = dataList.map((item: any) => ({
        id: item.id,
        areaType: Object.keys(categoryMap).find(key => categoryMap[key] === item.facilityCategory) || "bath",
        name: item.facilityName || "",
        price: parseFloat(item.chargingStandard) || 0,
        openingHoursType: item.usageTimeType === 0 ? "allDay" : "custom",
        openingHours: item.usageTimeType === 0 ? "全天" : `${item.usageStartTime}-${item.usageEndTime}`,
        imageUrl: item.imgUrl || "",
        status: item.displayInStoreDetail !== undefined ? item.displayInStoreDetail : 1,
        createTime: item.createdTime || "",
        storeId: item.storeId || 0, // 添加storeId映射
        // 保留新API的原始字段
        facilityCategory: item.facilityCategory,
        facilityName: item.facilityName,
        chargingStandard: item.chargingStandard,
        usageTimeType: item.usageTimeType,
        usageStartTime: item.usageStartTime,
        usageEndTime: item.usageEndTime,
        imgUrl: item.imgUrl,
        displayInStoreDetail: item.displayInStoreDetail
      }));
    }
  } catch (error) {
    console.error("获取服务列表失败:", error);
  }
};

// 批量导入
const handleBatchImport = () => {
  batchImportVisible.value = true;
};

// 文件选择
const handleFileChange = (file: UploadFile) => {
  importFile.value = file;
};

// 文件移除
const handleFileRemove = () => {
  importFile.value = null;
};

// 下载模板
const downloadTemplate = async () => {
  try {
    const res: any = await downloadServiceTemplate();
    const blob =
      res instanceof Blob
        ? res
        : new Blob([res], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `服务导入模板_${new Date().getTime()}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success("模板下载成功");
  } catch (error: any) {
    console.error("下载模板失败:", error);
    ElMessage.error(error?.msg || "模板下载失败，请重试");
  }
};

// 提交导入
const handleImportSubmit = async () => {
  if (!importFile.value || !importFile.value.raw) {
    ElMessage.warning("请先选择文件");
    return;
  }

  const userInfo: any = localGet("geeker-user")?.userInfo || {};
  const storeId = userInfo.storeId;
  if (!storeId) {
    ElMessage.error("未找到店铺ID");
    return;
  }

  importLoading.value = true;
  try {
    const formData = new FormData();
    formData.append("file", importFile.value.raw);
    const res: any = await importServiceExcel(formData, storeId);
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("导入成功");
      batchImportVisible.value = false;
      importFile.value = null;
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
      await loadServiceList();
      updatePagination();
    } else {
      ElMessage.error(res?.msg || "导入失败");
    }
  } catch (error: any) {
    console.error("导入失败:", error);
    ElMessage.error(error?.msg || "导入失败，请重试");
  } finally {
    importLoading.value = false;
  }
};

// 页面初始化
onMounted(async () => {
  await loadServiceList();
  updatePagination();
});
</script>

<style scoped lang="scss">
.service-management-container {
  .header-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    :deep(.el-tabs) {
      flex: 1;
      .el-tabs__header {
        margin: 0;
      }
    }
    .action-buttons {
      display: flex;
      gap: 10px;
    }
  }
  .table-section {
    .pagination-section {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
    .image-placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      color: #909399;
      background-color: #f0f0f0;
      border-radius: 4px;
      .el-icon {
        font-size: 24px;
      }
    }
    .image-slot {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      color: #909399;
      background-color: #f0f0f0;
    }
  }
  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
  .import-steps {
    .import-step {
      margin-bottom: 30px;
      &:last-child {
        margin-bottom: 0;
      }
      .step-header {
        display: flex;
        gap: 12px;
        align-items: center;
        margin-bottom: 16px;
        .step-number {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          font-size: 14px;
          font-weight: 500;
          color: white;
          background-color: var(--el-color-primary);
          border-radius: 50%;
        }
        .step-title {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-text-color-primary);
        }
      }
    }
    .import-upload {
      :deep(.el-upload-dragger) {
        width: 100%;
        padding: 40px 20px;
        .el-icon--upload {
          font-size: 48px;
          color: var(--el-text-color-placeholder);
        }
        .el-upload__text {
          margin-top: 16px;
          font-size: 14px;
          color: var(--el-text-color-regular);
          em {
            font-style: normal;
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
}
</style>
