<template>
  <div class="page-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-group">
        <span class="form-label">账号</span>
        <el-input
          v-model="searchForm.dccode"
          placeholder="请输入账号"
          clearable
          style="height: 36px; width: 140px"
        />
        <span class="form-label">地区</span>
        <el-select
          v-model="searchForm.country"
          placeholder="请选择地区"
          clearable
          filterable
          style="height: 36px; width: 160px"
          :loading="isRegionLoading"
        >
          <el-option
            v-for="region in regionList"
            :key="region.ID"
            :label="region.Name"
            :value="region.ID"
          />
        </el-select>
        <span class="form-label">物品类型</span>
        <el-select
          v-model="searchForm.prize_type"
          placeholder="请选择类型"
          style="height: 36px; width: 160px"
          clearable
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="button-group">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="success" @click="exportExcel">导出Excel列表</el-button>
        <el-button color="#626aef" @click="exportList">查看导出列表</el-button>
        <el-button type="primary" @click="resetBn">重置</el-button>
      </div>
    </div>

    <!-- 数据 -->
    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 20px"
      header-cell-class-name="table-header"
      @sort-change="handleSortChange"
      :default-sort="{ prop: null, order: null }"
      class="table-rounded"
      :loading="tableLoading"
    >
      <el-table-column
        prop="id"
        label="序号"
        align="center"
        header-align="center"
        width="80"
      >
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="dccode"
        label="账号"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="name"
        label="姓名"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="market"
        label="地区"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="prize_name"
        label="物品名称"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="stick_type"
        label="福签"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="num"
        label="数量"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="created_at"
        label="时间"
        align="center"
        header-align="center"
      />
    </el-table>

    <!-- 分页组件 -->
    <div class="demo-pagination-block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="datatotal"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { marketListApi } from "../../api/userPermissions";
import { userLuckyDrawListApi, exportUserLuckyDrawListApi } from "../../api/eventManagement";
import router from "../../router";

// token
const token = localStorage.getItem("token");
const typeOptions = ref([
  { label: "金币", value: 2 },
  { label: "金豆", value: 3 },
  { label: "Token", value: 1 },
  { label: "实物", value: 4 },
  { label: "模板", value: 5 },
]);
// 搜索表单
const searchForm = reactive({
  dccode: "",
  country: "",
  prize_type: "",
});

// 排序参数
const sortProp = ref(null);
const sortOrder = ref(null);

// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);
const datatotal = ref(0);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(15);

// 地区下拉框
const regionList = ref([]);
const isRegionLoading = ref(false);

// 来源下拉框
const originList = ref([]);
const isOriginLoading = ref(false);

// 禁用当前日期之前的日期（当天0点之前的时间）
const disabledDate = (time) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}/${month}/${day}`;
};

// 校验HLid
const checkHlids = () => {
  // 非空
  if (!hlidsInput.value.trim()) {
    ElMessage.error("请输入HLid");
    return false;
  }
  // 处理输入：去空、去重，转数组
  const hlidList = hlidsInput.value
    .split("\n")
    .map((item) => item.trim())
    .filter((item) => item)
    .filter((item, index, self) => self.indexOf(item) === index); // 去重
  // 数量校验（最多1000个）
  if (hlidList.length > 1000) {
    ElMessage.error("HLid数量不能超过1000个");
    return false;
  }
  // 格式校验（8位数字）
  const hlidReg = /^\d{8}$/;
  for (const hlid of hlidList) {
    if (!hlidReg.test(hlid)) {
      ElMessage.error(`有HLid格式错误：${hlid}，请重新输入`);
      return false;
    }
  }
  return true;
};

// 重置表单数据
const resetForm = () => {
  hlidsInput.value = "";
  timeType.value = "";
  expireTime.value = "";
  delayValue.value = "";
  delayUnit.value = "";
  remark.value = "";
  operator.value = "";
};

// 获取地区列表
const fetchRegionList = async () => {
  try {
    isRegionLoading.value = true;
    const data = await marketListApi({
      token: token,
      app_form: "en",
    });
    regionList.value = data.list;
  } catch (error) {
    console.error("获取地区列表失败：", error);
    regionList.value = [];
  } finally {
    isRegionLoading.value = false;
  }
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    tableLoading.value = true;
    const requestParams = {
      token: token,
      dccode: searchForm.dccode,
      country: searchForm.country,
      prize_type: searchForm.prize_type,
      page: currentPage.value,
      page_size: pageSize.value,
    };
    const data = await userLuckyDrawListApi(requestParams);
    tableData.value = data.list;
    datatotal.value = data.total;
  } catch (error) {
    console.error("获取表格数据失败：", error);
    tableData.value = [];
    datatotal.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 组件挂载时：获取地区列表 + 初始化表格数据
onMounted(() => {
  fetchRegionList();
  fetchTableData();
});

// 搜索按钮
const search = () => {
  currentPage.value = 1;
  fetchTableData();
};

// 导出Excel列表按钮
const exportExcel = async () => {
  const requestParams = {
    token: token,
    dccode: searchForm.dccode,
    country: searchForm.country,
    prize_type: searchForm.prize_type,
  };
  const data = await exportUserLuckyDrawListApi(requestParams);
  console.log(data);
  if (data != "") {
    ElMessage.success("已导出");
  }
};

// 查看导出列表按钮
const exportList = () => {
  router.push({
    path: '/userPermissions/export'
  });
};

// 重置按钮
const resetBn = () => {
  searchForm.dccode = "";
  searchForm.country = "";
  searchForm.prize_type = "";
  currentPage.value = 1;
  pageSize.value = 15;
  fetchTableData();
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
  console.log(`每页 ${val} 条`);
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
  console.log(`当前页: ${val}`);
};
</script>

<style scoped>
/* 父容器 */
.page-container {
  position: relative;
  min-height: 600px;
}

/* 搜索区域 */
.search-container {
  display: flex;
  height: auto;
  justify-content: center;
  align-items: flex-start;
  gap: 12px;
  align-self: stretch;
  border-radius: 8px;
  background: #fefaf9;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
  padding: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap; 
}

.search-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 搜索标签文字 */
.form-label {
  font-weight: 800 !important;
  font-size: 15px;
  color: #333;
  font-family: "SimHei", "Heiti SC", "Microsoft YaHei", sans-serif !important;
  font-weight: 500;
}

/* 按钮组 */
.button-group {
  display: flex;
  align-items: center;
  gap: 0px !important;
  margin-left: auto;
}

/* 按钮样式 */
.button-group .el-button {
  padding: 6px 10px !important;
  font-size: 14px !important;
  height: 36px !important;
}

/* 表格样式 */
.table-rounded {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: 1px solid #e4e7ed !important;
  height: 750px;
}

.table-header {
  text-align: center !important;
  font-weight: 800 !important;
  font-size: 15px !important;
  color: #333 !important;
  background-color: #f8f9fa !important;
}

.el-table__cell {
  border-right: none !important;
  border-bottom: 1px solid #e4e7ed !important;
}

.el-table__header th.el-table__cell {
  border-right: none !important;
  border-bottom: 1px solid #e4e7ed !important;
}

.el-table__row:hover .el-table__cell {
  background-color: #fafafa !important;
}

/* 分页组件样式 */
.demo-pagination-block {
  display: flex;
  width: 100%;
  height: 44px;
  padding: 0 16px;
  align-items: center;
  gap: 16px;
  position: absolute;
  margin-top: 10px;
  border-radius: 0 0 3px 3px;
  border-top: 1px solid #eaeaea;
  background: #fefbfb;
  box-sizing: border-box;
}
</style>