<template>
  <div class="app-container">
    <div class="app-container">
      <div class="filter-container">
        <el-button style="margin-left: 10px;" class="success" icon="el-icon-plus" @click="handleCreate">新增</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column label="菜单名称" header-align="center" width="180px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.menutype | menutypeFilter" size="small">
              <span>{{ scope.row.name }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标题" width="140px" header-align="center" align="center" prop="title" />
        <el-table-column label="路径" width="100px" header-align="center" align="center" prop="path" />
        <el-table-column label="组件" min-width="150px" header-align="center" align="center" prop="component" />
        <el-table-column label="图标" width="100px" header-align="center" align="center" prop="icon" />
        <el-table-column label="重定向" width="100px" header-align="center" align="center" prop="redirect" />
        <el-table-column label="顺序" width="100px" header-align="center" align="center" prop="sort" />
        <el-table-column label="启用" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_show" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2"  @change="handleEnableChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="80" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
            <span class="centerSpan">|</span>
            <el-button v-if="row.status!='已删'" class="miniDanger" icon="el-icon-delete" @click="handleRowDelete(row)" />
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        <el-form ref="dataForm" :rules="rules" :model="deptform" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="菜单名称" prop="name">
            <el-input ref="name" v-model="deptform.name" />
          </el-form-item>
          <el-form-item label="类型" prop="menutype">
            <el-radio-group ref="menutype" v-model="deptform.menutype">
              <el-radio label="first-menu">一级菜单</el-radio>
              <el-radio label="second-menu">二级菜单</el-radio>
              <el-radio label="button">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <span style="color:red;" v-if="deptform.menutype == 'second-menu'">上级菜单请选一级菜单</span>
            <span style="color:red;" v-else-if="deptform.menutype == 'button'">上级菜单请选二级菜单</span>
          </el-form-item>
          <el-form-item v-if="deptform.menutype !== 'first-menu'" label="上级菜单" prop="parentid">
            <tree-select
              :height="280"
              :width="200"
              :disabled="disabled"
              size="small"
              :data="menuList"
              :default-props="defaultProps"
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input ref="title" v-model="deptform.title" />
          </el-form-item>
          <el-form-item label="路径" prop="path">
            <el-input ref="path" v-model="deptform.path" />
          </el-form-item>
          <el-form-item v-if="deptform.menutype !== 'button'" label="组件" prop="component">
            <el-input ref="component" v-model="deptform.component" />
          </el-form-item>
          <el-form-item v-if="deptform.menutype !== 'button'" label="图标" prop="icon">
            <el-input ref="icon" v-model="deptform.icon" />
          </el-form-item>
          <el-form-item v-if="deptform.menutype !=='button'" label="重定向" prop="redirect">
            <el-input ref="redirect" v-model="deptform.redirect" />
          </el-form-item>
          <el-form-item label="顺序" prop="sort">
            <el-input ref="sort" v-model="deptform.sort" />
          </el-form-item>
          <el-form-item label="启用" prop="is_show">
            <el-switch ref="is_show" v-model="deptform.is_show" :disabled="dialogStatus=='update'" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="save" @click="dialogStatus==='create'?createData():updateData()"> 确认 </el-button>
          <el-button @click="dialogFormVisible = false" class="cancelClose"> 关闭 </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TreeSelect from '@/components/TreeSelect'
import waves from '@/directive/waves' // waves directive
import { isIntegerZero } from '@/utils/validate'
import { postJson,delJson } from '@/api/common'
import { MessageBox } from 'element-ui'
export default {
  name: 'Menu',
  components: { TreeSelect },
  directives: { waves },

  filters: {
    menutypeFilter(menutype) {
      const menutypeMap = {
        menu: '',
        button: 'warning'
      }
      return menutypeMap[menutype]
    }
  },
  data() {
    return {
      tableKey: 0,
      listLoading: true,
      list: [],
      menuList:[],
      disabled: false,



      deptform: {
        id: '',
        name: '',
        title: '',
        path: '',
        component: '',
        icon: '',
        redirect: '',
        sort: '',
        parnetid: '',
        menutype: 'first-menu',
        is_show: ''
      },
      rules: {
        name: [{ type: 'string', required: true, message: '菜单名称必填', trigger: 'change' }],
        title: [{ type: 'string', required: true, message: '菜单标题必填', trigger: 'change' }],
        path: [{ type: 'string', required: true, message: '路径必填', trigger: 'change' }],
        component: [{ type: 'string', required: true, message: '组件必填', trigger: 'change' }],
        sort: [{ validator: isIntegerZero, trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      table:{
        page:1,
        page_size:20
      }
    }
  },
  created() {
    this.getList()
    this.getMenuList()
  },
  methods: {
    getList() {
      this.listLoading = true
      let page = this.table.page
      let page_size = this.table.page_size
      let url = 'api/v1/system/menu/list' + '?page='+page+'&page_size='+ page_size
      let data = {}
      postJson(url,data).then(response => {
        if(response.code == 200){
          this.list = response.data.list
        }else{
          this.list = []
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1000)
      })
    },
    getMenuList() {
      let url = 'api/v1/system/menu/list'
      let data = {}
      postJson(url,data).then(response => {
        if(response.code == 200){
          this.menuList = response.data.list
        }else{
          this.menuList = []
        }
      })
    },

    resetRequestParam() {
      this.deptform.id = ''
      this.deptform.parentid = '-1'
      this.deptform.name = ''
      this.deptform.title = ''
      this.deptform.path = ''
      this.deptform.component = 'Layout'
      this.deptform.icon = ''
      this.deptform.redirect = ''
      this.deptform.sort = 0
      this.deptform.menutype = 'first-menu'
      this.deptform.is_show = 1
    },
    handleCreate() {
      this.resetRequestParam()
      this.getMenuList()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.name.focus()
      })
    },
    popoverHide(checkedIds, checkedData) {
      this.deptform.parentid = checkedIds
      console.log(this.deptform.parentid)
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let url = 'api/v1/system/menu/add'
          let parentid = 0
          if(this.deptform.menutype == 'first-menu'){
            parentid = 0
          }else{
            parentid = this.deptform.parentid
          }
          let menu_type = 1
          if(this.deptform.menutype == 'first-menu' || this.deptform.menutype == 'second-menu'){
            menu_type = 1
          }else{
            menu_type = 2
          }
          let level = 1
          if(this.deptform.menutype == 'first-menu'){
            level = 1
          }else if(this.deptform.menutype == 'second-menu'){
            level = 2
          }else{
            level = 3
          }
          let data = {
            "name": this.deptform.name,
            "title": this.deptform.title,
            "menu_type": menu_type,
            "level":level,
            "path": this.deptform.path,
            "icon": this.deptform.icon,
            "sort": parseInt(this.deptform.sort),
            "parent_id": parentid,
            "redirect": this.deptform.redirect,
            "component": this.deptform.component,
            "is_show":this.deptform.is_show
          }
          postJson(url,data).then(response => {
            if(response.code == 200){
              this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },

    handleUpdate(row) {
      if(row.level == 1){
        this.deptform.menutype = 'first-menu'
      }else if(row.level == 2){
        this.deptform.menutype = 'second-menu'
      }else{
         this.deptform.menutype = 'button'
      }
      this.defaultCheckedKeys = [row.parent_id]
      this.deptform.id = row.id
      this.deptform.name = row.name
      this.deptform.title =row.title
      this.deptform.path = row.path,
      this.deptform.icon = row.icon,
      this.deptform.sort = row.sort,
      this.deptform.parentid = row.parent_id
      this.deptform.redirect = row.redirect,
      this.deptform.component = row.component,
      this.deptform.is_show = row.is_show
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              let url = 'api/v1/system/menu/edit'
              let parentid = 0
              if(this.deptform.menutype == 'first-menu'){
                parentid = 0
              }else{
                parentid = this.deptform.parentid
              }
              let menu_type = 1
              if(this.deptform.menutype == 'first-menu' || this.deptform.menutype == 'second-menu'){
                menu_type = 1
              }else{
                menu_type = 2
              }
              let level = 1
              if(this.deptform.menutype == 'first-menu'){
                level = 1
              }else if(this.deptform.menutype == 'second-menu'){
                level = 2
              }else{
                level = 3
              }
              let data = {
                "id":this.deptform.id,
                "name": this.deptform.name,
                "title": this.deptform.title,
                "menu_type": menu_type,
                "level":level,
                "path": this.deptform.path,
                "icon": this.deptform.icon,
                "sort": parseInt(this.deptform.sort),
                "parent_id": parentid,
                "redirect": this.deptform.redirect,
                "component": this.deptform.component,
                "is_show":this.deptform.is_show
              }
              postJson(url,data).then(response => {
                if(response.code == 200){
                  this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
                  this.dialogFormVisible = false
                  this.getList()
                }
              })
            }
          })
        }
      })
    },
    handleEnableChange(index, row) {
      let url = 'api/v1/system/menu/is_show'
      let data = {
        "menu_id":row.id,
        "is_show":row.is_show
      }
      postJson(url,data).then(response => {
        if(response.code == 200){
          this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
          this.getList()
        }
      })
    },
    handleRowDelete(row) {
      console.log('点击了行内删除')
      MessageBox.confirm('菜单名称:'+ row.name, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'api/v1/system/menu/'
        let data = row.id
        console.log(data)
        delJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      })
    }
  }
}
</script>
