<!-- @format -->

<template>
  <div>
    <div class="page-container">
      <!-- 搜索区域 -->
      <div class="search-container" @keyup.enter="search">
        <div class="search-group">
          <div class="search-group1">
            <div class="search-item">
              <span class="form-label">账号</span>
              <el-input
                v-model="searchForm.dccode"
                placeholder="请输入账号"
                clearable
                style="height: 36px; width: 140px"
              />
            </div>
            <div class="search-item">
              <span class="form-label">姓名</span>
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"
                clearable
                style="height: 36px; width: 140px"
              />
            </div>
            <div class="search-item">
              <span class="form-label">归属</span>
              <el-input
                v-model="searchForm.inviter"
                placeholder="请输入归属账号"
                clearable
                style="height: 36px; width: 140px"
              />
            </div>
          </div>
          <div class="search-group2">
            <div class="search-item">
              <span class="form-label">兑换方式</span>
              <el-select
                v-model="searchForm.type"
                placeholder="请选择兑换方式"
                clearable
                style="height: 36px; width: 160px"
              >
                <el-option
                  v-for="item in exchangeTypeList"
                  :key="item.gold_id"
                  :label="item.gold_type"
                  :value="item.gold_id"
                />
              </el-select>
            </div>
            <div class="search-item">
              <span class="form-label">兑换日期</span>
              <el-date-picker
                v-model="searchDate"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="height: 36px; width: 280px"
              />
            </div>
          </div>
        </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"
        class="table-rounded"
        :loading="tableLoading"
      >
        <el-table-column
          prop="id"
          label="序号"
          align="center"
          header-align="center"
          width="80"
        >
          <template #default="scope">
            {{ (currentPage - 1) * pageSizeDM + 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="inviter"
          label="归属"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="type"
          label="兑换方式"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="token_num"
          label="兑换数量"
          align="center"
          header-align="center"
        >
          <template #default="scope"> {{ scope.row.token_num }}Token </template>
        </el-table-column>
        <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, 20, 50, 100]"
          :page-size="pageSizeDM"
          layout="total, sizes, prev, pager, next, jumper"
          :total="datatotalDM"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  getTokenExchangeRecordApi,
  exportTokenExchangeRecordApi,
  getDropDownListApi,
} from "../../api/eventManagement";
import router from "../../router";
import { useRoute } from "vue-router";
import { usePermissionStore } from "../../store/permission";
const permissionStore = usePermissionStore();
// 兑换方式列表
const exchangeTypeList = ref([]);
// token
const token = localStorage.getItem("token");
//permission
const permission = ref("-1");

// 获取路由实例
const route = useRoute();

// 组件挂载时：获取地区列表 + 初始化表格数据
onMounted(async () => {
  permission.value = permissionStore.permission;
  fetchExchangeTypeList();
  getTableData();
});

const shortcuts = [
  {
    text: "最近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "最近1个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
  {
    text: "最近3个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    },
  },
];

// 搜索表单
const searchForm = reactive({
  dccode: "",
  name: "",
  inviter: "",
  type: "",
});

const searchDate = ref([]);

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

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

// 获取兑换方式列表
const fetchExchangeTypeList = async () => {
  try {
    const data = await getDropDownListApi({
      token: token
    });
    exchangeTypeList.value = data;
  } catch (error) {
    console.error("获取兑换方式列表失败：", error);
    exchangeTypeList.value = [];
  }
};

// 获取表格数据
const getTableData = async () => {
  try {
    tableLoading.value = true;
    const requestParams = {
      token: token,
      dccode: searchForm.dccode,
      name: searchForm.name,
      inviter: searchForm.inviter,
      type: Number(searchForm.type),
      start_at:
        searchDate.value && searchDate.value[0] ? searchDate.value[0] : "",
      end_at:
        searchDate.value && searchDate.value[1] ? searchDate.value[1] : "",
      page: currentPage.value,
      page_size: pageSizeDM.value,
    };
    const data = await getTokenExchangeRecordApi(requestParams);
    tableData.value = data.list;
    datatotalDM.value = data.total;
  } catch (error) {
    console.error("获取表格数据失败：", error);
    tableData.value = [];
    datatotalDM.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

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

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

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

// 重置按钮
const resetBn = () => {
  searchForm.dccode = "";
  searchForm.name = "";
  searchForm.inviter = "";
  searchForm.type = "";
  searchDate.value = [];
  currentPage.value = 1;
  pageSizeDM.value = 15;
  getTableData();
};

// 导出Excel列表按钮
const exportExcel = async () => {
  const requestParams = {
    token: token,
    dccode: searchForm.dccode,
    name: searchForm.name,
    inviter: searchForm.inviter,
    type: Number(searchForm.type),
    start_at:
      searchDate.value && searchDate.value[0] ? searchDate.value[0] : "",
    end_at:
      searchDate.value && searchDate.value[1] ? searchDate.value[1] : "",
  };
  const data = await exportTokenExchangeRecordApi(requestParams);
  if (data != "") {
    ElMessage.success("已导出");
  }
};

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

// 格式化日期
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}`;
};

// 校验指标
const checkmodel = () => {
  if (indicator_id.value.length === 0) {
    ElMessage.error("请至少选择一个指标");
    return false;
  }
  return true;
};
</script>

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

/* 搜索区域 */
.search-container {
  display: flex;
  height: auto;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  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;
}

.search-group {
  display: flex;
  flex-direction: column;
  flex: 1;
}

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

.search-group2 {
  display: flex;
  margin-top: 15px;
  align-items: center;
  gap: 15px;
}

/* 单个搜索项 */
.search-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

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

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

/* 按钮样式 */
.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: 650px;
}

.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;
}

/* 添加/修改样式 */
.form-item {
  margin-bottom: 24px;
  padding-left: 20px;
  padding-right: 20px;
  text-align: left;
}

/* 文本溢出省略样式（深度探索） */
.ellipsis-text {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #ff0000 !important;
  border-color: #ff0000 !important;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner::after) {
  border-color: #fff !important;
}

:deep(.el-checkbox__input:hover .el-checkbox__inner) {
  border-color: #ff0000 !important;
}

:deep(.el-checkbox__input:focus .el-checkbox__inner) {
  box-shadow: 0 0 0 2px rgba(255, 0, 0, 0.2) !important;
}

:deep(.el-checkbox__label) {
  color: #333 !important;
  font-size: 14px !important;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
}
</style>