<template>
  <div class="system-menu card" v-loading="delLoading">
    <div class="header">
      <el-form size="mini" :inline="true" label-width="80px">
        <el-form-item label>
          <el-button type="primary" @click="showDialog({ id: 0 }, 2)">
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-wrap" v-loading="loading">
      <table-view
        :tableColumns="tableColumns"
        rowKey="id"
        :serialNumber="false"
        :treeConfig="{
          children: 'children',
          reserve: true
        }"
        :sourceData="sourceData"></table-view>
    </div>

    <el-dialog
      :title="isEdit ? '修改' : '新增'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      v-loading="formLoading"
      :before-close="beforeClose"
      width="820px">
      <el-form
        size="mini"
        :inline="true"
        label-width="120px"
        :rules="rules"
        ref="editForm"
        :model="editForm">
        <el-form-item label="菜单名称" prop="name" required>
          <el-input style="width: 220px" v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="父级菜单">
          <el-cascader
            :show-all-levels="false"
            v-model="editForm.pid"
            :disabled="editForm.type === 1"
            style="width: 220px"
            :options="showMenu"
            :props="{
              checkStrictly: true,
              label: 'name',
              value: 'id',
              emitPath: false
            }"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="类型" prop="type" required>
          <div style="width: 220px; display: inline-block" class="radioGroup">
            <el-radio v-model="editForm.type" :label="0">菜单</el-radio>
            <el-radio v-model="editForm.type" :label="1">按钮</el-radio>
            <el-radio v-model="editForm.type" :label="2">左边栏</el-radio>
          </div>
          <!--          <el-select-->
          <!--            style="width: 220px"-->
          <!--            v-model="editForm.type"-->
          <!--            placeholder="请选择"-->
          <!--          >-->
          <!--            <el-option label="菜单" :value="0"></el-option>-->
          <!--            <el-option label="按钮" :value="1"></el-option>-->
          <!--            <el-option-->
          <!--              label="左边栏"-->
          <!--              :value="2"-->
          <!--            ></el-option>-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item
          label="路径名称"
          :required="editForm.pid !== 0"
          prop="path">
          <el-input
            style="width: 220px"
            :disabled="isEdit"
            v-model="editForm.path"></el-input>
        </el-form-item>
        <el-form-item label="路径地址">
          <el-input style="width: 220px" v-model="editForm.route"></el-input>
        </el-form-item>
        <el-form-item label="接口路径">
          <el-input style="width: 220px" v-model="editForm.url"></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input style="width: 220px" v-model="editForm.level" />
        </el-form-item>
        <el-form-item label="启用状态" prop="enable">
          <div style="width: 220px; display: inline-block">
            <el-radio v-model="editForm.enable" :label="true">启用</el-radio>
            <el-radio v-model="editForm.enable" :label="false">禁用</el-radio>
          </div>
        </el-form-item>
        <el-form-item label=" 排序">
          <el-input
            style="width: 220px"
            v-model="editForm.sortNo"
            placeholder></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input style="width: 220px" v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input style="width: 220px" v-model="editForm.describe"></el-input>
        </el-form-item>
        <!-- <el-form-item label="应用名称">
          <el-select
            v-model="editForm.appId"
            style="width: 400px"
            clearable
            placeholder="请选择">
            <el-option
              v-for="(item, index) in applicationList"
              :key="index"
              filterable
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="包含的namespace">
          <el-select
            v-model="editForm.includeNamespace"
            multiple
            style="width: 400px"
            clearable
            placeholder="请选择">
            <el-option
              v-for="(item, index) in simpleList"
              :key="index"
              filterable
              :label="item.companyName"
              :value="item.apiName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排除的namespace">
          <el-select
            v-model="editForm.excludeNamespace"
            multiple
            style="width: 400px"
            clearable
            filterable
            placeholder="请选择">
            <el-option
              v-for="(item, index) in simpleList"
              :key="index"
              :label="item.companyName"
              :value="item.apiName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="small" @click="clone">取 消</el-button>
        <el-button size="small" type="primary" @click="submit">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import tableView from '@/common/components/base/tableView.vue'
// import myLayout from '@/common/components/base/myLayout.vue'
import {
  updateSysmenu,
  getAllMenusTree,
  updateMenu,
  addMenu,
  deleteMenu,
  getSimpleByPage
} from '../common/api/sys'

export default {
  name: 'saasMenu',
  components: {
    tableView
    // myLayout,
  },
  data() {
    return {
      applicationList: [],
      loading: false,
      sourceData: [],
      dialogVisible: false,
      formLoading: false,
      delLoading: false,
      editForm: {
        name: '',
        pid: '0',
        type: '',
        path: '',
        url: '',
        title: '',
        describe: '',
        enable: true,
        includeNamespace: '',
        excludeNamespace: '',
        appId: ''
      },
      rules: {
        type: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          }
        ]
      },
      isEdit: false,
      simpleList: []
    }
  },
  computed: {
    tableColumns() {
      return [
        {
          label: '菜单名称',
          key: 'name',
          width: '',
          align: 'left',
          treeNode: true
        },

        {
          label: '类型',
          key: 'type',
          width: '',
          render: (item) =>
            item.type === 0 ? '菜单' : item.type === 1 ? '按钮' : '左边栏'
        },
        {
          label: '路径名称',
          key: 'path',
          width: ''
        },
        {
          label: '路径地址',
          key: 'route',
          width: ''
        },
        {
          label: '接口路径',
          key: 'url',
          width: ''
        },
        {
          label: '排序',
          key: 'sortNo',
          width: ''
        },
        {
          label: '启动状态',
          key: 'url',
          width: '',
          render: (item) => (
            <el-checkbox
              value={item.enable}
              onChange={(v) => this.enableChange(item, v)}
              label=""></el-checkbox>
          )
        },
        {
          label: '标题',
          key: 'title',
          width: ''
        },
        {
          label: '备注',
          key: 'describe',
          width: ''
        },
        {
          label: '操作',
          key: '',
          width: '',
          align: 'left',
          render: (item) => (
            <div>
              <el-button
                size="mini"
                type="text"
                onClick={() => this.showDialog(item, 1)}>
                修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                onClick={() => this.remove(item)}>
                删除
              </el-button>
              {item.type !== 1 && (
                <el-button
                  size="mini"
                  type="text"
                  onClick={() => this.showDialog(item, 2)}>
                  新增下级
                </el-button>
              )}
            </div>
          )
        }
      ]
    },
    showMenu() {
      const data = JSON.parse(JSON.stringify(this.sourceData))
      const arr = []
      for (const iterator of data) {
        const children = []
        for (const iterato of iterator.children) {
          if (iterato.type === 0) {
            children.push(iterato)
          }
          delete iterato.children
        }
        iterator.children = children
        arr.push(iterator)
      }
      return [
        {
          id: 0,
          name: '顶级菜单',
          children: arr,
          describe: '',
          enable: true,
          path: '',
          pid: '',
          route: '',
          sortNo: 0,
          title: '',
          type: 0,
          url: ''
        }
      ]
    }
  },
  mounted() {
    this.getlist()
    this.getSimpleByPage()
  },
  methods: {
    getSimpleByPage() {
      getSimpleByPage().then((res) => {
        if (res.code === 200) {
          this.simpleList = res.data.records
        }
      })
    },
    async enableChange(item, v) {
      try {
        const res = await updateSysmenu({
          id: item.id,
          enable: v,
          type: item.type
        })
        if (res.code === 200) {
          this.$message.success(res.message)
          item.enable = v
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getlist(id, cb) {
      this.loading = true
      try {
        const res = await getAllMenusTree()
        if (res.code === 200) {
          if (cb) {
            cb(res.data)
          } else {
            this.sourceData = res.data
          }
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    resetForm() {
      for (const key in this.editForm) {
        if (key === 'enable') continue
        this.editForm[key] = ''
      }
    },
    async showDialog(item, t) {
      if (t === 2) {
        this.editForm.pid = item.id
        this.isEdit = false
      } else {
        this.isEdit = true
        if (item.excludeNamespace && item.excludeNamespace.length > 0) {
          item.excludeNamespace = item.excludeNamespace.split(',')
        }
        if (item.includeNamespace && item.includeNamespace.length > 0) {
          item.includeNamespace = item.includeNamespace.split(',')
        }
        this.editForm = item
      }
      // getApplication().then((res) => {
      //   if (res.code === 200) {
      //     this.applicationList = res.data || []
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate()
      })
      this.dialogVisible = true
      //   }
      // })
    },
    async submit() {
      try {
        if (!(await this.$refs.editForm.validate())) return
      } catch {
        return
      }
      this.formLoading = true
      const api = this.isEdit ? updateMenu : addMenu
      delete this.editForm.children
      try {
        if (
          this.editForm.includeNamespace &&
          this.editForm.includeNamespace.length > 0
        ) {
          this.editForm.includeNamespace =
            this.editForm.includeNamespace.join(',')
        } else {
          this.editForm.includeNamespace = ''
        }
        if (
          this.editForm.excludeNamespace &&
          this.editForm.excludeNamespace.length > 0
        ) {
          this.editForm.excludeNamespace =
            this.editForm.excludeNamespace.join(',')
        } else {
          this.editForm.excludeNamespace = ''
        }
        const res = await api({ ...this.editForm })
        if (res.code === 200) {
          this.$message.success(res.message)
          this.getlist()
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.resetForm()
        this.formLoading = false
        this.dialogVisible = false
      }
    },
    async remove(item) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return
      }
      this.delLoading = true
      try {
        const res = await deleteMenu(item.id)
        if (res.code === 200) {
          this.$message.success(res.message)
          this.delLoading = false
          await this.getlist()
        }
      } catch (e) {
        console.error(e)
        this.delLoading = false
      }
    },
    clone() {
      this.resetForm()
      this.dialogVisible = false
    },
    beforeClose(clone) {
      this.resetForm()
      clone()
    }
  }
}
</script>
<style lang="scss" scoped>
.system-menu {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px 20px 0;
  overflow: hidden;
}

.table-wrap {
  flex: 1;
}

.radioGroup {
  .el-radio {
    margin-right: 15px !important;
  }
}
</style>
