<template>
  <div class="page-container list-container">
    <div :gutter="10" class="list-btns-container">
      <el-button
        type="primary"
        size="small"
        icon="Plus"
        @click="handleAdd"
        v-hasPermi="['system:menu:add']"
        >新增</el-button
      >
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
    </div>
    <el-form
      class="list-search-container"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="模块名称：" prop="name">
        <el-input
          size="small"
          v-model="queryParams.name"
          placeholder="请输入模块名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模块说明：" prop="remark" @change="handleQuery">
        <el-input
          size="small"
          v-model="queryParams.remark"
          placeholder="请输入模块说明"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="Search"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button size="small" icon="Refresh" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      border
      size="small"
      v-loading="loading"
      :data="versionList"
      row-key="menuId"
      height="100%"
    >
      <el-table-column
        label="模块名称"
        prop="moduleName"
        align="center"
      ></el-table-column>
      <el-table-column
        label="模块说明"
        prop="remark"
        align="center"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="210"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="warning"
            size="small"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:menu:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改模块对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="680px"
      append-to-body
      draggable
    >
      <el-form ref="moduleRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模块名称" prop="name">
              <el-input
                v-model="form.moduleName"
                placeholder="请输入模块名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块说明" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入模块说明" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="管理">
              <el-checkbox
                v-model="menuExpand"
                @change="handleCheckedTreeExpand($event, 'menu')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox
                v-model="menuNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'menu')"
                >全选/全不选</el-checkbox
              >
              <el-checkbox
                v-model="menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              >
              <el-tree
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                ref="menuRef"
                node-key="id"
                :check-strictly="!menuCheckStrictly"
                empty-text="加载中，请稍候"
                :props="{
                  label: 'label',
                  node: 'menuNode',
                  children: 'children',
                }"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            icon="Finished"
            size="small"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button icon="Close" size="small" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup name="Menu">
import {
  addModule,
  delModule,
  getModule,
  listModule,
  updateModule,
} from "@/api/system/module";
import { treeselect as menuTreeselect } from "@/api/system/menu";
import { nextTick, ref } from "vue";

const { proxy } = getCurrentInstance();
// const { sys_show_hide, sys_normal_disable, app_key } = proxy.useDict('sys_show_hide', 'sys_normal_disable', 'app_key')

const versionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuOptions = ref([]);
const modules = ref([]);
const versionModules = ref([]);
const menuRef = ref(null);
const menuCheckStrictly = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    orderByColumn: "create_time",
    menuName: undefined,
    visible: undefined,
  },
  rules: {
    menuName: [
      { required: true, message: "模块名称不能为空", trigger: "blur" },
    ],
  },
});

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

/** 查询模块列表 */
function getList() {
  loading.value = true;
  listModule(queryParams.value).then((response) => {
    versionList.value = response.rows;
    loading.value = false;
  });
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  menuTreeselect().then((response) => {
    menuOptions.value = response.data;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    menuId: undefined,
    isFrame: "1",
    isCache: "0",
    visible: "0",
    status: "0",
    details: [],
  };
  proxy.resetForm("moduleRef");
}
/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
  showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name) {
  form.value.icon = name;
  showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
  var elem =
    event.relatedTarget ||
    event.srcElement ||
    event.target ||
    event.currentTarget;
  var className = elem.className;
  if (className !== "el-input__inner") {
    showChooseIcon.value = false;
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.menuId) {
    form.value.parentId = row.menuId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加模块";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  Promise.all([getModule(row.id), menuTreeselect()]).then((response) => {
    form.value = response[0].data;
    menuOptions.value = response[1].data;
    open.value = true;
    title.value = "修改模块";
    nextTick((_) => {
      form.value.details.forEach((l) => {
        menuRef.value.setChecked(l.menuId, true, false);
      });
    });
  });
}
/** 提交按钮 */
function submitForm() {
  const checkedKeys = getMenuAllCheckedKeys();
  // 删除已有但未选中的
  form.value.details = form.value.details.filter(
    (l) => checkedKeys.findIndex((v) => v.id === l.menuId) > -1
  );
  console.log(checkedKeys, form.value.details);
  form.value.details = form.value.details.concat(
    checkedKeys
      // 获取明细中没有但选中的目录
      .filter(
        (l) => form.value.details.findIndex((v) => v.menuId === l.id) === -1
      )
      // 设置为对应模块明细的数据
      .map((l) => ({
        menuId: l.id,
        moduleId: form.value.id,
        type: l.menuNode.menuType,
      }))
  );
  proxy.$refs["moduleRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateModule(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addModule(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除?")
    .then(function () {
      return delModule(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then((response) => {
    menuOptions.value = response.data;
  });
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == "menu") {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  }
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == "menu") {
    form.value.menuCheckStrictly = value ? true : false;
  }
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedNodes();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedNodes();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

getList();
</script>
  