
<template>
  <el-dialog
    v-dialog-drag
    :title="`${dialogStatus === 'create' ? '新增' : readonly ? '查看' : '编辑'}服务`"
    :visible.sync="dialogVisible"
    width="500px"
    append-to-body
    :destroy-on-close="true"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @close="handleCancel"
  >
    <el-form ref="form" :model="formState" :rules="rules" label-width="80px" :disabled="readonly">
      <el-form-item label="服务名称" prop="serviceName">
        <el-input v-model="formState.serviceName" placeholder="请输入服务名称" />
      </el-form-item>
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-tree
          ref="menu"
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          node-key="id"
          :check-strictly="menuCheckStrictly"
          empty-text="加载中，请稍后"
          :props="defaultProps"
        />
      </el-form-item>
    </el-form>

    <div v-show="!readonly" slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleCancel">取 消</el-button>
      <el-button size="small" type="primary" :loading="loading" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { listSimpleMenus } from '@/api/system/menu'
import { addService, fetchServiceInfo } from '@/api/system/service'

const initForm = {
  id: null,
  serviceName: null,
  menuIds: null
}
export default {
  name: 'ServiceDialog',
  data() {
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      menuExpand: false,
      readonly: false,
      menuNodeAll: false,
      menuCheckStrictly: true,
      loading: false,
      menuOptions: [], // 菜单列表
      dialogStatus: 'create',
      dialogVisible: false,
      formState: Object.assign({}, initForm),
      rules: {
        serviceName: [{ required: true, message: '服务名称不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getMenus()
  },
  methods: {
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    getMenus() {
      listSimpleMenus().then(response => {
        // 处理 menuOptions 参数
        this.menuOptions = []
        // 只需要配置
        this.menuOptions.push(...this.handleTree(response.data, 'id'))
      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      const treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = value
    },
    handleCancel() {
      this.dialogVisible = false
      this.readonly = false
      this.$refs.form.resetFields()
    },
    handleOpen() {
      this.dialogVisible = true
      this.dialogStatus = 'create'
    },
    handleEdit(row, readonly = false) {
      this.readonly = readonly
      this.dialogStatus = 'edit'
      this.dialogVisible = true
      fetchServiceInfo(row.id).then(({ data }) => {
        this.formState = data
        this.menuCheckStrictly = true
        // 设置选中
        this.$refs.menu.setCheckedKeys(data.menuIds.split(','))
        // 设置为非严格，继续使用半选中
        this.menuCheckStrictly = false
      })
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.formState.menuIds = this.getMenuAllCheckedKeys().join(',')
          addService(this.formState).then(() => {
            this.handleCancel()
            this.$modal.msgSuccess('保存成功')
            this.$emit('ok')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">

</style>
