<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
      size="small"
      v-loading="loading"
      border
      :data="versionList"
      row-key="menuId"
      height="100%"
    >
      <el-table-column
        label="版本名称"
        prop="name"
        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="menuRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本名称" prop="name">
              <el-input v-model="form.name" 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="12">
            <el-form-item label="版本包含模块" prop="remark">
              <el-button
                size="small"
                type="primary"
                icon="Plus"
                @click="handleAddModule"
                >点击新增模块</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-loading="loading"
        :data="modulelist"
        row-key="id"
        size="small"
        border
        height="100%"
      >
        <el-table-column label="模块名称" align="center" prop="moduleName">
          <template #default="scope">
            <el-select
              v-if="scope.row.isEdit || scope.row.isAdd"
              v-model="scope.row.moduleId"
              type="text"
              placeholder="选择模块"
              :clearable="true"
              width="100px"
              @clear="handleTaskDetaiClear"
            >
              <el-option
                v-for="item in modules"
                :key="item.id"
                :label="`${item.moduleName}:${item.remark}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ scope.row.moduleName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模块备注" align="center" prop="moduleRemark" />
        <el-table-column label="排序" align="center" prop="serialNumber">
          <template #default="scope">
            <el-input-number
              v-if="scope.row.isEdit || scope.row.isAdd"
              v-model="scope.row.serialNumber"
              controls-position="right"
              :min="0"
            />
            <span v-else>{{ scope.row.serialNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              v-show="!scope.row.isEdit && !scope.row.isAdd"
              link
              type="warning"
              size="small"
              @click="scope.row.isEdit = true"
              v-hasPermi="['priceList:priceList:save']"
              >修改</el-button
            >
            <el-button
              v-show="scope.row.isEdit || scope.row.isAdd"
              link
              type="info"
              size="small"
              @click="handleModuleCancel(scope.row)"
              v-hasPermi="['priceList:priceList:remove']"
              >取消</el-button
            >
            <el-button
              v-show="scope.row.isEdit"
              link
              type="danger"
              size="small"
              @click="handleModulDelete(scope.row)"
              v-hasPermi="['priceList:priceList:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            size="small"
            icon="Finished"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button size="small" icon="close" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Menu">
import {
  addVersion,
  delVersion,
  getVersion,
  listVersion,
  updateVersion,
} from "@/api/system/version";
import { listModule } from "@/api/system/module";
import { ref } from "vue";
import { connect } from "echarts";

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 menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const modulelist = ref([]);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const modules = ref([]);
const versionModules = ref([]);

const moduleMenu = ref({
  moduleId: null,
  moduleName: "",
  moduleRemark: "",
  serialNumber: 0,
  isAdd: false,
  versionId: null,
});

const data = reactive({
  form: {},
  queryParams: {
    orderByColumn: "create_time",
    menuName: undefined,
    visible: undefined,
  },
  rules: {
    menuName: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "菜单顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});

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

/** 查询菜单列表 */
function getList() {
  loading.value = true;
  listVersion(queryParams.value).then((response) => {
    versionList.value = response.rows;
    loading.value = false;
  });
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  // listVersion().then((response) => {
  //   const menu = { menuId: 0, menuName: "主类目", children: [] };
  //   menu.children = proxy.handleTree(response.data, "menuId");
  //   menuOptions.value.push(menu);
  // });
}
function getModules() {
  listModule().then((res) => {
    modules.value = res.rows;
    console.log(modules.value);
  });
}

/** 删除模块 */
function handleModulDelete(row) {
  let index = modulelist.value.indexOf(row);
  if (index !== -1) {
    modulelist.value.splice(index, 1);
  }
}
/** 新增模块 */
function handleAddModule() {
  // 此处必须进行深拷贝，否则添加的明细，将都指向了一个对象
  const _newModule = JSON.parse(JSON.stringify(moduleMenu.value));
  _newModule.isAdd = true;
  modulelist.value.push(_newModule);
}

/** 修改新增属性判断 */
function handleSourceCurrentChange(row) {
  row.isAdd = true;
}

/** 取消按钮操作 */
function handleModuleCancel(row) {
  if (row.isEdit) {
    row.isEdit = false;
  } else if (row.isAdd) {
    modulelist.value.length = modulelist.value.length - 1;
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  modulelist.value = [];
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    menuId: undefined,
    parentId: 0,
    menuName: undefined,
    icon: undefined,
    menuType: "M",
    orderNum: undefined,
    isFrame: "1",
    isCache: "0",
    visible: "0",
    status: "0",
  };
  versionModules.value = [];
  proxy.resetForm("menuRef");
}
/** 展示下拉图标 */
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();
  await getTreeselect();
  getVersion(row.id).then((response) => {
    form.value = response.data;
    modulelist.value = response.data.modules;
    versionModules.value = Array.from(
      new Set(form.value.modules.map((item) => item.moduleId))
    );
    open.value = true;
    title.value = "修改版本";
  });
}
/** 提交按钮 */
function submitForm() {
  for (var i = 0; i < modulelist.value.length; i++) {
    if (modulelist.value[i].isAdd) {
      if (!modulelist.value[i].moduleId) {
        proxy.$modal.msgError("模块不能为空");
        return;
      }
      modulelist.value[i].versionId = form.value.id;
    }
  }
  form.value.modules = modulelist.value;
  proxy.$refs["menuRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateVersion(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVersion(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除?")
    .then(function () {
      return delVersion(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
getModules();

getList();
</script>
