<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-radio-group v-model="platform" size="small" @change="switchingPlatform">
          <el-radio-button :label="item.moduleKey" v-for="(item, index) in dataPlas" :key="index">{{item.moduleName}}</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增目录</el-button
        >
      </el-col>
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="menuList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="name"
        label="目录/API名称"
        :show-overflow-tooltip="true"
        width="300"
      ></el-table-column>
      <el-table-column
        prop="perm"
        label="api权限标识"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="url"
        label="URL"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column prop="type" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{
            scope.row.type === 0
              ? "目录"
              : scope.row.type === 1
              ? "api"
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="httpMethod"
        label="请求方式"
        align="center"
        :show-overflow-tooltip="true"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        align="center"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="belongSystem"
        label="所属服务"
        align="center"
        width="80"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="!scope.row.parentId"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="0" v-if="!form.parentId">目录</el-radio>
                <el-radio :label="1" v-if="form.parentId">API</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目录/API" prop="name">
              <el-input v-model="form.name" placeholder="请输入目录/API名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 0">
            <el-form-item label="请求方式" prop="httpMethod">
              <el-input
                v-model="form.httpMethod"
                placeholder="请输入请求方式（GET,POST,PUT..）"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 0">
            <el-form-item label="URL" prop="url">
              <el-input v-model="form.url" placeholder="请输入URL" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 0">
            <el-form-item label="权限标识" prop="perm">
              <el-input v-model="form.perm" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getApis,
  getApiTrees,
  addApi,
  delApi,
  editApi,
  plaDatas,
  getServer
} from "@/api/system/api";
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: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "目录/api名称", trigger: "blur" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        belongSystem: [{ required: true, message: "请选择所属服务", trigger: "blur" }],
        httpMethod: [{ required: true, message: "请输入请求方式", trigger: "blur" }],
        url: [{ required: true, message: "请输入URL", trigger: "blur" }],
      },
      platform: '',
      total: 0,
      dataPlas: []
    };
  },
  created() {
    this.getServerList()
  },
  methods: {
    getServerList() {
      getServer().then(res => {
        this.dataPlas = res.data
        if(res.data.length > 0) {
          this.platform = res.data[0].moduleKey
          this.getList();
        }
      })
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getApis(this.platform).then((response) => {
        this.loading = false;
        let dat = response.data[this.platform]
        let data = dat?.map((item) => {
          item.children = item.subApis;
          return item;
        });
        this.total = response.data.total
        this.menuList = data;
      });
    },
    /** 切换 */
    switchingPlatform(e) {
      this.platform = e
      this.getList()
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: "",
        sort: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != null && row.id) {
        this.form.parentId = row.id;
        this.form.type = 1;
      } else {
        this.form.type = 0;
      }
      this.open = true;
      this.title = "添加目录/API";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let { id, httpMethod, parentId, perm, sort, type, url, name } = row;
      let newForm = { id, sort, name, type };
      httpMethod && (newForm["httpMethod"] = httpMethod);
      parentId && (newForm["parentId"] = parentId);
      perm && (newForm["perm"] = perm);
      url && (newForm["url"] = url);
      this.form = newForm;
      this.title = "修改目录/API";
      this.open = true;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form);
          if (this.title === "添加目录/API") {
            addApi({...this.form, belongModule: this.platform}).then((res) => {
              if (res) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            editApi({...this.form, belongModule: this.platform}).then((res) => {
              if (res) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delApi(row.id);
        })
        .then((res) => {
          if (res.data) {
            this.msgSuccess("删除成功");
            this.open = false;
            this.getList();
          }else{
            this.$message.error('删除失败');
          }
        });
    },
  },
};
</script>