<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约日期" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    
    <br>

    <el-table v-loading="loading" :data="reservationList">
      <el-table-column label="预约日期" align="center">
        <template #default="scope">
          {{ formatDateYMD(scope.row.reservationTimeSlot && scope.row.reservationTimeSlot.date) }}
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reserveTime" />
      <el-table-column label="预约总人数" align="center" prop="totalVisitors" />
      <el-table-column label="整单状态" align="center">
        <template #default="scope">
          <el-tooltip v-if="Number(scope.row.status) === 3 && scope.row.remark" :content="`拒绝原因：${scope.row.remark}`" placement="top" effect="dark">
            <el-tag :type="statusType(scope.row.status)" style="cursor: help;">{{ statusText(scope.row.status) }}</el-tag>
          </el-tooltip>
          <el-tag v-else :type="statusType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="openDetail(scope.row)">详情</el-button>
          <el-button
            v-if="Number(scope.row.status) === 0 || Number(scope.row.status) === 1"
            link
            type="warning"
            icon="CloseBold"
            @click="handleCancel(scope.row)"
          >取消预约</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <div class="pagination-wrapper">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- 预约详情对话框 -->
    <el-dialog title="预约详情" v-model="detailOpen" width="700px" append-to-body>
      <div class="audit-info">
        <div class="audit-section-title">预约信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约日期">{{ formatDateYMD(detailData.reservationTimeSlot && detailData.reservationTimeSlot.date) }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ detailData.reserveTime }}</el-descriptions-item>
          <el-descriptions-item label="预约总人数">{{ detailData.totalVisitors }}</el-descriptions-item>
          <el-descriptions-item v-if="Number(detailData.status) === 1" label="整单核验二维码">
            <el-image v-if="detailData.qrCode" :src="qrImg('/api' + detailData.qrCode)" :preview-src-list="[qrImg('/api' + detailData.qrCode)]" style="width: 160px; height: 160px;" />
          </el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="left"><span class="audit-section-title">游客信息</span></el-divider>
        <div class="audit-visitors" v-if="detailData.reservationVisitors && detailData.reservationVisitors.length">
          <el-table :data="detailData.reservationVisitors" size="small" style="margin-top: 12px;">
            <el-table-column label="姓名" prop="realName" align="center" />
            <el-table-column label="身份证号" prop="idCard" align="center" />
            <el-table-column label="手机号" prop="phone" align="center" />
            <el-table-column label="核验状态" align="center">
              <template #default="scope">
                <el-tag :type="Number(scope.row.verifyStatus) === 1 ? 'success' : 'warning'">
                  {{ Number(scope.row.verifyStatus) === 1 ? '已验证' : '未验证' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="核验二维码" align="center">
              <template #default="scope">
                <el-image v-if="scope.row.visitorQrCode" :src="qrImg('/api' + scope.row.visitorQrCode)" :preview-src-list="[qrImg('/api' + scope.row.visitorQrCode)]" style="width: 120px; height: 120px;" />
                <span v-else>—</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="audit-visitors-empty" v-else>
          <el-empty description="暂无游客信息" image-size="80" />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen=false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reservation">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue';
import { listReservation, getReservation, delReservation, addReservation, updateReservation } from "@/api/reservation";
import { getCurrentSysUser } from "@/api/sysUser";

const { proxy } = getCurrentInstance();

const reservationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const isAdd = ref(false)

const detailOpen = ref(false)
const detailData = ref({})

function qrImg(url) {
  if (!url) return ''
  const u = encodeURIComponent(url)
  return `https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${u}`
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    dateRange: null,
    startDate: null,
    endDate: null,
    status: null,
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预约列表 */
function getList() {
  loading.value = true;
  const qp = {
    ...queryParams.value,
    startDate: queryParams.value.dateRange && queryParams.value.dateRange[0],
    endDate: queryParams.value.dateRange && queryParams.value.dateRange[1]
  }
  listReservation(qp).then(response => {
    reservationList.value = response.list;
    total.value = response.total;
    loading.value = false;
  });
}

// 改变每页条数大小
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

// 换页
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    timeSlotId: null,
    totalVisitors: null,
    qrCode: null,
    status: null,
    createTime: null,
    updateTime: null,
    updater: null,
    remark: null
  };
  const reservationRef = proxy.$refs["reservationRef"]
  if (reservationRef) {
    reservationRef.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  const queryRef = proxy.$refs["queryRef"]
  if (queryRef) {
    queryRef.resetFields();
  }
  handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约";
  isAdd.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReservation(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预约";
    isAdd.value = false;
  });
}

function openDetail(row) {
  getReservation(row.id).then(response => {
    detailData.value = response.data
    detailOpen.value = true
  })
}

const formatDateCN = (val) => {
  if (!val) return ''
  let y, M, D
  if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) {
    const parts = val.split('-')
    y = Number(parts[0])
    M = Number(parts[1])
    D = Number(parts[2])
  } else {
    const d = new Date(val)
    if (isNaN(d.getTime())) return ''
    y = d.getFullYear()
    M = d.getMonth() + 1
    D = d.getDate()
  }
  return `${y}年${M}月${D}日`
}

const formatTimeHMS = (v) => {
  if (!v) return ''
  if (typeof v === 'string') {
    const m = v.match(/\d{2}:\d{2}:\d{2}/)
    if (m) return m[0]
    const m2 = v.match(/\d{2}:\d{2}/)
    return m2 ? `${m2[0]}:00` : ''
  }
  const d = new Date(v)
  if (isNaN(d.getTime())) return ''
  const HH = String(d.getHours()).padStart(2, '0')
  const mm = String(d.getMinutes()).padStart(2, '0')
  const ss = String(d.getSeconds()).padStart(2, '0')
  return `${HH}:${mm}:${ss}`
}

function handleCancel(row) {
  const dateStr = formatDateCN(row.reservationTimeSlot && row.reservationTimeSlot.date)
  const timeStr = formatTimeHMS(row.reserveTime)
  const ppl = row.totalVisitors
  const msg = `是否要取消${dateStr} ${timeStr} 预约人数为${ppl}人的预约？`
  proxy.$confirm(msg).then(function() {
    return updateReservation({ id: row.id, status: 2 })
  }).then(resp => {
    proxy.$message({ message: resp.msg || '取消成功', type: 'success' })
    handleQuery()
  }).catch(() => {})
}

const formatDateYMD = (val) => {
  if (!val) return ''
  if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) return val
  const d = new Date(val)
  if (isNaN(d.getTime())) return ''
  const y = d.getFullYear()
  const M = String(d.getMonth() + 1).padStart(2, '0')
  const D = String(d.getDate()).padStart(2, '0')
  return `${y}-${M}-${D}`
}

const statusText = (s) => {
  const n = Number(s)
  if (n === 1) return '已通过'
  if (n === 2) return '已取消'
  if (n === 3) return '已驳回'
  return '待审核'
}

const statusType = (s) => {
  const n = Number(s)
  if (n === 1) return 'success'
  if (n === 2) return 'info'
  if (n === 3) return 'danger'
  return 'warning'
}

/** 表单提交按钮 */
function submitForm() {
  proxy.$refs["reservationRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {  // 添加
        addReservation(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      } else {  // 更新
        updateReservation(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$confirm('是否确认删除预约编号为"' + row.id + '"的数据项？').then(function() {
    return delReservation(row.id);
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/reservation/export', {
//     ...queryParams.value
//   }, `reservation_${new Date().getTime()}.xlsx`)
// }

getList();

onMounted(() => {
  getCurrentSysUser().then(u => {
    const data = u && (u.data || u)
    const uid = data && (data.id || data.userId)
    queryParams.value.userId = uid || null
    handleQuery()
  })
})
</script>

<style scoped>
.app-container {
  width: 80%;
  margin: 24px auto 40px;
}

.mb8 {
  margin-bottom: 8px;
}

:deep(.el-form) {
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  display: flex;
  justify-content: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
}

:deep(.el-row.mb8) {
  justify-content: center;
}
</style>

 
 
