<template>
  <div class="table-box button-table">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button link type="primary" @click="handleContact(scope.row)"> 联系业主 </el-button>
        <el-button link type="primary" @click="handleView(scope.row)"> 查看详情 </el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="decorationCompany">
import { reactive, ref, onMounted, onActivated } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getDecorationPage } 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" }
];

// 沟通状态枚举 (hasCommunicated: false:未沟通, true:已沟通)
const communicationStatusEnum = [
  { label: "未沟通", value: "false" },
  { label: "已沟通", value: "true" }
];

// 初始化请求参数
const initParam = reactive({});

// 数据回调处理
const dataCallback = (data: any) => {
  if (data && data.data && data.data.records) {
    return {
      list: data.data.records || [],
      total: data.data.total || 0
    };
  } else if (data && data.records) {
    return {
      list: data.records || [],
      total: data.total || 0
    };
  }
  return {
    list: [],
    total: 0
  };
};

// 获取表格列表
const getTableList = (params: any) => {
  let newParams: any = {};

  // 只保留分页参数 page 和 size
  if (params.pageNum) {
    newParams.page = params.pageNum;
  }
  if (params.pageSize) {
    newParams.size = params.pageSize;
  }

  // 处理沟通状态参数 hasCommunicated（将字符串转换为布尔值）
  // true:已沟通, false:未沟通
  if (params.hasCommunicated !== undefined && params.hasCommunicated !== "" && params.hasCommunicated !== null) {
    // 将字符串 "true"/"false" 转换为布尔值 true/false
    if (params.hasCommunicated === "true" || params.hasCommunicated === true) {
      newParams.hasCommunicated = true;
    } else if (params.hasCommunicated === "false" || params.hasCommunicated === false) {
      newParams.hasCommunicated = false;
    }
  }

  // 处理装修类型参数
  if (params.renovationType !== undefined && params.renovationType !== "" && params.renovationType !== null) {
    newParams.renovationType = params.renovationType;
  }

  // 调用 /renovation/requirement/getPage 接口（只传 page、size 和筛选条件）
  return getDecorationPage(newParams);
};

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

// 查看详情
const handleView = (row: any) => {
  router.push(`/storeDecorationManagement/decorationCompanyDetail?id=${row.id}`);
};

// 表格列配置
const columns = reactive<ColumnProps<any>[]>([
  { type: "index", fixed: "left", label: "序号", width: 80 },
  {
    prop: "requirementTitle",
    label: "标题",
    render: (scope: any) => {
      return scope.row.requirementTitle || "--";
    }
  },
  {
    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: "city",
    label: "所在城市",
    render: (scope: any) => {
      return scope.row.city || "--";
    }
  },
  {
    prop: "hasCommunicated",
    label: "状态",
    render: (scope: any) => {
      const hasCommunicated = scope.row.hasCommunicated;
      const statusMap: Record<string, { text: string; type: string }> = {
        true: { text: "已沟通", type: "success" },
        false: { text: "未沟通", type: "info" }
      };
      const statusKey = String(hasCommunicated);
      const statusInfo = statusMap[statusKey] || { text: "--", type: "info" };
      return (
        <el-tag type={statusInfo.type as any} size="small">
          {statusInfo.text}
        </el-tag>
      );
    },
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: communicationStatusEnum,
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "createdTime",
    label: "发布时间",
    render: (scope: any) => {
      if (scope.row.createdTime) {
        return scope.row.createdTime.replace(/-/g, "/");
      }
      return "--";
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 180 }
]);

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

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

<style lang="scss" scoped></style>
