<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <template #tableHeader>
        <div class="table-header">
          <el-button type="primary" @click="handleAdd"> 新建 </el-button>
        </div>
      </template>
      <template #imgUrl="{ row }">
        <el-image v-if="row.imgUrl" :src="row.imgUrl" fit="cover" style="width: 60px; height: 60px; border-radius: 6px" />
        <div v-else class="img-placeholder">无图</div>
      </template>
      <template #auditStatus="{ row }">
        <span>{{ auditStatusLabel(row.auditStatus) }}</span>
      </template>
      <template #shelfStatus="{ row }">
        <span>
          {{ row.shelfStatus === 1 ? "已上架" : row.shelfStatus === 2 ? "已下架" : "--" }}
        </span>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button link type="primary" @click="handleDetail(scope.row)"> 查看详情 </el-button>
        <!-- 上架按钮（仅审核通过且已下架时显示） -->
        <el-button
          v-if="scope.row.auditStatus === 1 && scope.row.shelfStatus === 2"
          link
          type="primary"
          @click="handleShelfToggle(scope.row, 1)"
        >
          上架
        </el-button>
        <!-- 下架按钮（仅审核通过且已上架时显示） -->
        <el-button
          v-if="scope.row.auditStatus === 1 && scope.row.shelfStatus === 1"
          link
          type="primary"
          @click="handleShelfToggle(scope.row, 2)"
        >
          下架
        </el-button>
        <!-- 编辑按钮（审核通过、审核拒绝、已下架、已结束时可编辑） -->
        <el-button
          v-if="scope.row.auditStatus === 1 || scope.row.auditStatus === 2"
          link
          type="primary"
          @click="handleEdit(scope.row)"
        >
          编辑
        </el-button>
        <!-- 删除按钮（审核通过、审核拒绝、已下架、已结束时可删除） -->
        <el-button
          v-if="scope.row.auditStatus === 1 || scope.row.auditStatus === 2"
          link
          type="primary"
          @click="handleDelete(scope.row)"
        >
          删除
        </el-button>
        <!-- 查看拒绝原因按钮（仅审核拒绝时显示） -->
        <el-button
          v-if="scope.row.auditStatus === 2 && scope.row.auditReason"
          link
          type="primary"
          @click="handleViewReason(scope.row)"
        >
          查看原因
        </el-button>
      </template>
    </ProTable>
    <!-- 删除确认弹窗 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="500px">
      <div style="padding: 20px 0">确定要删除该价目表吗？</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="confirmDelete"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看拒绝原因弹窗 -->
    <el-dialog v-model="reasonDialogVisible" title="查看拒绝原因" width="600px">
      <div class="reject-reason-content">
        <div class="reject-reason-item">
          <div class="reject-reason-label">价目表名称：</div>
          <div class="reject-reason-value">
            {{ currentReasonData.name || "--" }}
          </div>
        </div>
        <div class="reject-reason-item">
          <div class="reject-reason-label">拒绝原因：</div>
          <div class="reject-reason-value reject-reason-text">
            {{ currentReasonData.reason || "暂无拒绝原因" }}
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="reasonDialogVisible = false"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="priceList">
import { reactive, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { localGet } from "@/utils";
import {
  AUDIT_STATUS_LABEL,
  getPriceListPage,
  transformListItem,
  deletePriceItem,
  updateShelfStatus,
  getModuleTypeByBusinessSection,
  MODULE_TYPES,
  type PriceListRow
} from "@/api/modules/priceList";

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

// 删除确认弹窗
const deleteDialogVisible = ref(false);
const deletingItem = ref<PriceListRow | null>(null);

// 查看拒绝原因弹窗
const reasonDialogVisible = ref(false);
const currentReasonData = ref<{ name: string; reason: string }>({
  name: "",
  reason: ""
});

// 是否特色美食（经营板块为 1，与商家端一致：仅美食才显示类型列、新建时选择菜品/套餐）
const isFoodModule = computed(() => getModuleTypeByBusinessSection(initParam.businessSection) === MODULE_TYPES.FOOD);

// 列配置（与商家端保持字段含义一致）；特色美食时增加「类型」列
const baseColumns: ColumnProps<PriceListRow>[] = [
  {
    prop: "dishName",
    label: "名称",
    search: {
      key: "prodName",
      el: "input",
      props: {
        placeholder: "请输入名称"
      }
    }
  },
  {
    prop: "imgUrl",
    label: "图片",
    align: "center"
  },
  {
    prop: "dishPrice",
    label: "价格"
  },
  {
    prop: "dishUnit",
    label: "单位"
  },
  {
    prop: "auditStatus",
    label: "审核状态",
    search: {
      key: "status",
      el: "select",
      props: { placeholder: "请选择审核状态" }
    },
    enum: [
      { label: "审核中", value: 0 },
      { label: "审核通过", value: 1 },
      { label: "审核拒绝", value: 2 }
    ],
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "shelfStatus",
    label: "上下架状态",
    search: {
      key: "origin",
      el: "select",
      props: { placeholder: "请选择上下架状态" }
    },
    enum: [
      { label: "已上架", value: 1 },
      { label: "已下架", value: 2 }
    ],
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "startCreatedTime",
    label: "提交时间",
    isShow: false,
    search: {
      el: "date-picker",
      props: {
        type: "datetime",
        valueFormat: "YYYY-MM-DD HH:mm:ss",
        placeholder: "请输入"
      }
    }
  },
  {
    prop: "endCreatedTime",
    label: "至",
    isShow: false,
    search: {
      el: "date-picker",
      props: {
        type: "datetime",
        valueFormat: "YYYY-MM-DD HH:mm:ss",
        placeholder: "请输入"
      }
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
];

const columns = computed<ColumnProps<PriceListRow>[]>(() => {
  if (!isFoodModule.value) return baseColumns;
  const typeCol: ColumnProps<PriceListRow> = {
    prop: "cuisineType",
    label: "类型",
    width: 88,
    enum: [
      { label: "菜品", value: 1 },
      { label: "套餐", value: 2 }
    ],
    fieldNames: { label: "label", value: "value" }
  };
  return [baseColumns[0], typeCol, ...baseColumns.slice(1)];
});

// 初始查询参数：门店 + 经营板块，与其他商家端页面保持一致
const initParam = reactive({
  storeId: localGet("createdId") || "",
  businessSection: localGet("businessSection") || "1"
});

// 将审核状态值映射为文案
const auditStatusLabel = (status: number | null) => {
  if (status === null || status === undefined) return "--";
  return AUDIT_STATUS_LABEL[status] || "--";
};

// 表格请求方法
// 说明：不同经营板块在 api/modules/priceList 中会走不同的后台接口
const getTableList = (params: any) => {
  const query: any = {
    ...params,
    storeId: initParam.storeId,
    businessSection: initParam.businessSection
  };

  // shelfStatus 字段名与后台一致，直接透传
  return getPriceListPage(query);
};

// 统一处理接口返回的数据结构（入参已是后端的 data 字段）
const dataCallback = (payload: any) => {
  const records = Array.isArray(payload) ? payload : payload.records || [];
  const total = payload.total ?? records.length;

  return {
    list: records.map((item: any) => transformListItem(item)),
    total
  };
};

// 详情（进入编辑页只读模式，不跳转独立详情页）
const handleDetail = (row: PriceListRow) => {
  const query: Record<string, string> = {
    id: String(row.id),
    businessSection: String(initParam.businessSection),
    mode: "detail"
  };
  if (row.cuisineType !== undefined && row.cuisineType !== null) {
    query.cuisineType = String(row.cuisineType);
  }
  router.push({ path: "/priceList/edit", query });
};

// 新建：直接进入编辑页，美食类别在页面内选择类型（菜品/套餐）
const handleAdd = () => {
  router.push({
    path: "/priceList/edit",
    query: { businessSection: String(initParam.businessSection) }
  });
};

// 编辑
const handleEdit = (row: PriceListRow) => {
  const query: Record<string, string> = {
    id: String(row.id),
    businessSection: String(initParam.businessSection)
  };
  if (row.cuisineType !== undefined && row.cuisineType !== null) {
    query.cuisineType = String(row.cuisineType);
  }
  router.push({ path: "/priceList/edit", query });
};

// 删除
const handleDelete = (row: PriceListRow) => {
  deletingItem.value = row;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!deletingItem.value) return;
  try {
    const res: any = await deletePriceItem(deletingItem.value.id);
    if (res && res.code === 200) {
      ElMessage.success("删除成功");
      deleteDialogVisible.value = false;
      deletingItem.value = null;
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除失败:", error);
  }
};

// 上架/下架切换
const handleShelfToggle = async (row: PriceListRow, shelfStatus: number) => {
  const actionText = shelfStatus === 1 ? "上架" : "下架";
  ElMessageBox.confirm(`确定要${actionText}该价目表吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const res: any = await updateShelfStatus(row.id, shelfStatus);
        if (res && res.code === 200) {
          ElMessage.success(`${actionText}成功`);
          proTable.value?.getTableList();
        } else {
          ElMessage.error(res?.msg || "操作失败");
        }
      } catch (error) {
        console.error("操作失败:", error);
      }
    })
    .catch(() => {
      // 用户取消操作，不做任何处理
    });
};

// 查看拒绝原因
const handleViewReason = (row: PriceListRow) => {
  currentReasonData.value = {
    name: row.dishName || "",
    reason: row.auditReason || "暂无原因"
  };
  reasonDialogVisible.value = true;
};
</script>

<style scoped lang="scss">
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 12px 0;
  .table-header-title {
    font-size: 16px;
    font-weight: 600;
  }
}
.img-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  font-size: 12px;
  color: #909399;
  background-color: #f2f3f5;
  border-radius: 6px;
}
.reject-reason-content {
  padding: 20px 0;
  .reject-reason-item {
    display: flex;
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .reject-reason-label {
      flex-shrink: 0;
      min-width: 100px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
    }
    .reject-reason-value {
      flex: 1;
      font-size: 14px;
      color: #303133;
      word-break: break-word;
      &.reject-reason-text {
        min-height: 80px;
        padding: 12px;
        line-height: 1.6;
        white-space: pre-wrap;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }
}
</style>
