<template>
  <div class="detail-container">
    <div class="card content-box">
      <div class="detail-header">
        <h3>详情</h3>
        <el-button text @click="handleClose">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <el-form ref="formRef" :model="formData" label-width="140px" label-position="right">
        <el-form-item label="用户头像">
          <el-image
            v-if="formData.storeAvatar"
            :src="formData.storeAvatar"
            style="width: 100px; height: 100px; border-radius: 4px"
            fit="cover"
            :preview-src-list="[formData.storeAvatar]"
          />
          <span v-else style="color: #999999">暂无头像</span>
        </el-form-item>

        <el-form-item label="用户昵称">
          <el-input v-model="formData.userNickname" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="状态">
          <el-tag :type="formData.hasCommunicated ? 'success' : 'info'" size="default">
            {{ formData.hasCommunicated ? "已沟通" : "未沟通" }}
          </el-tag>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-input v-model="formData.createdTime" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="装修类型">
          <el-radio-group v-model="formData.renovationType" disabled>
            <el-radio :label="1"> 新房装修 </el-radio>
            <el-radio :label="2"> 旧房改造 </el-radio>
            <el-radio :label="3"> 局部装修 </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="房屋面积(㎡)" required>
          <el-input v-model="formData.houseArea" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="装修预算(万元)" required>
          <el-input v-model="formData.renovationBudget" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="详细需求">
          <el-input v-model="formData.detailedRequirement" type="textarea" :rows="4" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="期望装修时间" required>
          <el-date-picker
            v-model="formData.expectedRenovationTime"
            type="date"
            placeholder="请选择"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            disabled
          />
        </el-form-item>

        <el-form-item label="上传房屋图纸" required>
          <div class="attachment-wrap">
            <div class="attachment-grid">
              <div v-for="(url, index) in formData.attachmentUrls" :key="`${index}-${url}`" class="attachment-card">
                <template v-if="isAttachmentVideo(url)">
                  <div
                    class="attachment-card-inner attachment-card-inner--video"
                    @click="openVideoPreview(getAttachmentVideoSrc(url))"
                  >
                    <video
                      class="attachment-video-thumb"
                      :poster="getVideoThumbPoster(url) || undefined"
                      :src="getAttachmentVideoSrc(url)"
                      muted
                      preload="metadata"
                      playsinline
                    />
                    <div class="video-overlay">
                      <el-icon class="play-icon">
                        <VideoPlay />
                      </el-icon>
                    </div>
                  </div>
                </template>
                <el-image
                  v-else
                  :src="url"
                  fit="cover"
                  class="attachment-image"
                  :preview-src-list="imagePreviewList"
                  :initial-index="getImagePreviewIndex(url)"
                  preview-teleported
                />
              </div>
              <div
                v-if="formData.attachmentUrls.length < 9"
                class="attachment-card attachment-card--placeholder"
                aria-hidden="true"
              >
                <el-icon><Plus /></el-icon>
              </div>
            </div>
            <div class="upload-tip">({{ formData.attachmentUrls.length }}/9)</div>
          </div>
        </el-form-item>

        <el-form-item label="联系人" required>
          <el-input v-model="formData.contactName" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="联系电话" required>
          <el-input v-model="formData.contactPhone" placeholder="请输入" disabled />
        </el-form-item>

        <el-form-item label="所在城市" required>
          <el-input v-model="formData.city" placeholder="请选择" disabled />
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input v-model="formData.detailedAddress" type="textarea" :rows="3" placeholder="请输入" disabled />
        </el-form-item>
      </el-form>

      <div class="detail-footer">
        <el-button @click="handleClose"> 返回 </el-button>
        <el-button type="primary" @click="handleContact"> 联系业主 </el-button>
      </div>
    </div>

    <PcVideoPreviewDialog
      v-model="videoDialogVisible"
      :src="previewVideoUrl"
      title="视频预览"
      :autoplay="true"
      @closed="previewVideoUrl = ''"
    />
  </div>
</template>

<script setup lang="ts" name="decorationCompanyDetail">
import { ref, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, Close, VideoPlay } from "@element-plus/icons-vue";
import { getDecorationDetail } from "@/api/modules/storeDecoration";
import PcVideoPreviewDialog from "@/components/pcMediaPreview/PcVideoPreviewDialog.vue";

const route = useRoute();
const router = useRouter();

const formRef = ref();
const formData = ref<any>({
  storeAvatar: "",
  userNickname: "",
  hasCommunicated: false,
  createdTime: "",
  requirementTitle: "",
  renovationType: 1,
  houseArea: "",
  renovationBudget: "",
  detailedRequirement: "",
  expectedRenovationTime: "",
  contactName: "",
  contactPhone: "",
  city: "",
  detailedAddress: "",
  attachmentUrls: [],
  createUserId: "", // 业主/创建者ID，用于聊天
  userId: "" // 兼容字段
});

const videoDialogVisible = ref(false);
const previewVideoUrl = ref("");

/** 与 caseDetail / 常见上传一致：扩展名或「视频|封面」 */
const isAttachmentVideo = (raw: string) => {
  if (!raw || typeof raw !== "string") return false;
  if (raw.includes("|")) return true;
  return /\.(mp4|avi|mov|wmv|flv|webm|m4v|3gp)(\?|#|$)/i.test(raw);
};

const getAttachmentVideoSrc = (raw: string) => {
  if (!raw || typeof raw !== "string") return "";
  if (raw.includes("|")) return raw.split("|")[0].trim();
  return raw;
};

const getExplicitVideoCover = (raw: string) => {
  if (!raw || typeof raw !== "string" || !raw.includes("|")) return "";
  const parts = raw
    .split("|")
    .map(s => s.trim())
    .filter(Boolean);
  return parts.length >= 2 ? parts[1] : "";
};

/** OSS 视频首帧快照，与 storeCoverMap 一致，利于卡片缩略图 */
const getOssVideoSnapshotUrl = (videoUrl: string) => {
  if (!videoUrl || typeof videoUrl !== "string") return "";
  const isOss =
    videoUrl.includes("aliyuncs.com") ||
    videoUrl.includes("oss-cn-") ||
    videoUrl.includes("oss.") ||
    videoUrl.includes("alien-volume");
  if (!isOss) return "";
  const sep = videoUrl.includes("?") ? "&" : "?";
  return `${videoUrl}${sep}x-oss-process=video/snapshot,t_0,f_jpg,w_800,h_600,m_fast`;
};

const getVideoThumbPoster = (raw: string) => {
  const explicit = getExplicitVideoCover(raw);
  if (explicit) return explicit;
  const src = getAttachmentVideoSrc(raw);
  return getOssVideoSnapshotUrl(src);
};

const imagePreviewList = computed(() => (formData.value.attachmentUrls || []).filter((u: string) => u && !isAttachmentVideo(u)));

const getImagePreviewIndex = (url: string) => imagePreviewList.value.indexOf(url);

const openVideoPreview = (url: string) => {
  if (!url) return;
  previewVideoUrl.value = url;
  videoDialogVisible.value = true;
};

// 联系业主（跳转聊天页面）
const handleContact = () => {
  const data = formData.value as any;
  const receiverId = data.createUserId || data.userId || data.contactPhone;
  if (!receiverId) {
    ElMessage.warning("无法获取业主信息，请联系管理员");
    return;
  }
  const params = new URLSearchParams({
    receiverId: String(receiverId),
    uName: encodeURIComponent(data.contactName || data.userNickname || "业主"),
    storeName: encodeURIComponent(String(data.storeName ?? "")),
    userImage: encodeURIComponent(data.storeAvatar || ""),
    id: String(route.query.id || "")
  });
  router.push(`/storeDecorationManagement/decorationChat?${params.toString()}`);
};

// 获取详情数据
const initData = async () => {
  const id = route.query.id;
  if (!id) {
    handleClose();
    return;
  }

  try {
    // 调用 /renovation/requirement/getDetail 接口
    const res = await getDecorationDetail({ id: id as string });
    if (res.code == 200 || res.code == 0) {
      const data = res.data || res.data?.data || {};
      formData.value = {
        storeAvatar: data.storeAvatar || "",
        userNickname: data.storeName || data.userNickname || data.nickname || "",
        hasCommunicated: data.hasCommunicated ?? false,
        createdTime: data.createdTime || "",
        requirementTitle: data.requirementTitle || "",
        renovationType: data.renovationType || 1,
        houseArea: data.houseArea || "",
        renovationBudget: data.renovationBudget || "",
        detailedRequirement: data.detailedRequirement || "",
        expectedRenovationTime: data.expectedRenovationTime || "",
        contactName: data.contactName || "",
        contactPhone: data.contactPhone || "",
        city: data.city || "",
        detailedAddress: data.detailedAddress || "",
        attachmentUrls: data.attachmentUrls || [],
        createUserId: data.createUserId || data.userId || "",
        userId: data.userId || data.createUserId || ""
      };
    }
  } catch (error: any) {
    console.error("获取详情失败:", error);
    // 静默处理错误，不显示错误提示
  }
};

// 关闭页面
const handleClose = () => {
  router.go(-1);
};

// 监听路由变化
watch(
  () => route.query.id,
  () => {
    if (route.query.id) {
      initData();
    }
  },
  { immediate: true }
);

onMounted(() => {
  if (route.query.id) {
    initData();
  }
});
</script>

<style lang="scss" scoped>
.detail-container {
  width: 100%;
  min-height: 100%;
  background-color: white;
  .content-box {
    padding: 20px;
  }
  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 15px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
  :deep(.el-radio-group) {
    display: flex;
    gap: 20px;
  }
  .upload-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #999999;
  }
  .attachment-wrap {
    width: 100%;
  }
  .attachment-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: flex-start;
  }
  .attachment-card {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: #fafafa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }
  .attachment-card--placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #8c939d;
    pointer-events: none;
    border-style: dashed;
  }
  .attachment-card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
  .attachment-image {
    display: block;
    width: 100%;
    height: 100%;
  }
  .attachment-video-thumb {
    display: block;
    width: 100%;
    height: 100%;
    vertical-align: top;
    pointer-events: none;
    object-fit: cover;
  }
  .video-overlay {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
    background: rgb(0 0 0 / 25%);
  }
  .video-overlay .play-icon {
    font-size: 28px;
    color: #ffffff;
  }
  .detail-footer {
    padding: 20px 0 0;
    margin-top: 20px;
    text-align: center;
    border-top: 1px solid #ebeef5;
  }
}
</style>
