<template>
  <xy-page title="资源列表">
    <xy-search class="mgt20">
      <el-form
        inline
        :model="searchFilter"
        label-width="70px"
      >
        <el-form-item
          label="系统"
          prop
        >
          <el-select
            v-model="appId"
            placeholder="请选择系统"
          >
            <el-option
              v-for="item in appList"
              :key="item.id"
              :label="item.cnName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="right">
        <el-button
          plain
          @click="resetForm"
        >重置条件</el-button>
      </div>
    </xy-search>
    <div>
      <div
        v-if="appId"
        style="text-align:right;"
      >
        <xy-save
          v-model="isResetMenu"
          v-auth="'AUTH_RESOURCES-SAVE'"
          type="plane"
          size="small"
          text="重置中..."
          @click="resetMenu"
        >
          重置资源
        </xy-save>
        <xy-save
          v-model="isSave"
          v-auth="'AUTH_RESOURCES-SAVE'"
          type="primary"
          size="small"
          text="保存中..."
          @click="save"
        >
          保存
        </xy-save>
      </div>
      <div style="display:inline-block;width:49%;vertical-align:top;">
        <el-tree
          :data="treeData"
          node-key="id"
          :props="defaultProps"
          default-expand-all
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          empty-text="请选择系统"
          :expand-on-click-node="false"
          :highlight-current="true"
          draggable
          @node-drag-end="handleDragEnd"
          @node-click="nodeClick"
        >
          <span
            slot-scope="{ node, data }"
            class="custom-tree-node"
          >
            <span :class="{lineThrough:data.isActive === 0,green:data.id === 0}">{{ node.label }}</span>
            <span class="node-button">
              <el-button
                v-if="data.level < 2"
                v-auth="'AUTH_RESOURCES-SAVE'"
                type="text"
                size="mini"
                @click.stop="() => appendSub(data)"
              >子资源</el-button>
              <el-button
                v-if="data.id !== -1"
                v-auth="'AUTH_RESOURCES-SAVE'"
                type="text"
                size="mini"
                @click.stop="() => append(node, data)"
              >同级资源</el-button>
              <el-button
                v-if="data.id !== -1"
                v-auth="'AUTH_RESOURCES-SAVE'"
                type="text"
                size="mini"
                @click.stop="() => remove(node, data)"
              >删除</el-button>
            </span>
          </span>
        </el-tree>
      </div>
      <div
        v-if="typeof menu.id !== 'undefined'"
        style="display:inline-block;width:49%;vertical-align:top;"
      >
        <div class="form-row form-group">
          <label class="text-right">
            <span class="require"></span>资源id:
          </label>
          <el-input
            v-model="menu.id"
            type="test"
            :disabled="true"
            placeholder="资源id"
          />
        </div>
        <div class="form-row form-group">
          <label class="text-right">
            <span class="require">*</span>资源名字:
          </label>
          <el-input
            v-model="menu.name"
            type="test"
            placeholder="请输入资源名字"
          />
        </div>
        <div class="form-row form-group">
          <label class="text-right">
            <span class="require">*</span>资源地址:
          </label>
          <el-input
            v-model="menu.url"
            type="test"
            placeholder="请输入资源地址"
          />
        </div>
        <div class="form-row form-group">
          <label class="text-right">
            <span class="require">*</span>编码:
          </label>
          <el-input
            v-model="menu.code"
            type="test"
            placeholder="请输入资源编码"
          />
        </div>
        <div class="form-row form-group">
          <label class="text-right">
            <span class="require">*</span>类型:
          </label>
          <div>
            <el-radio
              v-model="menu.type"
              :label="1"
            >链接</el-radio>
            <el-radio
              v-model="menu.type"
              :label="2"
            >按钮</el-radio>
            <el-radio
              v-model="menu.type"
              :label="3"
            >无</el-radio>
          </div>
        </div>
      </div>
    </div>
  </xy-page>
</template>

<script>
export default {
  name: 'AuthMenuList',
  data() {
    return {
      searchFilter: {},
      appId: null,
      appList: [],

      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isResetMenu: false,
      isSave: false,
      menu: {}
    }
  },
  watch: {
    appId() {
      if (!this.appId) {
        return
      }
      this.resetData()
    }
  },
  mounted() {
    this.resetForm()
  },
  methods: {
    appendSub(data) {
      const menu = {
        id: 0,
        isActive: 1,
        name: '新建资源',
        url: '',
        children: []
      }
      data.children.push(menu)
      this.setLevel(this.treeData)
      this.menu = menu
      const tmp = this.treeData
      this.treeData = []
      this.$nextTick(() => {
        this.treeData = tmp
      })
    },
    remove(node, data) {
      this.$xyConfirm('确认是否删除，删除后数据将无法恢复？', () => {
        let index = -1
        node.parent.data.children.forEach((item, i) => {
          if (item === data) {
            index = i
          }
        })
        if (index === -1) return
        node.parent.data.children.splice(index, 1)
        this.setLevel(this.treeData)
        if (this.menu === data) {
          this.menu = {}
        }
      })
    },
    append(node) {
      const menu = {
        id: 0,
        isActive: 1,
        name: '新建资源',
        url: '',
        children: []
      }
      node.parent.data.children.push(menu)
      this.setLevel(this.treeData)
      this.menu = menu
    },
    handleDragEnd() {
      this.setLevel(this.treeData)
    },
    allowDrop(draggingNode, dropNode, type) {
      if (dropNode.data.id === -1) {
        return false
      }
      if (dropNode.data.level === 3) {
        return type !== 'inner'
      }
      return true
    },
    allowDrag(draggingNode) {
      if (draggingNode.data.id === -1) {
        return false
      }
      return true
    },
    nodeClick(menu) {
      if (menu.id === -1) {
        menu = {}
      }
      this.menu = menu
    },
    setLevel(data, level, sort) {
      level = level || 0
      sort = sort || 0
      if (!data || data.length === 0) {
        return sort
      }
      data.forEach(item => {
        item.level = level
        if (level <= 1) {
          item.type = 3
        } else if (!item.type) {
          item.type = 1
        }
        item.appId = this.appId
        item.sort = sort++
        item.children = item.children || []
        sort = this.setLevel(item.children, level + 1, sort)
      })
      return sort
    },
    resetMenu() {
      this.$xyConfirm('确认是否重置资源，重置后修改的数据将无法恢复？', () => {
        this.isResetMenu = true
        this.resetData(() => {
          this.isResetMenu = false
        })
      })
    },
    resetData(cb) {
      this.menu = {}
      this.treeData = []
      this.$nextTick(() => {
        this.$postStream('/admin/auth/instance/authResources/list.do', {
          data: {
            appId: this.appId
          },
          success: res => {
            this.treeData = res.object || []
            this.treeData = [
              {
                id: -1,
                name: '全部资源',
                children: this.treeData
              }
            ]
            this.setLevel(this.treeData)
            cb && cb()
          }
        })
      })
    },
    save() {
      this.setLevel(this.treeData)
      this.isSave = true
      this.$postStream('/admin/auth/instance/authResources/save.do', {
        data: this.treeData[0],
        success: res => {
          this.isSave = false
          if (!res.success) {
            return this.$message.error(res.message)
          }
          this.$message.success(res.message)
          this.resetData()
        }
      })
    },
    resetForm() {
      this.$postStream('/admin/auth/instance/authApp/list.do', {
        data: {},
        success: res => {
          if (res.success) {
            this.appList = res.object.list || []
            this.appId = ''
            this.treeData = []
          } else {
            this.$message.error(res.message)
          }
        },
        error: () => { }
      })
    }
  }
}
</script>

<style lang="scss">
.lineThrough {
  text-decoration: line-through;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 10px;
}
</style>
