<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <div class="table-header-btn">
          <el-tabs v-model="activeName" class="tabs" @tab-click="handleClick">
            <el-tab-pane v-for="tab in allTabOptions" :key="tab.name" :label="tab.label" :name="tab.name" />
          </el-tabs>
        </div>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!--        <el-button type="primary" link @click="showDishDialog(scope.row)"> 查看菜品 </el-button>-->
        <el-button link type="primary" @click="toDetail(scope.row)"> 订单详情 </el-button>
      </template>
    </ProTable>
    <!-- 菜品详情弹窗 -->
    <el-dialog v-model="dishDialogVisible" title="菜品详情" width="600">
      <el-table :data="dishList" border>
        <el-table-column prop="category" label="菜品类别" width="150" />
        <el-table-column prop="name" label="菜品名称" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="120">
          <template #default="scope"> {{ scope.row.quantity }}份 </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="orderManagement">
import { onActivated, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getThaliList, getCpList } from "@/api/modules/orderManagement";
import { localGet, usePermission } from "@/utils";
import { formatCurrency } from "@/utils/formatCurrency";

const router = useRouter();
const proTable = ref<ProTableInstance>();
const activeName = ref("");
const dishDialogVisible = ref(false);
const dishList = ref<any[]>([]);

// 状态标签选项
const allTabOptions = [
  { label: "全部", name: "" },
  { label: "待使用", name: "1" },
  { label: "已完成", name: "2" },
  { label: "已退款", name: "5" }
];

// 状态映射
const statusMap: Record<string, string> = {
  0: "待支付",
  1: "待使用",
  2: "已完成",
  3: "已过期",
  4: "已取消",
  5: "已退款",
  6: "退款失败",
  7: "已完成"
};

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: "index",
    label: "序号",
    width: 80,
    render: (scope: any) => {
      return scope.$index + (proTable.value!.pageable.pageNum - 1) * proTable.value!.pageable.pageSize + 1;
    }
  },
  {
    prop: "orderNo",
    label: "订单编号",
    search: {
      el: "input"
    }
  },
  {
    prop: "couponName",
    label: "商品名称",
    search: {
      el: "input"
    }
  },
  {
    prop: "couponCount",
    label: "数量",
    render: (scope: any) => {
      return scope.row.couponCount ? `x${scope.row.couponCount}` : "--";
    }
  },
  {
    prop: "price",
    label: "实付款",
    render: (scope: any) => {
      return formatCurrency(scope.row.price, 2, "￥") || "--";
    }
  },
  {
    prop: "estimatedIncome",
    label: "本单预计收入",
    render: (scope: any) => {
      return formatCurrency(scope.row.expectIncome, 2, "￥") || "--";
    }
  },
  {
    prop: "orderTime",
    label: "下单时间",
    isShow: false,
    search: {
      el: "date-picker",
      props: {
        type: "daterange",
        "range-separator": " - ",
        "start-placeholder": "开始日期",
        "end-placeholder": "结束日期"
      }
    }
  },
  {
    prop: "buyTime",
    label: "下单时间",
    render: (scope: any) => {
      return scope.row.buyTime?.replace(/-/g, "/") || "--";
    }
  },
  {
    prop: "status",
    label: "状态",
    render: (scope: any) => {
      return statusMap[scope.row.status] || "--";
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  storeId: localGet("createdId"),
  groupType: localGet("businessSection"),
  status: activeName
});
const type = ref(false);
// 页面加载时触发查询
onMounted(async () => {
  type.value = await usePermission("查看订单");
  proTable.value?.getTableList();
});

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

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

// 格式化日期为 yyyy/mm/dd
const formatDate = (date: string | Date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 获取表格列表
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // 将状态标签的值添加到请求参数中
  if (activeName.value) {
    newParams.status = activeName.value;
  }
  // 处理 orderTime 参数，转换为 startTime 和 endTime
  if (newParams.orderTime && Array.isArray(newParams.orderTime) && newParams.orderTime.length === 2) {
    newParams.startTime = formatDate(newParams.orderTime[0]);
    newParams.endTime = formatDate(newParams.orderTime[1]);
    delete newParams.orderTime;
  }
  return getThaliList(newParams);
};

// 状态标签切换
const handleClick = () => {
  // proTable.value?.getTableList();
};

// 显示菜品弹窗
const showDishDialog = (row: any) => {
  // TODO: 根据实际API获取菜品数据
  // const params = {
  //   storeId: "104",
  //   status: "1"
  // };
  // let res: any = await getCpList(params);
  // if (res && res.code == 200) {
  //   dishList.value = res.data.records;
  // }
  // 这里先使用模拟数据
  dishList.value = [
    { category: "蔬菜", name: "黄豆芽", price: 5, quantity: 1 },
    { category: "荤菜", name: "虾滑", price: 12, quantity: 1 }
  ];
  dishDialogVisible.value = true;
};

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

<style lang="scss" scoped>
.table-header-btn {
  .tabs {
    :deep(.el-tabs__nav-wrap::after) {
      height: 0;
    }
  }
}
</style>
