<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入预约者用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入预约者昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <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="预约id" align="center" prop="id" /> -->
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <!-- <el-table-column label="预约发起者id" align="center" prop="userId" /> -->
      <!-- <el-table-column label="预约时段id" align="center" prop="timeSlotId" /> -->
      <el-table-column label="预约总人数" align="center" prop="totalVisitors" />
      <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="qrCode" /> -->
       
      <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="审核者id" align="center" prop="updater" />
      <el-table-column label="审核备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="Number(scope.row.status) === 0" link type="success" icon="Check" @click="openAudit(scope.row)">审核</el-button>
          <el-button v-else link type="primary" icon="View" @click="openDetail(scope.row)">详情</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <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>

    <!-- 添加或修改预约对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reservationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约发起者id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入预约发起者id" />
        </el-form-item>
        <el-form-item label="预约时段id" prop="timeSlotId">
          <el-input v-model="form.timeSlotId" placeholder="请输入预约时段id" />
        </el-form-item>
        <el-form-item label="预约总人数" prop="totalVisitors">
          <el-input v-model="form.totalVisitors" placeholder="请输入预约总人数" />
        </el-form-item>
        <el-form-item label="预约时间" prop="reserveTime">
          <el-input v-model="form.reserveTime" placeholder="请输入预约时间(HH:mm:ss)" />
        </el-form-item>
        <el-form-item label="预约凭证二维码" prop="qrCode">
          <el-input v-model="form.qrCode" placeholder="请输入预约凭证二维码" />
        </el-form-item>
        <el-form-item label="审核者id" prop="updater">
          <el-input v-model="form.updater" placeholder="请输入审核者id" />
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="审核预约" v-model="auditOpen" width="700px" append-to-body>
      <div class="audit-info">
        <div class="audit-section-title">预约信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ auditData.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ auditData.nickname }}</el-descriptions-item>
          <el-descriptions-item label="预约日期">{{ formatDateYMD(auditData.reservationTimeSlot && auditData.reservationTimeSlot.date) }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ auditData.reserveTime }}</el-descriptions-item>
          <el-descriptions-item label="预约总人数">{{ auditData.totalVisitors }}</el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="left"><span class="audit-section-title">游客信息</span></el-divider>
        <div class="audit-visitors" v-if="auditData.reservationVisitors && auditData.reservationVisitors.length">
          <el-table :data="auditData.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>
        </div>
        <div class="audit-visitors-empty" v-else>
          <el-empty description="暂无游客信息" image-size="80" />
        </div>
      </div>
      <el-form :model="auditForm" :rules="auditRules" ref="auditRef" label-width="90px" style="margin-top: 12px;">
        <el-form-item label="审核结果" prop="status">
          <el-select v-model="auditForm.status" placeholder="请选择">
            <el-option label="通过" :value="1" />
            <el-option label="拒绝" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="Number(auditForm.status) === 3" label="拒绝原因" prop="remark">
          <el-input v-model="auditForm.remark" type="textarea" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">提 交</el-button>
          <el-button @click="auditOpen=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <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="用户名">{{ detailData.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ detailData.nickname }}</el-descriptions-item>
          <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-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 } from 'vue';
import { listReservation, getReservation, delReservation, addReservation, updateReservation, auditReservation } from "@/api/reservation";

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 auditOpen = ref(false)
const auditData = ref({})
const auditForm = ref({ id: null, status: null, remark: '' })
const auditRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  remark: [{ validator: (rule, value, callback) => {
    const s = auditForm.value.status
    if (Number(s) === 3 && (!value || !value.trim())) callback(new Error('拒绝原因不能为空'))
    else callback()
  }, trigger: 'blur' }]
}

const data = reactive({
  form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      username: null,
      nickname: null,
      dateRange: null,
      startDate: null,
      endDate: null,
      userId: null,
      timeSlotId: null,
      totalVisitors: null,
      reserveTime: null,
      qrCode: null,
      status: null,
      updater: null,
    },
    rules: {
      userId: [
        { required: true, message: "预约发起者id不能为空", trigger: "blur" }
      ],
      timeSlotId: [
        { required: true, message: "预约时段id不能为空", trigger: "blur" }
      ],
      totalVisitors: [
        { required: true, message: "预约总人数不能为空", trigger: "blur" }
      ],
      reserveTime: [
        { required: true, message: "预约时间不能为空", trigger: "blur" }
      ],
    }
  });

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,
    reserveTime: 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 openAudit(row) {
  getReservation(row.id).then(response => {
    auditData.value = response.data
    auditForm.value = { id: row.id, status: 1, remark: '' }
    auditOpen.value = true
  })
}

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}`
}

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

function submitAudit() {
  const auditRef = proxy.$refs["auditRef"]
  if (auditRef) {
    auditRef.validate(valid => {
      if (!valid) return
      const payload = { id: auditForm.value.id, status: auditForm.value.status, remark: auditForm.value.remark }
      auditReservation(payload).then(resp => {
        proxy.$message({ message: resp.msg, type: 'success' })
        auditOpen.value = false
        getList()
      })
    })
  }
}

/** 表单提交按钮 */
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();
</script>
<script>
export default {
  methods: {
    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}`
    },
    statusText(s) {
      const n = Number(s)
      if (n === 1) return '已通过'
      if (n === 2) return '已取消'
      if (n === 3) return '已驳回'
      return '待审核'
    },
    statusType(s) {
      const n = Number(s)
      if (n === 1) return 'success'
      if (n === 2) return 'info'
      if (n === 3) return 'danger'
      return 'warning'
    }
  }
}
</script>
