<template>
  <div class="entrance-map-container">
    <div class="content-wrapper">
      <!-- 左侧：上传区域 -->
      <div class="left-section">
        <h2 class="section-title">图片</h2>

        <!-- 说明文字 -->
        <div class="instructions">
          <ol class="instruction-list">
            <li>入口图建议上传能够代表店铺的图片,如环境范围、菜品样式、本店特色等。</li>
            <li>建议上传1:1尺寸的图片,避免图片出现显示不全问题。</li>
            <li>建议尺寸900*900像素以内,不超过10MB。</li>
          </ol>
        </div>

        <!-- 图片上传组件 -->
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="0">
          <el-form-item prop="entranceImage">
            <UploadImg
              v-model:image-url="formData.entranceImage"
              :width="'400px'"
              :height="'400px'"
              :file-size="20"
              :file-type="['image/jpeg', 'image/png', 'image/gif', 'image/webp']"
              :border-radius="'8px'"
              :api="customUploadApi"
            >
              <template #tip>
                <div class="upload-tip">上传图片 ({{ formData.entranceImage ? "1" : "0" }}/1)</div>
              </template>
            </UploadImg>
          </el-form-item>
        </el-form>

        <!-- 保存按钮 -->
        <div class="footer">
          <el-button type="primary" size="large" :loading="loading" @click="handleSave"> 保存 </el-button>
        </div>
      </div>

      <!-- 右侧：预览区域 -->
      <div class="right-section">
        <h2 class="section-title">示例</h2>
        <div class="preview-container">
          <div class="preview-card">
            <div class="preview-image">
              <img v-if="formData.entranceImage" :src="formData.entranceImage" alt="入口图" />
              <div v-else class="preview-placeholder">示例图</div>
            </div>
            <div class="preview-content">
              <div class="preview-rating">
                <el-rate v-model="previewData.rating" disabled show-score text-color="#ff9900" score-template="{value}" />
              </div>
              <div class="preview-reviews">{{ previewData.reviews }}条</div>
              <div class="preview-price">¥{{ previewData.price }}/人</div>
              <div class="preview-address">
                {{ previewData.address }}
              </div>
              <div class="preview-distance">
                {{ previewData.distance }}
              </div>
            </div>
          </div>
          <div class="preview-placeholder-bottom" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import UploadImg from "@/components/Upload/Img.vue";
import { uploadFileToOss } from "@/api/upload.js";
import { getEntranceImg, saveEntranceImg } from "@/api/modules/storeDecoration";
import { localGet } from "@/utils";

const loading = ref(false);
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  entranceImage: "" // 入口图URL
});

// 图片校验函数（已移除尺寸限制）
const validateImageDimensions = (file: File): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    // 直接通过，不进行任何校验
    resolve(true);
  });
};

/** OSS 直传；UploadImg 内为 `const { data } = await api(formData)`，需返回 `{ data: { fileUrl } }` */
const customUploadApi = async (formData: FormData): Promise<{ data: { fileUrl: string } }> => {
  const raw = formData.get("file");
  const file = raw instanceof File ? raw : null;
  if (!file) {
    throw new Error("请选择文件");
  }
  const url = await uploadFileToOss(file, "image");
  return { data: { fileUrl: url } };
};

// 表单校验规则
const rules = reactive<FormRules>({
  entranceImage: [
    { required: true, message: "请上传入口图", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请上传入口图"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});

// 预览数据（示例数据）
const previewData = reactive({
  rating: 4.9,
  reviews: 1127,
  price: 70,
  address: "某某街道 某某路",
  distance: "616m"
});

// 获取入口图数据
const getEntranceImgData = async () => {
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      console.warn("未找到店铺ID");
      return;
    }
    const res: any = await getEntranceImg(storeId);
    if (res && (res.code === 200 || res.code === "200") && res.data) {
      // 处理返回数据，取第一张图片
      const dataAny = res.data as any;
      const imgList = Array.isArray(dataAny) ? dataAny : dataAny.storeImgList || [];
      if (imgList.length > 0 && imgList[0].imgUrl) {
        formData.entranceImage = imgList[0].imgUrl;
      }
    }
  } catch (error) {
    console.error("获取入口图失败:", error);
  }
};

// 页面初始化时获取数据
onMounted(async () => {
  await getEntranceImgData();
});

// 保存
const handleSave = async () => {
  if (!formRef.value) return;

  // 表单校验
  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.warning("请完成必填项");
    return;
  }

  if (!formData.entranceImage) {
    ElMessage.warning("请上传入口图");
    return;
  }

  // 获取店铺ID
  const userInfo: any = localGet("geeker-user")?.userInfo || {};
  const storeId = userInfo.storeId;
  if (!storeId) {
    ElMessage.error("未找到店铺ID，请先完成店铺信息填写");
    return;
  }

  loading.value = true;
  try {
    // 构建保存参数
    const params = {
      imgType: 1,
      storeId: Number(storeId),
      storeImgList: [
        {
          imgType: 1,
          imgUrl: formData.entranceImage,
          storeId: Number(storeId)
        }
      ]
    };

    const result: any = await saveEntranceImg(params);
    if (result && (result.code === 200 || result.code === "200")) {
      ElNotification({
        title: "保存成功",
        type: "success",
        duration: 3000
      });
    } else {
      ElMessage.error(result?.msg || "保存失败");
    }
  } catch (error: any) {
    console.error("保存失败:", error);
    ElMessage.error(error?.msg || "保存失败，请重试");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.entrance-map-container {
  min-height: 100%;
  padding: 20px;
  background-color: white;
  .content-wrapper {
    display: flex;
    gap: 40px;
    max-width: 1400px;
    margin: 0 auto;
    .left-section,
    .right-section {
      flex: 1;
    }
    .section-title {
      margin-bottom: 20px;
      font-size: 18px;
      font-weight: bold;
      color: #000000;
    }
    .left-section {
      .instructions {
        margin-bottom: 24px;
        .instruction-list {
          padding-left: 20px;
          margin: 0;
          font-size: 14px;
          line-height: 24px;
          color: #606266;
          li {
            margin-bottom: 8px;
          }
        }
      }
      .upload-section {
        display: flex;
        justify-content: center;
        margin-bottom: 40px;
        .upload-tip {
          margin-top: 12px;
          font-size: 14px;
          color: #909399;
          text-align: center;
        }
      }
      .footer {
        display: flex;
        justify-content: center;
        margin-top: 40px;
      }
    }
    .right-section {
      .preview-container {
        min-height: 600px;
        padding: 20px;
        background-color: #f5f7fa;
        border-radius: 8px;
        .preview-card {
          display: flex;
          gap: 16px;
          padding: 16px;
          background-color: white;
          border-radius: 8px;
          box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
          .preview-image {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 120px;
            min-width: 120px;
            height: 120px;
            overflow: hidden;
            background-color: #f0f0f0;
            border-radius: 8px;
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            .preview-placeholder {
              font-size: 14px;
              color: #909399;
            }
          }
          .preview-content {
            display: flex;
            flex: 1;
            flex-direction: column;
            justify-content: space-between;
            .preview-rating {
              display: flex;
              align-items: center;
              margin-bottom: 8px;
              :deep(.el-rate) {
                .el-rate__icon {
                  font-size: 16px;
                }
              }
            }
            .preview-reviews {
              margin-bottom: 8px;
              font-size: 14px;
              color: #606266;
            }
            .preview-price {
              margin-bottom: 8px;
              font-size: 16px;
              font-weight: bold;
              color: #f56c6c;
            }
            .preview-address {
              margin-bottom: 8px;
              font-size: 14px;
              color: #606266;
            }
            .preview-distance {
              font-size: 14px;
              color: #909399;
            }
          }
        }
        .preview-placeholder-bottom {
          height: 200px;
          margin-top: 20px;
          background-color: #e4e7ed;
          border-radius: 8px;
          opacity: 0.3;
        }
      }
    }
  }
}
</style>
