<template>
  <div class="app-container my_menu">
    <el-form :inline="true">
      <el-form-item :label="$t('system:menu:search:menuName')">
        <el-input
          v-model="queryParams.menuName"
          placeholder=""
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('system:menu:search:visible')">
        <el-select
          v-model="queryParams.visible"
          placeholder=""
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
          >{{ $t("system:menu:button:search") }}</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          >{{ $t("system:menu:button:add") }}</el-button
        >
      </el-form-item>
    </el-form>
    <div>
      <el-button
        type="info"
        plain
        icon="el-icon-sort"
        @click="toggleExpandAll"
        >{{ $t("system:menu:button:foldAndExpand") }}</el-button
      >
    </div>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      :default-expand-all="isExpandAll"
      row-key="MenuId"
      :tree-props="{ children: 'Children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="MenuName"
        :label="$t('system:menu:table:menuName')"
        :show-overflow-tooltip="true"
        min-width="130px"
      />
      <el-table-column
        prop="icon"
        :label="$t('system:menu:table:icon')"
        align="center"
        min-width="100px"
      >
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.MenuIcon" />
        </template>
      </el-table-column>
      <el-table-column
        prop="ShowOrder"
        :label="$t('system:menu:table:showOrder')"
        min-width="60px"
      />
      <el-table-column
        prop="Path"
        :label="$t('system:menu:table:path')"
        min-width="120px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="ApiPath"
        :label="$t('system:menu:table:apiPath')"
        min-width="180px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="Component"
        :label="$t('system:menu:table:component')"
        min-width="180px"
        :show-overflow-tooltip="true"
      />
      <!--      <el-table-column prop="Redirect" label="重定向" min-width="180px" :show-overflow-tooltip="true" />-->
      <el-table-column
        prop="PermissionStr"
        :label="$t('system:menu:table:permissionStr')"
        min-width="130px"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="PermissionStr"
        :label="$t('system:menu:table:type')"
        min-width="80px"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{
            scope.row.MenuType === "M"
              ? $t("system:menu:template:message:directttory")
              : scope.row.MenuType === "C"
              ? $t("system:menu:template:message:menu")
              : $t("system:menu:template:message:permission")
          }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('system:menu:table:showOrNone')"
        align="center"
        prop="CreateTime"
        min-width="80"
      >
        <template slot-scope="scope">
          <el-tag v-if="!scope.row.IsDisplay" size="medium">{{
            $t("system:menu:tag:show")
          }}</el-tag>
          <el-tag v-else size="warning">{{
            $t("system:menu:tag:none")
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('system:menu:table:enable')"
        align="center"
        prop="CreateTime"
        min-width="80"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsEnable" size="success">{{
            $t("system:menu:tag:enable")
          }}</el-tag>
          <el-tag v-else size="danger">{{
            $t("system:menu:tag:disable")
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('system:menu:table:action')"
        align="center"
        min-width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:menu:edit']"
            type="text"
            @click="handleUpdate(scope.row)"
            >{{ $t("system:menu:button:edit") }}</el-button
          >
          <el-button
            v-hasPermi="['system:menu:add']"
            type="text"
            @click="handleAdd(scope.row)"
            >{{ $t("system:menu:button:add") }}</el-button
          >
          <el-button
            v-hasPermi="['system:menu:delete']"
            type="text"
            @click="handleDelete(scope.row)"
            >{{ $t("system:menu:button:remove") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="open"
      width="680px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('system:menu:form:lastMenu')">
              <treeselect
                v-model="form.ParentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('system:menu:form:menuType')"
              prop="menuType"
            >
              <el-radio-group v-model="form.MenuType">
                <el-radio label="M">{{
                  $t("system:menu:template:message:directttory")
                }}</el-radio>
                <el-radio label="C">{{
                  $t("system:menu:template:message:menu")
                }}</el-radio>
                <el-radio label="F">{{
                  $t("system:menu:template:message:permission")
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="form.MenuType != 'F'"
              :label="$t('system:menu:form:menuIcon')"
            >
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input
                  slot="reference"
                  v-model="form.MenuIcon"
                  placeholder="点击选择图标"
                  readonly
                >
                  <svg-icon
                    v-if="form.MenuIcon"
                    slot="prefix"
                    :icon-class="form.MenuIcon"
                    class="el-input__icon"
                    style="height: 28px; width: 16px; margin-left: 6px"
                  />
                  <i
                    v-else
                    slot="prefix"
                    class="el-icon-search el-input__icon"
                  />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('system:menu:form:menuName')"
              prop="MenuName"
            >
              <el-input v-model="form.MenuName" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('system:menu:form:showOrder')"
              prop="ShowOrder"
            >
              <el-input-number
                v-model="form.ShowOrder"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <!--选择是外链则路由地址需要以`http(s)://`开头-->
                <el-tooltip
                  :content="$t('system:menu:form:isExternalLinkMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:isExternalLink") }}
              </span>
              <el-radio-group v-model="form.IsExternalLink">
                <el-radio
                  v-for="item of $d.YesOrNo"
                  :label="item.value"
                  :key="item.id"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'" prop="path">
              <span slot="label">
                <!--访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头-->
                <el-tooltip
                  :content="$t('system:menu:form:pathMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:path") }}
              </span>
              <el-input v-model="form.Path" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType == 'C'" :span="12">
            <el-form-item prop="component">
              <span slot="label">
                <!--访问的组件路径，如：`system/user/index`，默认在`views`目录下-->
                <el-tooltip
                  :content="$t('system:menu:form:componentMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:component") }}
              </span>
              <el-input v-model="form.Component" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType != 'F'" :span="12">
            <el-form-item prop="Redirect Path">
              <span slot="label">
                <!--重定向路由，如：`/system/user/index`-->
                <el-tooltip
                  :content="$t('system:menu:form:redirectPathMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:redirectPath") }}
              </span>
              <el-input v-model="form.Redirect" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'M'">
              <el-input
                v-model="form.PermissionStr"
                placeholder=""
                maxlength="100"
              />
              <span slot="label">
                <!--控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)-->
                <el-tooltip
                  :content="$t('system:menu:form:permissionStrMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:permissionStr") }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'M'">
              <el-input v-model="form.ApiPath" placeholder="" />
              <span slot="label">
                <!--接口名-->
                <el-tooltip
                  :content="$t('system:menu:form:apiPathMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:apiPath") }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType == 'C'">
              <span slot="label">
                <!--选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致-->
                <el-tooltip
                  :content="$t('system:menu:form:isCacheMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:isCache") }}
              </span>
              <el-radio-group v-model="form.IsCache">
                <el-radio :label="true">{{
                  $t("system:menu:form:radio:cache")
                }}</el-radio>
                <el-radio :label="false">{{
                  $t("system:menu:form:radio:notCache")
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <!--选择隐藏则路由将不会出现在侧边栏，但仍然可以访问-->
                <el-tooltip
                  :content="$t('system:menu:form:isDisplayMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:isDisplay") }}
              </span>
              <el-switch
                v-model="form.IsDisplay"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <!--c-->
                <el-tooltip
                  :content="$t('system:menu:form:isInTabDisplayMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:isInTabDisplay") }}
              </span>
              <el-switch
                v-model="form.IsInTabDisplay"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <!--选择停用则路由将不会出现在侧边栏，也不能被访问-->
                <el-tooltip
                  :content="$t('system:menu:form:isEnablesMessage')"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
                {{ $t("system:menu:form:isEnable") }}
              </span>
              <el-switch
                v-model="form.IsEnable"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType != 'F'" :span="24">
            <el-form-item :label="$t('system:menu:form:LangMark')">
              <el-input v-model="form.LanguageMark" placeholder="LangMark" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType != 'F'" :span="24">
            <el-form-item :label="$t('system:menu:form:meta')">
              <el-input
                v-model="form.Meta"
                type="textarea"
                placeholder="{ title: 'Setting', breadcrumb: false, role: [8, 1, 2, 3, 10] }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("system:menu:button:save")
        }}</el-button>
        <el-button @click="cancel">{{
          $t("system:menu:button:canel")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuList, addOrUpdateMenu, deleteMenu } from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";

export default {
  name: "Menu",
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 菜单状态数据字典
      visibleOptions: [],
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined,
      },
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        MenuName: [
          {
            required: true,
            message: this.$t("system:menu:form:rule:notMenuName"),
            trigger: "blur",
          }, // 菜单名称不能为空
        ],
        ShowOrder: [
          {
            required: true,
            message: this.$t("system:menu:form:rule:notShowOrder"),
            trigger: "blur",
          }, // 菜单顺序不能为空
        ],
      },
    };
  },
  created() {
    console.log(
      this.hasPermi(
        ["trials:trials-list:new", "trials:trials-list:export1"],
        "&&"
      )
    );
    this.getList();
    // this.getDicts("sys_show_hide").then(response => {
    //   this.visibleOptions = response.data;
    // });
  },
  methods: {
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    normalizer(node) {
      if (node.Children && !node.Children.length) {
        delete node.Children;
      }
      return {
        id: node.MenuId,
        label: node.MenuName,
        children: node.Children,
      };
    },
    toTree(arr, ParentId) {
      function loop(ParentId) {
        const res = [];
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i];
          item.hasChildren = false;
          if (item.ParentId !== ParentId) {
            continue;
          }
          item.Children = loop(item.MenuId);
          res.push(item);
        }
        return res;
      }
      return loop(ParentId);
    },
    // 选择图标
    selected(name) {
      this.form.MenuIcon = name;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getMenuList(this.queryParams)
        .then((res) => {
          this.menuList = this.toTree(
            res.Result,
            "00000000-0000-0000-0000-000000000000"
          );
          const menu = {
            MenuId: "00000000-0000-0000-0000-000000000000",
            MenuName: "主类目",
            Children: [],
          };
          menu.Children = this.menuList;
          this.menuOptions = Object.assign([], [menu]);
          this.loading = false;
        })
        .catch(function () {});
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      this.loading = true;
      getMenuList({})
        .then((res) => {
          const menu = {
            MenuId: "00000000-0000-0000-0000-000000000000",
            MenuName: "主类目",
            Children: [],
          };
          menu.Children = this.toTree(
            res.Result,
            "00000000-0000-0000-0000-000000000000"
          );
          this.menuOptions = Object.assign([], [menu]);
          this.loading = false;
        })
        .catch(function () {});
    },
    // 菜单显示状态字典翻译
    visibleFormat(row, column) {
      if (row.MenuType === "F") {
        return "";
      }
      return this.selectDictLabel(this.visibleOptions, row.visible);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        MenuId: null,
        ParentId: null,
        MenuType: "M",
        MenuIcon: "",
        MenuName: "",
        Path: "",
        Component: "",
        ShowOrder: null,
        IsEnable: true,
        IsCache: false,
        IsDisplay: false,
        IsInTabDisplay: false,
        IsExternalLink: false,
        PermissionStr: "",
        Note: "",
        CreateTime: "",
        LanguageMark: null,
        Apipath: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.ParentId = row.MenuId;
      }
      this.open = true;
      this.title = this.$t("system:menu:form:title:addMenu");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = this.$t("system:menu:form:title:editMenu");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addOrUpdateMenu(this.form).then((response) => {
            this.$message.success(this.$t("common:message:savedSuccessfully"));
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let message = this.$t("system:menu:confirm:message:delete").replace(
        "xxx",
        row.MenuName
      );
      //'是否确认删除名称为"' + row.MenuName + '"的数据项?'
      this.$confirm(message, this.$t("system:menu:confirm:title:warning"), {
        confirmButtonText: this.$t("system:menu:button:save"),
        cancelButtonText: this.$t("system:menu:button:canel"),
        type: "warning",
      })
        .then(function () {
          return deleteMenu(row.MenuId);
        })
        .then(() => {
          this.getList();
          this.$message.success(this.$t("common:message:deletedSuccessfully"));
        })
        .catch(function () {});
    },
  },
};
</script>
<style lang="scss">
.vue-treeselect div {
  line-height: 40px;
}
</style>
