<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-row :gutter="40">
          <!-- 左侧列 -->
          <el-col :span="12">
            <el-form-item label="需求标题" required>
              <el-input v-model="formData.requirementTitle" 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="upload-wrapper">
                <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>
              <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-col>

          <!-- 右侧列 -->
          <el-col :span="12">
            <el-form-item label="提交时间">
              <el-input v-model="formData.createdTime" placeholder="请输入" disabled />
            </el-form-item>

            <el-form-item label="审核状态">
              <el-input v-model="auditStatusText" placeholder="请输入" disabled />
            </el-form-item>

            <el-form-item label="审核时间">
              <el-input v-model="formData.updatedTime" placeholder="请输入" disabled />
            </el-form-item>

            <el-form-item v-if="formData.auditStatus === 2" label="拒绝原因">
              <el-input
                v-model="formData.rejectionReason"
                type="textarea"
                :rows="4"
                placeholder="请输入"
                disabled
              />
              <div class="form-tip">根据审核状态 对应展示</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="detail-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</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="decorationDetail">
import { ref, computed, 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>({
  requirementTitle: "",
  renovationType: 1,
  houseArea: "",
  renovationBudget: "",
  detailedRequirement: "",
  expectedRenovationTime: "",
  contactName: "",
  contactPhone: "",
  city: "",
  detailedAddress: "",
  createdTime: "",
  auditStatus: 0,
  updatedTime: "",
  rejectionReason: "",
  attachmentUrls: []
});

const fileList = ref<UploadFile[]>([]);
const imageViewerVisible = ref(false);
const imageViewerUrlList = ref<string[]>([]);
const imageViewerInitialIndex = ref(0);

// 审核状态文本
const auditStatusText = computed(() => {
  const statusMap: Record<number, string> = {
    0: "待审核",
    1: "审核通过",
    2: "审核失败"
  };
  return statusMap[formData.value.auditStatus] || "--";
});

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

  try {
    const res = await getDecorationDetail({ id: id as string });
    if (res.code == 200 || res.code == 0) {
      const data = res.data || res.data?.data || {};
      formData.value = {
        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 || "",
        createdTime: data.createdTime || "",
        auditStatus: data.auditStatus ?? 0,
        updatedTime: data.updatedTime || "",
        rejectionReason: data.auditReason || data.rejectionReason || "", // 优先使用 auditReason 字段
        attachmentUrls: data.attachmentUrls || []
      };

      // 处理附件列表
      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);
};

// 确定按钮
const handleConfirm = () => {
  handleClose();
};

// 监听路由变化
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;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    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 {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  .form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    text-align: right;
  }

  .detail-footer {
    text-align: center;
    padding: 20px 0 0;
    margin-top: 20px;
    border-top: 1px solid #ebeef5;
  }

  .upload-wrapper {
    :deep(.el-upload) {
      display: inline-block;
    }

    :deep(.el-upload-list--picture-card) {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
      margin: 0;
      width: 100%;
    }

    :deep(.el-upload--picture-card) {
      width: 100%;
      margin: 0;
      display: none; // 禁用状态下隐藏上传按钮
    }

    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 100%;
      margin: 0;
      aspect-ratio: 1;
      height: auto;
    }

    // 确保图片缩略图正确显示
    :deep(.el-upload-list__item-thumbnail) {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
</style>
