<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>
          <el-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :disabled="true"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">({{ fileList.length }}/9)</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>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="imageViewerVisible"
      :url-list="imageViewerUrlList"
      :initial-index="imageViewerInitialIndex"
      @close="imageViewerVisible = false"
    />
  </div>
</template>

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

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 fileList = ref<UploadFile[]>([]);
const imageViewerVisible = ref(false);
const imageViewerUrlList = ref<string[]>([]);
const imageViewerInitialIndex = ref(0);

// 联系业主（跳转聊天页面）
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 || "业主"),
    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 || ""
      };

      // 处理附件列表
      if (formData.value.attachmentUrls && formData.value.attachmentUrls.length > 0) {
        fileList.value = formData.value.attachmentUrls.map((url: string, index: number) => ({
          uid: index,
          name: `图片${index + 1}`,
          url: url,
          status: "success"
        }));
      }
    }
  } catch (error: any) {
    console.error("获取详情失败:", error);
    // 静默处理错误，不显示错误提示
  }
};

// 图片预览
const handlePictureCardPreview = (file: UploadFile) => {
  if (file.url) {
    imageViewerUrlList.value = fileList.value.map((item: UploadFile) => item.url || "").filter(Boolean);
    imageViewerInitialIndex.value = fileList.value.findIndex((item: UploadFile) => item.uid === file.uid);
    imageViewerVisible.value = true;
  }
};

// 删除图片（详情页禁用，这里只是占位）
const handleRemove = () => {
  // 详情页不允许删除
};

// 关闭页面
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;
  }
  .detail-footer {
    padding: 20px 0 0;
    margin-top: 20px;
    text-align: center;
    border-top: 1px solid #ebeef5;
  }
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
  }
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
  }
}
</style>
