<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row :gutter="10" class="mb8">
              <!-- 第一行：道具和方式 -->
              <el-form-item label="道具" prop="itermsId">
                <el-select v-model="queryParams.itemId" placeholder="请选择道具" style="flex: 1">
                  <el-option label="所有" value="" />
                  <el-option v-for="item in itemOptions" :key="item.id" :label="item.label" :value="item.id" />
                </el-select>
              </el-form-item>

              <el-form-item label="方式" prop="gameType">
                <el-select aria-required="true" v-model="queryParams.itemType" placeholder="请选择">
                  <el-option label="所有" value="" />
                  <el-option v-for="dict in every_tools_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-form-item label="时间">
                <el-date-picker
                  v-model="data.queryParams.loginTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </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-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:itemsLog:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:itemsLog:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:itemsLog:remove']"
              >删除</el-button
            >
          </el-col> v-hasPermi="['business:itemsLog:export']"-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="itemsLogList" @selection-change="handleSelectionChange">
        <el-table-column label="编号" width="60" align="center">
          <template #default="{ $index }">
            {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="用户名" align="center" prop="userName" />
        <el-table-column label="手机号" align="center" prop="phone" />
        <!--        <el-table-column label="参赛数" align="center" prop="tournamentCount" />
        <el-table-column label="充值次数" align="center" prop="payOrderCount" />
        <el-table-column label="充值总金额" align="center" prop="payOrderAmount" />-->
        <el-table-column label="道具名称" align="center" prop="itemName" />
        <el-table-column label="操作类型" align="center">
          <template #default="scope">
            <span v-if="scope.row.type === 1">新增</span>
            <span v-else-if="scope.row.type === 2">扣除</span>
            <span v-else-if="scope.row.type === 3">其他</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column label="方式" align="center" prop="itermTypeWay" />
        <el-table-column label="当前操作数量" align="center" prop="scoreNum" />
        <el-table-column label="操作前数量" align="center" prop="beforeNum" />
        <el-table-column label="操作后数量" align="center" prop="afterNum" />
        <el-table-column label="描述" align="center" prop="remark" />
        <el-table-column label="时间" align="center" prop="createdAt" width="150"> </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="ItemsLog" lang="ts">
import { queryStatisticsAllDataPageList } from '@/api/system/business/itemsLog';
import { ItemsLogVO, ItemsLogQuery, ItemsLogForm } from '@/api/system/business/itemsLog/types';
import { selectItemsSelList } from '@/api/system/business/items';
import { useRoute } from 'vue-router';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { every_tools_type } = toRefs<any>(proxy?.useDict('every_tools_type'));

const itemsLogList = ref<ItemsLogVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const itemsLogFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ItemsLogForm = {
  id: undefined,
  itemId: undefined,
  scoreNum: undefined,
  afterNum: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  userId: undefined,
  type: undefined,
  remark: undefined
};
const data = reactive<PageData<ItemsLogForm, ItemsLogQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scoreNum: undefined,
    afterNum: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    userId: undefined,
    type: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

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

/** 查询道具使用记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await queryStatisticsAllDataPageList(queryParams.value);
  itemsLogList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  itemsLogFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  const timeRange = data.queryParams.loginTimeRange;
  if (timeRange && timeRange.length === 2) {
    data.queryParams.startTime = timeRange[0];
    data.queryParams.endTime = timeRange[1];
  } else {
    data.queryParams.startTime = null;
    data.queryParams.endTime = null;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ItemsLogVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/itemsLog/export',
    {
      ...queryParams.value
    },
    `道具流水${new Date().getTime()}.xlsx`
  );
};
// 下拉选项数据 selectBlingStructuresInfo
const itemOptions = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadItemOptions = async () => {
  try {
    const res = await selectItemsSelList();
    if (res.code === 200) {
      // 类型断言
      const data = res.data as unknown as { id: number; name: string }[];

      // 过滤掉 id === 2 的项，并映射为 { id, label }
      itemOptions.value = data
        .filter((item) => item.id !== 2) // ✅ 过滤 id 为 2 的
        .map((item) => ({
          id: item.id,
          label: item.name
        }));
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
const route = useRoute();
onMounted(() => {
  getList();
  loadItemOptions();
});
// 监听路由参数变化
watch(
  () => route.query,
  (newQuery, oldQuery) => {
    getList();
  },
  { immediate: true } // 立即执行一次，确保初始参数被处理
);
</script>
