<template>
  <a-card :bordered="false" :bodyStyle="{overflowY: 'auto'}"   :style="{height:windowHeight +'px'}">
    <a-row :gutter="24">
      <a-button style="margin-right: 10px;" type="primary" icon="plus" @click="addChild">添加子菜单</a-button>
      <a-button style="margin-right: 10px;background-color: #19be6b;color: #fff;" type="" icon="plus" @click="addTitle">添加顶部菜单</a-button>
      <a-button style="margin-right: 10px;background-color: red;color: #fff;" type="" icon="delete" @click="delect()">删除</a-button>
    </a-row>
    <a-row :gutter="24">
      <!-- 左侧菜单树列表 -->
      <a-col :span="8">
        <a-row :gutter="24" class="textCount">
          <a-icon type="info-circle" style="color: #1890FF;margin-right: 10px;" />
          <span>当前选择：<span style="color: #40a9ff;font-weight: 600;">{{ selectedMenu }}</span><span v-if="selectedKeys.length" class="imgSize" @click="cancelSel">取消选择</span></span>
        </a-row>
        <a-row :gutter="24" >
          <a-input-search placeholder="输入搜索菜单名搜索" style="width: 100%" @change="onChange" />
          <div style="max-height: 600px;overflow: auto;">
            <a-tree
              @expand="onExpand"
              :treeData="getMenus"
              :expandedKeys="expandedKeys"
              :autoExpandParent="autoExpandParent"
              @select="onSelect"
              :selectedKeys="selectedKeys"
              showIcon
            >
              <template slot="title" slot-scope="{title}">
                <span v-if="title.indexOf(searchValue) > -1">
                  {{ title.substr(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ title }}</span>
              </template>
              <a-icon slot="file" type="file" />
              <a-icon slot="pushpin" type="pushpin" />
            </a-tree>
          </div>
        </a-row>
      </a-col>
      <!-- 右侧 -->
      <a-col :span="16" >
        <a-form :form="form" @submit="handleSubmit">
          <!-- 类型 -->
          <a-form-item label="类型" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <div v-if="!formData.type||formData.type=='0'">
              <a-icon type="file" style="margin-right: 10px;" /><span >页面菜单</span>
            </div>
            <div v-if="formData.type=='1'">
              <a-icon type="pushpin" style="margin-right: 10px;" /><span >操作按钮</span>
            </div>
          </a-form-item>
          <a-form-item label="ID" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            {{ formData.id }}
          </a-form-item>
          <a-form-item label="父节点ID" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              placeholder="请输入父节点ID(最多50个字符)"
              :maxLength="50"
              v-decorator="['formData.parentId', {
                initialValue: formData.parentId,
                getValueFromEvent: $filterEmpty,
                rules: [{ required: true, message: '请输入父节点ID!' }] }]"
            />
          </a-form-item>
          <!-- 名称 -->
          <a-form-item label="名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              placeholder="请输入名称(最多30个字符)"
              v-decorator="['formData.name', {
                initialValue: formData.name,
                getValueFromEvent: $filterEmpty,
                rules: [{ required: true, message: '请输入名称!' }] }]"
            />
          </a-form-item>

          <!-- 前端权限编码 -->
          <a-form-item label="前端权限编码" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              placeholder="请输入前端权限编码"
              v-decorator="[
                'formData.code',
                {
                  initialValue: formData.code,
                  rules: [{ required: true, message: '请输入前端权限编码!' }] },
              ]"
            />
          </a-form-item>
          <!-- 后台权限编码 -->
          <a-form-item label="后台权限编码" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-textarea
              placeholder="请输入后台权限编码"
              :auto-size="{ minRows: 2, maxRows: 6 }"
              v-decorator="[
                'formData.permission',
                {
                  initialValue: formData.permission,
                  rules: [{ required: formData.isLeaf, message: '请输入后台权限编码!' }] },
              ]"
            />
          </a-form-item>
          <a-form-item label="价格权限" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-checkbox-group v-model="authPrice" :options="priceOptions" @change="onPriceChange" />
          </a-form-item>
          <!-- 排序值 -->
          <a-form-item label="排序值" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input-number
              style="width: 100%;"
              type="number"
              placeholder="请输入排序值(0~999999)"
              v-decorator="['formData.sort', {
                initialValue: formData.sort,
                rules: [] }]"
              :max="99999999"
              :min="0"
            />
          </a-form-item>
          <!-- 状态 -->
          <a-form-item label="启用" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-radio-group
              name="radioGroup"
              v-decorator="[
                'formData.status',
                {
                  initialValue: formData.status,
                  rules: [{ required: true, message: '请选择状态!' }] },
              ]"
            >
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
            <a-button size="large" type="primary" @click="handleSubmit()">
              保存
            </a-button>
          </a-form-item>
        </a-form>

      </a-col>
    </a-row>
    <childModal parentType="admin" :visible="showChildModal" @refresh="getYyMenuList" :data="parentData" @close="showChildModal = false"></childModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import childModal from './childModal.vue'
import { getYyMenuList, saveYyMenu, deleteYyMenu } from '@/api/menu.js'

export default {
  name: 'AdminMenus',
  mixins: [commonMixin],
  components: {
    STable, VSelect, childModal
  },
  props: {},
  data () {
    return {
      priceOptions:[],
      authPrice: [],
      treeData: [],
      dataList: [],
      searchValue: '',
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      selectedMenu: '', // 选择的树节点名
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'menu' }),
      showChildModal: false,
      parentData: {}, // 父级菜单
      currMenusData:null,
      formData: {
        id: '',
        name: '',
        routePath: '',
        icon: '',
        routeName: '',
        componentPath: '',
        urlPath: '',
        code: '',
        permission: '',
        sort: '',
        type: '0',
        isLeaf: true,
        status: '' // 活动状态
      },
      windowHeight:0
    }
  },
  computed: {
    getMenus () {
      this.generateList(this.treeData)
      return this.treeData
    }
  },
  methods: {
    onPriceChange(val){
      console.log(val,this.authPrice,this.currMenusData)
      
      const data = this.currMenusData
      if(!data){
        this.$message.warning('请选择一个父级菜单')
        this.authPrice = []
        return false
      }

      // 当前选中节点的价格code
      const child = data&&data.dataRef&&data.dataRef.children ? data.dataRef.children : []
      data.dataRef.children = child
      const curAuth = []
      child.map(item=>{
        const a = item.code.split('_')
        const b = a[a.length-1]
        const c = this.priceOptions.find(item => item.value == b)
        if(c){
          curAuth.push(a[a.length-1])
        }
      })
 
      // 添加
      if(val.length > curAuth.length){
        const diff = val.filter(item => !new Set(curAuth).has(item))
        console.log(diff)
        const n = this.priceOptions.find(item=>item.value == diff[0])
        this.addChildPrice({
          parentId: data.id,
          name: n.label,
          code: data.code +'_'+diff[0],
          status: 1,
          sort: curAuth.length
        },function(ret){
          ret.title = ret.name
          child.push(ret)
        })
      }else{
        // 删除
        const diff = curAuth.filter(item => !new Set(val).has(item))
        const idx = child.findIndex(item => {
          const a = item.code.split('_')
          return a[a.length-1] == diff[0]
        })
        console.log(child[idx])
        this.delChildPrice(child[idx].id,function(){
          child.splice(idx,1)
        })
      }
    },
    onExpand (expandedKeys) {
      // console.log('onExpand', expandedKeys)
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSelect (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      if (info.selected) {
        this.clear()
        const data = info.selectedNodes[0].data.props
        const isLeaf = data.dataRef.children || []
        console.log('onSelect', isLeaf)
        this.currMenusData = data // 当前节点的子级
        // 价格权限回显
        isLeaf.map(item => {
          const a = item.code.split('_')
          this.authPrice.push(a[a.length-1])
        })
        this.formData = {
          id: data.id,
          parentId: data.parentId,
          name: data.name,
          routePath: data.routePath,
          icon: data.icon,
          routeName: data.routeName,
          componentPath: data.componentPath,
          urlPath: data.urlPath,
          code: data.code,
          permission: data.permission,
          sort: data.sort,
          type: data.type,
          status: data.status,
          isLeaf: !(isLeaf && isLeaf.length)
        }

        this.selectedMenu = this.formData.name
        this.formData.status = Number(this.formData.status)
      } else {
        this.selectedMenu = ''
        this.clear()
      }
    },
    generateList (data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.title
        this.dataList.push({ key, title: key })
        node.scopedSlots = { title: 'title' }
        node.slots = { icon: node.type == '0' ? 'file' : 'pushpin' }

        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    getParentKey (key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some(item => item.title == key)) {
            parentKey = node.key
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },
    onChange (e) {
      const value = e.target.value
      const expandedKeys = this.dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.title, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    // 获取菜单树列表
    getYyMenuList () {
      getYyMenuList().then(res => {
        if (res.status == 200) {
          this.treeData = res.data
          this.$store.state.app.authMenusList = res.data
        }
      })
    },
    // 添加子节点
    addChild () {
      if (!this.selectedMenu) {
        return this.$message.warning('请先选择一个父级菜单')
      } else if (this.formData.type == '1') {
        return this.$message.warning('请选择一个页面级菜单')
      }
      this.showChildModal = true
      this.parentData = this.formData
    },
    // 添加顶部菜单
    addTitle () {
      this.showChildModal = true
      this.parentData = {}
    },
    //  取消选择
    cancelSel () {
      this.selectedKeys = []
      this.selectedMenu = ''
      this.clear()
    },
    // 清空列表
    clear () {
      this.form.resetFields()
      this.formData.id = ''
      this.formData.parentId = ''
      this.formData.name = ''
      this.formData.routePath = ''
      this.formData.icon = ''
      this.formData.routeName = ''
      this.formData.componentPath = ''
      this.formData.urlPath = ''
      this.formData.sort = ''
      this.formData.type = ''
      this.formData.status = ''
      this.formData.code = ''
      this.formData.permission = ''
      this.formData.isLeaf = true
      this.currMenusData = null
      this.authPrice = []
    },
    // 删除数据
    delect () {
      if (!this.selectedKeys.length) {
        return this.$message.warning('您还未选择要删除的数据')
      }
      const _this = this
      console.log(_this.formData.id, '_this.formData.id')
      this.$confirm({
        title: '警告',
        content: `确定要删除您选择的 ${_this.formData.name} 的数据吗?`,
        okText: '确定',
        cancelText: '取消',
        onOk () {
          _this.delChildPrice(_this.formData.id)
        }
      })
    },
    // 删除子级
    delChildPrice(id,callback){
      const _this = this
      deleteYyMenu({
        id: id
      }).then(res => {
        if (res.status == 200) {
          _this.$message.success('删除成功')
          _this.getYyMenuList()
          callback&&callback()
        }
      }).catch(() => {
        _this.$message.success('删除失败, 请稍后重试')
      })
    },
    // 保存提交
    handleSubmit () {
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          if (values.formData.permission) {
            values.formData.permission = values.formData.permission.replace(/\//g, '_')
          }
          this.addChildPrice(Object.assign({ id: this.formData.id }, values.formData))
        }
      })
    },
    // 新增子级
    addChildPrice(data,callback){
      saveYyMenu(data).then(res => {
        if (res.status + '' === '200') {
          this.$message.success(res.message ? res.message : '保存成功')
          this.getYyMenuList()
          callback&&callback(res.data)
        }
      })
    },
    handleCancel () {
      this.clear()
    },
    setTableH () {
      this.windowHeight = window.innerHeight - 90
    }
  },
  mounted () {
    this.priceOptions = this.$store.state.app.priceAuthOptions
    this.setTableH();
  },
  beforeCreate () {
    this.form = this.$form.createForm(this, { name: 'menu' })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getYyMenuList()
    })
  },
  watch: {

  }
}
</script>

<style>
  .menu-box::-webkit-scrollbar{
    width: 6px;
    height: 6px ;
  }

  .menu-box::-webkit-scrollbar-thumb{
    width: 6px;
    height: 6px ;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 2px #d1d1d1;
    background: #e4e4e4;
  }

  .textCount{
    border: 1px solid #91d5ff;
    background-color: #e6f7ff;
    border-radius: 5px;
    padding: 5px 10px 5px 20px;
    margin: 10px 0;
    color: rgba(0, 0, 0);
  }
  .imgSize{
    color: #2d8cf0;
    margin-left: 10px;
    font-size: 14px;
  }

</style>
