<template>
  <Page>
    <!-- 查询和全局功能 -->
    <Row>
      <Col :span="22">
      <!-- 查询 -->
      <Space v-if="data.isShowQuery">
        <Input v-model:value="data.query.name" allowClear :placeholder="$t('system.menu.name')" />
        <Input v-model:value="data.query.menu" allowClear :placeholder="$t('system.menu.menu')" />
        <Input v-model:value="data.query.permission" allowClear :placeholder="$t('system.menu.permission')" />
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.status" allowClear
          :placeholder="$t('system.menu.status')" style="width: 100px">
          <SelectOption v-for="(item, index) in data.statusOptions" :key="index" :value="item.value" :label="item.label"
            :text="item.label">{{ item.label }}</SelectOption>
        </Select>
        <!-- 查询按钮 -->
        <Button @click="handleQuery" :loading="data.loading" :disabled="data.loading"
          style="background-color: #0084CA;color: white">
          {{ $t('common.search') }}
        </Button>
        <Button @click="resetQuery" :loading="data.loading" :disabled="data.loading" danger>
          {{ $t('common.reset') }}
        </Button>
      </Space>

      <!-- 全局功能 -->
      <div style="padding: 15px 0">
        <Button @click="handleOpenAdd" style="background-color: #0084CA;color: white">
          {{ $t('common.add') }}
        </Button>
      </div>
      </Col>
    </Row>

    <!-- 路径 -->
    <div v-if="data.parents && data.parents.length > 0">
      <Button type="link" size="small" @click="handleResetParent()">top</Button>
      <span v-for="(item, index) in data.parents" :key="index">
        <span>/</span>
        <Button type="link" size="small" @click="handleResetParent(index)">{{ item.name }}</Button>
      </span>
    </div>
    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" :scroll="{ x: 1500 }" @change="handleQuery" size="small">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <Button type="link" size="small" @click="handleOpenEdit(record)">{{ $t('common.edit') }}</Button>
          <Button type="link" size="small" @click="handleDeleteConfirm(record)">{{ $t('common.delete') }}</Button>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <span>{{ data.statusMap[record.status] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'header'">
          <div @click="handleQueryChildren(record)" class="pointer">
            <span class="icon-[teenyicons--right-solid]"></span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'name'">
          <div @click="handleQueryChildren(record)" class="pointer"><span>{{ record.name }}</span></div>
        </template>
      </template>
    </Table>

    <!-- 添加 -->
    <Add ref="addRef" @close="reload"></Add>
    <!-- 编辑 -->
    <Edit ref="editRef" @close="reload"></Edit>
    <!-- 删除 -->
    <DeleteConfirm ref="deleteRef"></DeleteConfirm>
  </Page>
</template>

<script setup lang="ts">
import DeleteConfirm from "#/components/myui/deleteConfirm/index.vue";
import Add from "./components/add.vue";
import Edit from "./components/edit.vue";
import { reactive, onMounted, ref } from "vue";
import { $t } from '@vben/locales';
import { Page } from '@vben/common-ui';
import { Button, Input, Space, Table, Row, Col, message,Select,SelectOption } from 'ant-design-vue';
import {MdiKeyboardEsc} from '@vben/icons';
import { menu } from '#/api';
import { d } from './index.ts';

const data = reactive(d);
const addRef = ref();
const deleteRef = ref();
const editRef = ref();

onMounted(() => {
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
})

function handleOpenAdd() {
  addRef.value._open({ parentId: getCurrentParent()?.uid });
}

function handleOpenEdit(item) {
  editRef.value._open(item);
}

function handleDeleteConfirm(item) {
  deleteRef.value._open($t('common.deleteConfirm') + '【' + item.name + '】?').then(() => {
    menu.removeByUid(item).then((res) => {
      if (res.error) {
        return;
      }
      message.success($t('common.deleteSuccess'));
      handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
    })
  })
}

// 选择框过滤方法
const selectFilterOption = (input: string, option: any) => {
  return option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

/**
 * 查询子数据
 * @param item
 */
function handleQueryChildren(item) {
  data.parents.push(item);
  resetQuery();
}

/**
 * 重置上级
 * @param index
 */
function handleResetParent(index) {
  index == null ? data.parents = [] : data.parents = data.parents.slice(0, index + 1);
  resetQuery();
}

function getCurrentParent() {
  return data.parents && data.parents.length > 0 ? data.parents[data.parents.length - 1] : null;
}

/**
 * 包装查询参数
 * @param context
 * @param page
 * @param filter
 * @param sorter
 */
function wrapQueryParam(page, filter, sorter) {
  let { current, pageSize } = { ...data.pagination, ...(page || {}) };
  let param = {
    pageNum: current,
    pageSize: pageSize,
  }
  //父级
  param.parentId = getCurrentParent()?.uid;
  //查询
  for (const key in data.query) {
    if (data.query[key] == null) {
      continue;
    }
    param[key] = data.query[key];
  }
  //过滤
  if (filter) {
    for (const key in filter) {
      const value = Array.isArray(filter[key]) && filter[key].length > 0 ? filter[key][0] : filter[key];
      param[key] = value || param[key];
    }
  }
  //排序
  if (sorter && sorter.field && sorter.order) {
    param.sorts = [{ name: sorter.field, desc: sorter.order == 'descend' }]
  }
  return param;
}

/**
 * 重置查询
 */
function resetQuery() {
  data.query = {}
  data.pagination.current = 1;
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}

/**
 * 重置内容
 */
function reload(success) {
  success && handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}

/**
 * 查询方法
 * @param context
 * @param page
 * @param filter
 * @param sorter
 */
function handleQuery(page, filter, sorter) {
  console.log(page, filter, sorter);
  let param = wrapQueryParam(page, filter, sorter);
  data.loading = true;
  menu.queryPageNextChildren(param).then(res => {
    if (res.data) {
      data.datas = res.data.list || [];
      data.pagination.current = res.data.pageNum || 1;
      data.pagination.pageSize = res.data.pageSize || 10;
      data.pagination.total = res.data.total;
    }
  }).finally(() => {
    data.loading = false;
  });
}
</script>

<style scoped>
.pointer {
  cursor: pointer;
}
</style>