<script setup lang="ts">
import { ref, onMounted } from "vue";

import { httpList, httpStatus, httpDelete } from "/@/api/system/menuOperator";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { responseHandle } from "/@/utils/responseHandle";
import { useUserStoreHook } from "/@/store/modules/user";
import { TableProBar } from "/@/components/ReTable";
import { useNav } from "/@/layout/hooks/nav";
import { useColumns } from "../columns";

const { columns } = useColumns();
const loading = ref(true);
const dataList = ref([]);
const powers = ref([]);
const { logout } = useNav();
const tableRef = ref();
const loadMap = new Map();

const emit = defineEmits(["edit", "create", "view"]);

//更新状态
const handleStatus = async row => {
  const { id, status } = row;
  const { code, message } = await httpStatus({
    id,
    status: status + "" === "1" ? "0" : "1"
  });
  responseHandle({
    code,
    message,
    logout,
    handler: () => reloadTree(row.pid)
  });
};
//删除
const handleDelete = async row => {
  const { id } = row;
  const { code, message } = await httpDelete({ id });
  responseHandle({
    code,
    message,
    logout,
    handler: () => (Number(row.pid) === 0 ? onSearch() : reloadTree(row.pid))
  });
};
//勾选
function handleSelectionChange(val) {
  console.log("handleSelectionChange", val);
}

async function requestMenu(params: Record<string, string>) {
  loading.value = true;
  return new Promise(resolve => {
    httpList({
      ...params,
      size:100
    })
      .then(result => {
        loading.value = false;
        const { code, data } = result;
        if (code === 1 && data.list.length !== 0) {
          resolve(data.list);
        } else {
          resolve([]);
        }
      })
      .catch(() => {
        loading.value = false;
        resolve([]);
      });
  });
}

async function onSearch() {
  const list = await requestMenu({});
  dataList.value = list.map(item => ({ ...item, hasChildren: true }));
}

function reloadTree(p: string) {
  const pid = p ? parseInt(p) : 0;
  const { row, treeNode, resolve } = loadMap.get(pid) || {};

  if (row) {
    handleLoad(row, treeNode, resolve);
  } else {
    onSearch();
  }
}

async function handleLoad(row, treeNode, resolve) {
  const { id: pid } = row;
  loadMap.set(pid, { row, treeNode, resolve });
  const list = await requestMenu({ pid });
  resolve(list);
}
//编辑
function editItem(item, id: string, type: "create" | "edit" | "view") {
  emit(type, item, id, type);
}
onMounted(() => {
  powers.value = useUserStoreHook().getMenuActions("menuOperator");
});
defineExpose({
  onSearch,
  reloadTree
});
</script>

<template>
  <div class="main flex" style="width: 100%">
    <TableProBar
      title="菜单列表"
      :loading="loading"
      :tableRef="tableRef?.getTableRef()"
      :dataList="dataList"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          v-if="powers.some(i => i == '2')"
          type="primary"
          size="small"
          :icon="useRenderIcon('add')"
          @click="editItem(null, '', 'create')"
        >
          新增
        </el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <PureTable
          ref="tableRef"
          border
          align="left"
          row-key="id"
          table-layout="auto"
          :size="size"
          :lazy="true"
          :data="dataList"
          :columns="columns"
          :checkList="checkList"
          :tree-props="{ hasChildren: 'hasChildren', children: 'child' }"
          :header-cell-style="{ background: '#fafafa', color: '#606266' }"
          @selection-change="handleSelectionChange"
          :load="handleLoad"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              v-if="powers.some(i => i == '5')"
              type="primary"
              :size="size"
              @click="editItem(row, row.id, 'view')"
              :icon="useRenderIcon('eye-view')"
            />
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              v-if="powers.some(i => i == '4')"
              @click="editItem(row, row.id, 'edit')"
              :icon="useRenderIcon('edits')"
            />
            <el-popconfirm
              :title="String(row.status) === '1' ? '改为禁用？' : '改为启用？'"
              v-if="
                (powers.some(i => i == '7') && row.status + '' === '1') ||
                (powers.some(i => i == '6') && row.status + '' === '0')
              "
              @confirm="handleStatus(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="
                    useRenderIcon(
                      String(row.status) === '1'
                        ? 'close-circle-line'
                        : 'checkbox-circle-line'
                    )
                  "
                /> </template
            ></el-popconfirm>
            <el-popconfirm
              title="是否确认删除?"
              v-if="powers.some(i => i == '8')"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon('delete')"
                />
              </template>
            </el-popconfirm>
            <!--            v-if="row.menu_type + '' === '1' && powers.some(i => i == '002')"-->
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="editItem(null, row.id, 'create')"
              :icon="useRenderIcon('add')"
            />
          </template>
        </PureTable>
      </template>
    </TableProBar>
  </div>
</template>
