<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-form-item label="分组名" prop="rgName">
              <el-input v-model="queryParams.rgName" placeholder="请输入分组名" clearable @keyup.enter="handleQuery" />
            </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>
        </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:rankGroup:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:rankGroup:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="rankGroupList"
        row-key="rgId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
      <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="分组id" align="center" prop="rgId" v-if="false" />
        <el-table-column label="赛事ID" align="center" prop="eventId" v-if="false" />
        <el-table-column label="分组名" align="center" prop="rgName" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column label="状态" align="center" prop="status" v-if="false" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:rankGroup:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="新增下级" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:rankGroup:add']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:rankGroup:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改排名分组对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="rankGroupFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分组" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="rankGroupOptions"
                :props="{ value: 'rgId', label: 'rgName', children: 'children' }"
                value-key="rgId"
                placeholder="请选择上级分组"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分组名" prop="rgName">
              <el-input v-model="form.rgName" placeholder="请输入分组名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示顺序" prop="sortNum">
              <el-input-number v-model="form.sortNum" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RankGroup" lang="ts">
import { treeListRankGroup, getRankGroup, delRankGroup, addRankGroup, updateRankGroup } from '@/api/system/rankGroup';
import { RankGroupVO, RankGroupQuery, RankGroupForm } from '@/api/system/rankGroup/types';
import { useGameEventStore } from '@/store/modules/gameEvent';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const rankGroupList = ref<RankGroupVO[]>([]);
const rankGroupOptions = ref<RankGroupVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const isExpandAll = ref(false);
const refreshTable = ref(true);

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

let gameEventStore = useGameEventStore();

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

const getInitFormData = () => ({
  rgId: undefined,
  parentId: 0,
  eventId: gameEventStore.defaultEventInfo?.eventId,
  rgName: undefined,
  sortNum: 0,
  status: '0',
  remark: undefined
});

const data = reactive<PageData<RankGroupForm, RankGroupQuery>>({
  form: getInitFormData(),
  queryParams: {
    eventId: gameEventStore.defaultEventInfo?.eventId,
    rgName: undefined,
    status: '0',
    params: {}
  },
  rules: {
    parentId: [{ required: true, message: "上级分组不能为空", trigger: "blur" }],
    rgName: [{ required: true, message: "分组名不能为空", trigger: "blur" }]
  }
});

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

/** 查询排名分组列表 */
const getList = async () => {
  loading.value = true;
  const res = await treeListRankGroup(queryParams.value);
  rankGroupList.value = res.data;
  loading.value = false;
};

/** 查询菜单下拉树结构 */
const getTreeSelect = async () => {
  rankGroupOptions.value = [];
  const res = await treeListRankGroup({ eventId: queryParams.value.eventId });
  const group: any = { rgId: 0, rgName: '顶级分组', children: res.data };
  rankGroupOptions.value.push(group);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

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

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

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

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

/** 新增按钮操作 */
const handleAdd = (row?: RankGroupVO) => {
  reset();
  getTreeSelect();
  if (row != null && row.rgId) {
    form.value.parentId = row.rgId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加排名分组";
};

/** 修改按钮操作 */
const handleUpdate = async (row: RankGroupVO) => {
  reset();
  getTreeSelect();
  const res = await getRankGroup(row.rgId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改排名分组";
};

/** 提交按钮 */
const submitForm = () => {
  rankGroupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.rgId) {
        await updateRankGroup(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addRankGroup(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: RankGroupVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.rgName + '"的数据项？');
  loading.value = true;
  await delRankGroup(row.rgId).finally(() => loading.value = false);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/rankGroup/export', {
    ...queryParams.value
  }, `${gameEventStore.defaultEventInfo?.eventCode || ''}_排名分组组别.xlsx`)
};

onMounted(() => {
  getList();
});

</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
