<template>
  <div class="system-menu card">
    <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"
      :before-close="beforeClose"
      width="620px"
    >
      <el-form
        size="mini"
        :inline="true"
        label-width="100px"
        :rules="rules"
        ref="editForm"
        :model="editForm"
      >
        <el-form-item label="菜单名称" prop="name" required>
          <el-input
            style="width: 164px"
            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: 164px"
            :options="showMenu"
            :props="{
              checkStrictly: true,
              label: 'name',
              value: 'id',
              emitPath: false,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="类型" prop="type" required>
          <el-select
            style="width: 164px"
            v-model="editForm.type"
            placeholder="请选择"
          >
            <el-option label="菜单" :value="0"></el-option>
            <el-option label="按钮" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="路径名称"
          :required="editForm.pid !== 0"
          prop="path"
        >
          <el-input
            style="width: 164px"
            :disabled="isEdit"
            v-model="editForm.path"
          ></el-input>
        </el-form-item>
        <el-form-item label="路径地址">
          <el-input
            style="width: 164px"
            v-model="editForm.route"
          ></el-input>
        </el-form-item>
        <el-form-item label="接口路径">
          <el-input
            style="width: 164px"
            v-model="editForm.url"
          ></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input
            style="width: 164px"
            v-model="editForm.level"
          />
        </el-form-item>
        <el-form-item label="启用状态">
          <div style="width: 164px; 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: 164px"
            v-model="editForm.sortNo"
            placeholder
          ></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input
            style="width: 164px"
            v-model="editForm.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            style="width: 164px"
            v-model="editForm.describe"
          ></el-input>
        </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,
} from '../common/api/sys'

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

        {
          label: '类型',
          key: 'type',
          width: '',
          render: (item) =>
            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()
  },
  methods: {
    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] = ''
      }
    },
    showDialog(item, t) {
      if (t === 2) {
        this.editForm.pid = item.id
        this.isEdit = false
      } else {
        this.isEdit = true
        this.editForm = { ...item, enable: true }
      }
      this.$nextTick(() => {
        this.$refs.editForm &&
          this.$refs.editForm.clearValidate()
      })
      this.dialogVisible = true
    },
    async submit() {
      try {
        if (!(await this.$refs.editForm.validate())) return
      } catch {
        return
      }
      const api = this.isEdit ? updateMenu : addMenu
      delete this.editForm.children
      try {
        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.dialogVisible = false
      }
    },
    async remove(item) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
      } catch {
        return
      }
      try {
        const res = await deleteMenu(item.id)
        if (res.code === 200) {
          this.$message.success(res.message)
          this.getlist()
        }
      } catch (e) {
        console.error(e)
      }
    },
    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;
}

.table-wrap {
  flex: 1;
}
</style>
