<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getBorrowReturnRecordListApi, type BorrowReturnRecordDTO, type BorrowReturnRecordQuery } from "@/api/shop/order";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

defineOptions({
  name: "BorrowReturnRecord"
});

const props = defineProps<{
  goodsId: number;
}>();

const formRef = ref();
const tableRef = ref();

const searchFormParams = ref<BorrowReturnRecordQuery>({
  goodsId: props.goodsId,
  status: null
});

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

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

const getList = async () => {
  try {
    loading.value = true;
    const { data } = await getBorrowReturnRecordListApi({
      ...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 formatDateTime = (dateTime: string | null) => {
  if (!dateTime) return { date: '-', time: '' };

  const date = new Date(dateTime);
  const dateStr = date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
  const timeStr = date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });

  return {
    date: dateStr,
    time: timeStr
  };
};

onMounted(() => {
  getList();
});
</script>

<template>
  <div class="borrow-return-record">
    <el-form ref="formRef" :inline="true" :model="searchFormParams"
      class="search-form bg-bg_color flex w-[99/100] ">
      <el-form-item prop="status">
        <el-select v-model="searchFormParams.status" placeholder="请选择状态" clearable class="!w-[180px]">
          <el-option label="未退还" :value="0" />
          <el-option label="待审批" :value="1" />
          <el-option label="已通过" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch" style="margin-right: 10px;">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="table-container">
      <el-table ref="tableRef" v-loading="loading" :data="dataList"
      height="calc(100vh - 300px)" row-key="orderId" border>
        <el-table-column label="订单ID" prop="orderId" width="70" />
        <el-table-column label="下单时间" prop="orderTime" width="100">
          <template #default="{ row }">
            <div v-if="row.orderTime" class="flex flex-col text-center">
              <span>{{ formatDateTime(row.orderTime).date }}</span>
              <span>{{ formatDateTime(row.orderTime).time }}</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="机柜" prop="cabinetName" width="70">
          <template #default="{ row }">
            {{ row.cabinetName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="格口号" prop="cellNo" width="70">
          <template #default="{ row }">
            {{ row.cellNo || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="goodsPrice" width="90">
          <template #default="{ row }">{{ row.goodsPrice }}元</template>
        </el-table-column>
        <!-- <el-table-column label="商品数量" prop="quantity" width="100" /> -->
        <el-table-column label="姓名" prop="orderName" width="70" />
        <el-table-column label="手机号" prop="orderMobile" width="120" />
        <el-table-column label="支付方式" prop="paymentMethod" width="90">
          <template #default="{ row }">
            {{ { wechat: '微信支付', balance: '借呗支付' }[row.paymentMethod] || row.paymentMethod }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="statusStr" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === 2 ? 'success' : row.status === 3 ? 'danger' : 'info'">
              {{ row.statusStr }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="归还时间" prop="returnTime" width="100">
          <template #default="{ row }">
            <div v-if="row.returnTime" class="flex flex-col text-center">
              <span>{{ formatDateTime(row.returnTime).date }}</span>
              <span>{{ formatDateTime(row.returnTime).time }}</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="归还图片" prop="returnImages" width="140">
          <template #default="{ row }">
            <div v-if="row.returnImages" class="flex gap-2">
              <el-image v-for="(img, index) in row.returnImages.split(',')" :key="index" :src="img"
                :preview-src-list="row.returnImages.split(',')" :z-index="9999" :preview-teleported="true"
                :hide-on-click-modal="true" fit="cover" class="rounded" width="40" height="40" />
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审批人" prop="auditName" width="90" />
        <el-table-column label="审批时间" prop="auditTime" width="100">
          <template #default="{ row }">
            <div v-if="row.auditTime" class="flex flex-col text-center">
              <span>{{ formatDateTime(row.auditTime).date }}</span>
              <span>{{ formatDateTime(row.auditTime).time }}</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核图片" prop="auditImages" width="140">
          <template #default="{ row }">
            <div v-if="row.auditImages" class="flex gap-2">
              <el-image v-for="(img, index) in row.auditImages.split(',')" :key="index" :src="img"
                :preview-src-list="row.auditImages.split(',')" :z-index="9999" :preview-teleported="true"
                :hide-on-click-modal="true" fit="cover" class="rounded" width="40" height="40" />
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核说明" prop="auditRemark" width="90" />
      </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>
</template>

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

.table-container {
  margin-top: 0;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 0;
  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>
