<template>
  <div class="table-box button-table">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <div class="action-buttons">
          <el-button :icon="Plus" class="button" type="primary" @click="handleAdd"> 新增 </el-button>
        </div>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button v-if="scope.row.auditStatus !== '0'" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
        <el-button link type="primary" @click="toDetail(scope.row)">查看详情</el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="decorationManagement">
import { reactive, ref, onMounted, onActivated } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getDecorationPage, deleteDecoration } from "@/api/modules/storeDecoration";
import { localGet } from "@/utils";

const router = useRouter();
const proTable = ref<ProTableInstance>();

// 装修类型枚举
const decorationTypeEnum = [
  { label: "新房装修", value: "1" },
  { label: "旧房改造", value: "2" },
  { label: "局部装修", value: "3" }
];

// 审核状态枚举 (auditStatus: 0:待审核, 1:审核通过, 2:审核失败)
const auditStatusEnum = [
  { label: "待审核", value: "0" },
  { label: "审核通过", value: "1" },
  { label: "审核失败", value: "2" }
];

// 状态枚举 (status: 0:草稿, 1:已发布, 2:已下架)
const statusEnum = [
  { label: "草稿", value: "0" },
  { label: "已发布", value: "1" },
  { label: "已下架", value: "2" }
];

// 初始化请求参数
const initParam = reactive({
  storeId: localGet("createdId")
});

// 数据回调处理 - 根据图四的出参格式处理
const dataCallback = (data: any) => {
  // 出参格式: { code, data: { current, pages, records[], searchCount, size, total }, msg, success }
  // httpApi 的响应拦截器会处理响应，返回的 data 可能是整个响应对象或 data 字段
  // 如果 data 有 data 属性，说明是完整响应，需要取 data.data
  // 如果 data 直接有 records，说明已经是处理后的数据
  if (data && data.data && data.data.records) {
    // 完整响应格式: { code, data: { records, total, ... }, msg, success }
    return {
      list: data.data.records || [],
      total: data.data.total || 0
    };
  } else if (data && data.records) {
    // 已经是 data 字段: { records, total, ... }
    return {
      list: data.records || [],
      total: data.total || 0
    };
  }
  return {
    list: [],
    total: 0
  };
};

// 获取表格列表
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  
  // 转换 ProTable 的分页参数为后端需要的参数
  // ProTable 使用 pageNum 和 pageSize，后端使用 page 和 size
  if (newParams.pageNum) {
    newParams.page = newParams.pageNum;
    delete newParams.pageNum;
  }
  if (newParams.pageSize) {
    newParams.size = newParams.pageSize;
    delete newParams.pageSize;
  }
  
  // 处理日期范围 - createdTime 是日期范围选择器返回的数组
  // 将日期范围转换为 startTime 和 endTime 参数（格式: yyyy-MM-dd）
  if (newParams.createdTime && Array.isArray(newParams.createdTime) && newParams.createdTime.length === 2) {
    newParams.startTime = newParams.createdTime[0]; // 开始时间
    newParams.endTime = newParams.createdTime[1]; // 结束时间
    delete newParams.createdTime;
  }
  
  // 清理空值参数
  Object.keys(newParams).forEach(key => {
    if (newParams[key] === "" || newParams[key] === null || newParams[key] === undefined) {
      delete newParams[key];
    }
  });
  
  // 确保 storeId 存在
  if (!newParams.storeId) {
    newParams.storeId = localGet("createdId");
  }
  
  return getDecorationPage(newParams);
};

// 新增按钮点击事件
const handleAdd = () => {
  // TODO: 跳转到新增页面或打开新增对话框
  router.push(`/storeDecorationManagement/add`);
};

// 跳转详情页
const toDetail = (row: any) => {
  router.push(`/storeDecorationManagement/detail?id=${row.id}`);
};

// 删除装修记录
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定要删除这条装修记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // 调用删除接口 /renovation/requirement/delete
        const res: any = await deleteDecoration({ id: row.id });
        if (res.code === 200 || res.code === 0) {
          ElMessage.success("删除成功");
          // 刷新列表
          proTable.value?.getTableList();
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (error: any) {
        ElMessage.error(error?.msg || error?.message || "删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 表格列配置
const columns = reactive<ColumnProps<any>[]>([
  { type: "index", fixed: "left", label: "序号", width: 80 },
  {
    prop: "requirementTitle",
    label: "标题",
    render: (scope: any) => {
      return scope.row.requirementTitle || "--";
    },
    search: {
      el: "input",
      props: { placeholder: "请输入" }
    }
  },
  {
    prop: "renovationType",
    label: "装修类型",
    render: (scope: any) => {
      const type = decorationTypeEnum.find(item => item.value === String(scope.row.renovationType));
      return type ? type.label : "--";
    },
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: decorationTypeEnum,
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "houseArea",
    label: "面积(㎡)",
    render: (scope: any) => {
      return scope.row.houseArea || "--";
    }
  },
  {
    prop: "renovationBudget",
    label: "装修预算(万元)",
    render: (scope: any) => {
      return scope.row.renovationBudget || "--";
    }
  },
  {
    prop: "expectedRenovationTime",
    label: "期望装修时间",
    render: (scope: any) => {
      if (scope.row.expectedRenovationTime) {
        return scope.row.expectedRenovationTime.replace(/-/g, "/");
      }
      return "--";
    }
  },
  {
    prop: "auditStatus",
    label: "状态",
    render: (scope: any) => {
      // 使用 auditStatus 字段判断状态
      const auditStatus = scope.row.auditStatus;
      // 如果 auditStatus 为空、null、undefined，显示 --
      if (auditStatus === null || auditStatus === undefined || auditStatus === "") {
        return "--";
      }
      const statusMap: Record<string, { text: string; type: string }> = {
        "0": { text: "待审核", type: "warning" },
        "1": { text: "审核通过", type: "success" },
        "2": { text: "审核失败", type: "danger" }
      };
      const statusInfo = statusMap[String(auditStatus)];
      if (!statusInfo) {
        return "--";
      }
      return (
        <el-tag type={statusInfo.type as any} size="small">
          {statusInfo.text}
        </el-tag>
      );
    },
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: auditStatusEnum,
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "createdTime",
    label: "提交时间",
    render: (scope: any) => {
      if (scope.row.createdTime) {
        return scope.row.createdTime.replace(/-/g, "/");
      }
      return "--";
    },
    search: {
      el: "date-picker",
      props: {
        type: "daterange",
        "range-separator": "至",
        "start-placeholder": "请输入",
        "end-placeholder": "请输入",
        "value-format": "YYYY-MM-DD"
      },
      span: 2
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 180 }
]);

// 页面加载时触发查询
onMounted(() => {
  proTable.value?.getTableList();
});

// 从其他页面返回时触发查询
onActivated(() => {
  proTable.value?.getTableList();
});
</script>

<style lang="scss" scoped>
.action-buttons {
  display: flex;
  flex: 0 0 auto;
  gap: 10px;
  margin-right: 20px;
  .button {
    margin-bottom: 0;
  }
}
</style>
