<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getOrderListApi, exportOrderExcelApi, type OrderDTO, OrderQuery } from "@/api/shop/order";
import { allCabinets, SmartCabinetDTO } from "@/api/cabinet/smart-cabinet";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { ElMessage } from "element-plus";
import { useRoute } from 'vue-router'

defineOptions({
  name: "ShopOrder"
});
const route = useRoute();

const formRef = ref();
const tableRef = ref();
const cabinets = ref<SmartCabinetDTO[]>([]);

const searchFormParams = ref<OrderQuery>({
  cabinetId: null,
  orderId: null,
  cellId: null,
  status: null,
  payStatus: null,
  paymentMethod: null,
  startTime: "",
  endTime: "",
  payTime: "",
  returnStatus: null,
});

const pagination = ref({
  pageSize: 8,
  currentPage: 1,
  total: 0
});

const loading = ref(false);
const dataList = ref<OrderDTO[]>([]);

onMounted(async () => {
  const { data } = await allCabinets();
  cabinets.value = data;
});

const getList = async () => {
  try {
    loading.value = true;
    const { data } = await getOrderListApi({
      ...searchFormParams.value,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};

const resetForm = () => {
  formRef.value.resetFields();
  onSearch();
};

const onSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  getList();
};

const onCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  getList();
};

const exportLoading = ref(false);

const handleExport = async () => {
  try {
    exportLoading.value = true;
    const dateSuffix = searchFormParams.value.payTime
      ? `_${searchFormParams.value.payTime.split(' ')[0].replace(/-/g, '')}`
      : '';
    const fileName = `订单列表${dateSuffix}.xlsx`;
    await exportOrderExcelApi({
      ...searchFormParams.value,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    }, fileName);
    ElMessage.success('导出任务已开始，请稍后查看下载文件');
  } catch (e) {
    ElMessage.error('导出失败');
  } finally {
    exportLoading.value = false;
  }
};

watch(() => route.query.cellId,
  (newVal) => {
    searchFormParams.value.cellId = newVal ? Number(newVal) : null;
    getList();
  }
  ,
  {
    immediate: true
  });

getList();
</script>

<template>
  <div class="main flex">
    <!-- 左侧柜机列表 -->
    <div class="w-[200px] mr-4 bg-white rounded shadow p-4">
      <div class="text-lg font-bold mb-4">柜机列表</div>
      <div class="space-y-2">
        <div v-for="cabinet in cabinets" :key="cabinet.cabinetId" class="p-2 rounded cursor-pointer hover:bg-gray-100"
          :class="{ 'bg-blue-50': searchFormParams.cabinetId === cabinet.cabinetId }"
          @click="searchFormParams.cabinetId = cabinet.cabinetId; onSearch()">
          {{ cabinet.cabinetName }}
        </div>
      </div>
    </div>
    <div class="flex-1">
      <el-form ref="formRef" :inline="true" :model="searchFormParams"
        class="search-form bg-bg_color flex w-[99/100] pl-[22px] pt-[12px]">
        <!-- <el-form-item label="时间范围：">
        <el-date-picker v-model="searchFormParams.startTime" type="date" placeholder="开始时间"
          value-format="YYYY-MM-DD HH:mm:ss" class="!w-[200px]" />
        <span class="mx-2">至</span>
        <el-date-picker v-model="searchFormParams.endTime" type="date" placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss" class="!w-[200px]" />
      </el-form-item> -->
        <el-form-item>
          <el-date-picker v-model="searchFormParams.payTime" type="date" placeholder="支付时间"
            value-format="YYYY-MM-DD HH:mm:ss" class="!w-[200px]" />
        </el-form-item>
        <el-form-item prop="orderId">
          <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.orderId" placeholder="请输入订单编号" clearable
            class="!w-[200px]" />
        </el-form-item>
        <el-form-item prop="cellId">
          <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.cellId" placeholder="请输入格口ID" clearable
            class="!w-[200px]" />
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchFormParams.status" placeholder="请选择订单状态" clearable class="!w-[180px]">
            <el-option label="待付款" :value="1" />
            <el-option label="已付款" :value="2" />
            <el-option label="已发货" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已取消" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item prop="payStatus">
          <el-select v-model="searchFormParams.payStatus" placeholder="请选择支付状态" clearable class="!w-[180px]">
            <el-option label="未支付" :value="1" />
            <el-option label="已支付" :value="2" />
            <el-option label="退款中" :value="3" />
            <el-option label="已退款" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item prop="returnStatus">
          <el-select v-model="searchFormParams.returnStatus" placeholder="请选择退还状态" clearable class="!w-[180px]">
            <el-option label="未退还" :value="0" />
            <el-option label="已退还" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item prop="paymentMethod">
          <el-select v-model="searchFormParams.paymentMethod" placeholder="请选择支付方式" clearable class="!w-[180px]">
            <el-option label="微信支付" value="wechat" />
            <el-option label="借呗支付" value="balance" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" class="search-form bg-bg_color flex w-[99/100] pl-[22px] pt-0">
        <el-form-item>
          <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch" style="margin-right: 10px;">
            搜索
          </el-button>
          <el-button type="success" :loading="exportLoading" :icon="useRenderIcon('vscode-icons:file-type-excel2')"
            @click="handleExport">
            导出Excel
          </el-button>
        </el-form-item>
      </el-form>

      <div class="table-container">
        <el-table ref="tableRef" v-loading="loading" :data="dataList" row-key="orderId" border>
          <el-table-column label="订单ID" prop="orderId" width="120" />
          <el-table-column label="商品名称" prop="goodsNames">
            <template #default="{ row }">
              <span v-if="row.goodsNames">
                {{ row.goodsNames.split(',').join(', ') }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="商品封面" prop="coverImgs" width="100">
            <template #default="{ row }">
              <div v-if="row.coverImgs" class="flex gap-2">
                <el-image v-for="(img, index) in row.coverImgs.split(',')" :key="index" :src="img"
                  :preview-src-list="row.coverImgs.split(',')" :z-index="9999" :preview-teleported="true"
                  :hide-on-click-modal="true" fit="cover" class="rounded" width="60" height="60" />
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="name" width="120" />
          <el-table-column label="手机号" prop="mobile" width="120" />
          <el-table-column label="订单金额" prop="totalAmount" width="120">
            <template #default="{ row }">{{ row.totalAmount }}元</template>
          </el-table-column>
          <el-table-column label="订单状态" prop="status" width="120">
            <template #default="{ row }">
              <el-tag :type="row.status === 2 ? 'success' : row.status === 5 ? 'danger' : 'info'">
                {{ { 1: '待付款', 2: '已付款', 3: '已发货', 4: '已完成', 5: '已取消' }[row.status] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="支付状态" prop="payStatus" width="120">
            <template #default="{ row }">
              <el-tag :type="row.payStatus === 2 ? 'success' : 'info'">
                {{ { 1: '未支付', 2: '已支付', 3: '退款中', 4: '已退款' }[row.payStatus] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="退还状态" prop="returnStatus" width="120">
            <template #default="{ row }">
              <el-tag :type="row.returnStatus === 1 ? 'success' : 'info'">
                {{ { 0: '未退还', 1: '已退还' }[row.returnStatus] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="支付方式" prop="paymentMethod" width="120">
            <template #default="{ row }">
              {{ { wechat: '微信支付', balance: '借呗支付' }[row.paymentMethod] || row.paymentMethod }}
            </template>
          </el-table-column>
          <el-table-column label="支付时间" prop="payTime" width="180">
            <template #default="{ row }">
              {{ row.payTime ? new Date(row.payTime).toLocaleString() : '-' }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column> -->
        </el-table>
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[8, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="onSizeChange" @current-change="onCurrentChange" class="pagination" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 12px;
  }
}

.right-btn {
  margin: 0;
}

.table-container {
  margin-top: 8px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;

  .el-table {
    flex: 1;
    overflow: hidden;
  }

  .pagination {
    margin-top: 10px;
  }
}
</style>