<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-form-item label="用户名" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable @keyup.enter="handleQuery" style="width: 100%" />
              </el-form-item>
              <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-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>

              &lt;!&ndash; 按钮行 &ndash;&gt;
              <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>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:itemsLog:export']">导出</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="itemName" />
        <el-table-column label="道具数量" align="center" prop="scoreNum" />
        <el-table-column label="方式" align="center" prop="itermTypeWay" />
        <el-table-column label="事项" align="center" prop="remark" />
        <el-table-column label="时间" align="center" prop="createdAt" width="150"> </el-table-column>
        <el-table-column label="关联用户ID" align="center" prop="userId" />
        <el-table-column label="关联用户手机号" align="center" prop="phone" />
        <el-table-column label="关联用户名" align="center" prop="userName" />
        <el-table-column label="状态" align="center" prop="statusText" />
      </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 { queryStatisticsPageList } 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 queryStatisticsPageList(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;
  }
  queryParams.value.itemId = 1001;
  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(
    'system/itemsLog/export',
    {
      ...queryParams.value
    },
    `itemsLog_${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(() => {
  const flagType = route.query.timeFilter;
  const startTime = route.query.startTime;
  const endTime = route.query.endTime;
  // 根据参数设置查询条件
  if (startTime) {
    queryParams.value.startTime = startTime as string; // 直接赋值字符串
  } else {
    /* queryParams.value.startTime = `${yyyy}-${mm}-${dd}`;*/
  }
  // 处理结束时间（如果需要）
  if (endTime) {
    queryParams.value.endTime = endTime as string;
  }
  if (flagType) {
    queryParams.value.flagType = flagType as string;
  }
  queryParams.value.itemId = 1001;
  getList();
  loadItemOptions();
});
// 监听路由参数变化
watch(
  () => route.query,
  (newQuery, oldQuery) => {
    const flagType = route.query.timeFilter;
    const startTime = route.query.startTime;
    const endTime = route.query.endTime;
    // 根据参数设置查询条件
    if (startTime) {
      queryParams.value.startTime = startTime as string; // 直接赋值字符串
    } else {
    }
    // 处理结束时间（如果需要）
    if (endTime) {
      queryParams.value.endTime = endTime as string;
    }
    if (flagType) {
      queryParams.value.flagType = flagType as string;
    }
    queryParams.value.itemId = 1001;
    getList();
  },
  { immediate: true } // 立即执行一次，确保初始参数被处理
);
</script>
