<!-- taoyuan -->
<style scoped>
  .row {
    padding: 5px 0;
  }
</style>
<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6 col-sm-12">
        <div class="btn-group" v-if="isOpen">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            展开 <span class="caret"></span>
          </button>
          <ul class="dropdown-menu">
            <li>
              <a href="javascript:;;" @click="openClk(true)">
                <i class="fa fa-plus-square"></i>
                全部展开</a>
            </li>
            <li>
              <a href="javascript:;;" @click="openClk(false)">
                <i class="fa fa-minus-square"></i>
                全部收起
              </a>
            </li>
          </ul>
        </div>
        <div class="btn-group" role="group" aria-label="btn group">
          <template v-for="group in btnGroups">
            <button type="button" class="btn" :class="group.className" @click="group.event">
              <i class="fa" :class="group.iconName"></i>
              {{group.name}}
            </button>
          </template>
          <button type="button" class="btn btn-success" v-if="isExport" @click="exclClk">
            <i class="fa fa-file-text"></i>
            导出Excl
          </button>
        </div>
      </div>
      <div class="col-md-6 col-sm-12  clearfix">
        <div class="input-group clearfix"  style="float:right;">
          <el-autocomplete
            class="inline-input"
            v-model="filVal"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            @select="handleSelect"
            style="float:right"
          ></el-autocomplete>
          <span class="input-group-btn"  v-if="isMore">
            <button class="btn backgroundHeadtheme" type="button" @click="moreClk">
              <i class="fa fa-th"></i>
            </button>
          </span>
        </div>
      </div>
    </div>
    <div>
      <div>
          <tree-grid
            :dataSource='dataSource'
            :columns='columns'
            :tree-structure="true"
            :tableType = 4
            :btns="btns"
            :selectAll="selectAll"
            :select="select"
            :defaultExpandAll="defaultExpandAll"
            ref="tableGrid"
          ></tree-grid>
      </div>
    </div>
    <_POPUP :dialogObj='moduleNew' @confirmBack="moduleConfirmBack" @insertModule="insertModule"/>
    <_POPUP :dialogObj='moduleUpdate' @confirmBack="moduleConfirmBack" @updateModule="updateModule"/>
    <ul>
      <template v-for="item in userInfo">
        <li>{{item.value}}</li>
      </template>
    </ul>
  </div>
</template>
<script>
  import TreeGrid from '@/views/components/TabPagin/TreeGrid'
  import _POPUP from './AddModulePopup.vue'
  import _BTN_FILTER from '@/views/components/Screen/btn&filterTemp.vue'
  import BasePath from '@/config/BasePath'
  import api from '@/api'
  import log from '@/log'
  import { mapState } from 'vuex'
  export default {
    mounted () {
      /** 调用初始化数据 **/
      this.init()
    },
    data () {
      return {
        /** table **/
        isOpen: true, // 是否显示展开更多按钮
        isExport: true, // 是否显示导出elcx
        defaultExpandAll: true,
        columnType: 'selection',
        tableType: '4',
        currentPage: 1, // 默认当前第一页
        pageSize: 10,  // 默认每页20条数据
        pageSizes: [2, 5, 10, 20, 40, 50], // 分页数选择项
        totalCount: 0, // 表格总记录数
        isMore: false,
        btnGroups: [
          {
            name: '新增',
            className: 'btn-info',
            iconName: 'fa-plus',
            event: this.addClk
          }
        ],
        columns: [
          {
            value: 'resCode',
            label: '菜单代码',
            align: 'center'
          }, {
            value: 'resName', // 列的值
            label: '菜单名称', // 列的显示字段
            align: 'center' // 列的对齐方式，[left, center, right]，选填，默认是left
          }, {
            value: 'resSicon',
            align: 'center', // 列的css样式（选填）
            label: '图标'
          }, {
            value: 'resUrl',
            label: '链接',
            align: 'center'
          }, {
            value: 'status',
            label: '状态',
            align: 'center'
          }
        ],
        tableData: [],
        btns: {
          btnArr: [
            {
              label: '修改', // 按钮的名称
              value: 'modify', // 按钮的值
              functionName: this.modify, // 按钮的方法
              type: 'warning',
              icon: 'edit'
            },
            {
              label: '删除',
              value: 'del',
              type: 'danger',
              functionName: this.del,
              icon: 'delete'
            }
          ],
          value: 'operation',
          label: '操作',
          width: '180px'
        },
        dataSource: [], // 当前页的数据
        /** filter **/
        filmode: 0,  // 过滤方式；0:代表本地过滤，1：服务器过滤,
        filType: 1, // 过滤类型；0：单列数据过滤，1：整条数据过滤
        filVal: '', // 过滤变量
        fileName: ['resName', 'resCode'],
        keyupend: false,   // 输入筛选；true：之前展示；false：之后展示
        templTableData: [], // 临时记录tableDate的值
        /** 弹出层 **/
        moduleNew: {
          title: '新增模块',
          type: 'menuMaintenance',
          dialogVisible: false,
          nodeKey: 'id',
          data: {
            form: {
              resName: '',
              resSicon: '',
              resUrl: '',
              parentId: '',
              sortKey: '',
              status: '启用'
            }
          }
        },
        moduleUpdate: {
          title: '修改模块',
          type: 'menuMaintenance',
          dialogVisible: false,
          data: {
            form: {
              resName: '',
              resSicon: '',
              resUrl: '',
              parentId: '',
              sortKey: '',
              status: ''
            }
          }
        },
        /** 实际操作 **/
        sel_id: '', // 当前选中的值id
        sel_all: []
      }
    },
    computed: {
      ...mapState([
        'userInfo',
        'resSicon'
      ])
    },
    methods: {
      init () {
        let params = {}
        api.requestJava('POST', BasePath.MODULE_SELECTTREELIST, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              var tempArray = []
              tempArray.push(request.data.data)
              this.tableData = tempArray
              this.currentPage = 1
              this.queryData(this.currentPage, this.pageSize)
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '查询失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      .catch((err) => {
        this.$store.commit('TOGGLE_LOADING')
        let culprit = this.$route.name
        log.work(err, culprit)
      })
      },
      queryData (page, size) {
      // 前段分页
        this.totalCount = this.tableData.length
        this.dataSource = this.tableData.filter((u, index) => index < size * page && index >= size * (page - 1))
      }, // 分页请求
      select (selection, index) {
        if (selection[0] !== undefined) {
          this.sel_all = []
          for (var i in selection) {
            this.sel_all.push(selection[i].id)
          }
        } else {
        }
      }, // 选中某1条
      selectAll (data) {
        this.sel_all = []
        for (var i in data) {
          this.sel_all.push(data[i].id)
        }
      }, // 全选
      exclClk () {
        this.$refs.tableGrid.exportExcel()
      },
      addClk () {
        this.moduleNew.dialogVisible = true
      }, // 新增
      modify (index, row) {
        this.moduleUpdate.data.form.rowId = row.id
        this.moduleUpdate.data.form.resCode = row.resCode
        this.moduleUpdate.data.form.resName = row.resName
        this.moduleUpdate.data.form.resSicon = row.resSicon
        this.moduleUpdate.data.form.resUrl = row.resUrl
        this.moduleUpdate.data.form.parentId = row.treeId
        this.moduleUpdate.data.form.parentName = row.treeLabel
        if (row.status === '1') {
          this.moduleUpdate.data.form.status = '启用'
        } else {
          this.moduleUpdate.data.form.status = '停用'
        }
        this.moduleUpdate.dialogVisible = true
      }, // 修改
      insertModule (msg) {
        let params = {}
        params.resCode = this.moduleNew.data.form.resCode
        params.resName = this.moduleNew.data.form.resName
        params.resSicon = this.moduleNew.data.form.resSicon
        params.resUrl = this.moduleNew.data.form.resUrl
        params.parentId = this.moduleNew.data.form.parentId
        params.sortKey = '1'
        params.status = this.moduleNew.data.form.status
        params.modificationNum = 0
        params.deletedFlag = 0
        if (this.moduleNew.data.form.status === '启用') {
          params.status = 1
        } else {
          params.status = 0
        }
        params.resCatId = 1
        params.idTree = ''
        api.requestJava('POST', BasePath.MODULE_INSERTIDTREE, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.$message({ type: 'success', message: '保存成功!' })
              this.moduleNew.dialogVisible = false
              this.moduleConfirmBack()
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '新增失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      updateModule (msg) {
        let params = msg.data.form
        if (msg.data.form.status === '启用') {
          params.status = '1'
        } else {
          params.status = '0'
        }
        api.requestJava('POST', BasePath.MDOULE_UPDARE, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.moduleUpdate.dialogVisible = false
              this.$message({ type: 'success', message: '保存成功!' })
              this.init()
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '更新失败', message: request.data.result.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            this.$store.commit('TOGGLE_LOADING')
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      },
      del (index, row) {
        this.$confirm('确定删除此条信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {}
          let params1 = {}
          params1.resId = row.id
          params.rowId = row.id
          api.requestJava('POST', BasePath.ROLE_PERMISSIONS_QUERY, params1)
            .then((request) => {
              if (Number(request.data.code) === 200) {
                if (request.data.data.length !== 0) {
                  this.$message({type: 'info', message: '该条记录不能删除!'})
                } else {
                  api.requestJava('POST', BasePath.MODULE_DELETE, params)
                     .then((request) => {
                       if (Number(request.data.code) === 200) {
                         this.$message({type: 'success', message: '删除成功!'})
                         this.init()
                         // this.$delete(this.dataSource, index)
                       } else if (Number(request.data.code) === 401) {
                         this.$notify.error({ title: '删除失败', message: request.data.result.message })
                       } else if (Number(request.data.code) === 500) {
                         this.$message({type: 'info', message: '该条记录不能删除!'})
                       } else {
                         throw new Error(JSON.stringify(request))
                       }
                     })
                 .catch((err) => {
                   this.$store.commit('TOGGLE_LOADING')
                   let culprit = this.$route.name
                   log.work(err, culprit)
                 })
                }
              } else if (Number(request.data.code) === 401) {
                this.$notify.error({ title: '查询失败', message: request.data.result.message })
              } else {
                throw new Error(JSON.stringify(request))
              }
            })
      .catch((err) => {
        this.$store.commit('TOGGLE_LOADING')
        let culprit = this.$route.name
        log.work(err, culprit)
      })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除!' })
        })
      },  // 删除
      moduleConfirmBack (msg) {
        this.init()
        this.$set(this.moduleNew, 'data', this.moduleUpdate.data)
      },
      querySearch (queryString, cb) {
        this.temp = []
        let restaurants = this.tableData
        let results = queryString ? this.dataFilter(restaurants, queryString) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
        this.temp.push(...results)
        if (this.temp.length > 0) {
          let page = this.currentPage
          let size = this.pageSize
          this.dataSource = this.temp.filter((u, index) => index < size * page && index >= size * (page - 1))
        } else {
          this.dataSource = []
        }
      },
      dataFilter (restaurants, queryString) {
        let result = []
        restaurants.forEach((restaurant, n) => {
          let isTrue = false
          for (let i in this.fileName) {
            if (restaurant[this.fileName[i]].indexOf(queryString) !== -1) {
              result.push(restaurant)
              isTrue = true
              break
            }
          }
          if (!isTrue && restaurant.children.length > 0) {
            let temp = this.findInChild(restaurant.children, queryString)
            if (temp.length !== 0) {
              result.push(...temp)
            }
          }
        })
        return result
      },
      createFilterLine (queryString) {
        return (restaurant) => {
          this.isTrue = false
          this.tempMen(restaurant, queryString)
          return (this.isTrue === true)
        }
      }, // 过滤整条数据
      tempMen (obj, str) {
        for (let i in obj) {
          for (let j in this.fileName) {
            if (this.fileName[j] === i) {
              if (obj[i] !== undefined && obj[i].toString().toLocaleUpperCase().indexOf(str.toLocaleUpperCase()) === 0) {
                this.isTrue = true
              }
            }
          }
        }
      },
      findInChild (obj, str) {
        let result = []
        for (let i in obj) {
          let isTrue = false
          for (let j in this.fileName) {
            if (obj[i][this.fileName[j]].indexOf(str) !== -1) {
              result.push(obj[i])
              isTrue = true
              break
            }
          }
          if (!isTrue && obj[i].children.length > 0) {
            let temp = this.findInChild(obj[i].children, str)
            if (temp.length !== 0) {
              result.push(...temp)
            }
          }
        }
        return result
      },
      handleSelect (item) {
        console.log(item)
      },
      openClk (isTrue) {
        this.$refs.tableGrid.expand(isTrue)
      }
    },
    components: {
      // _TABLE,
      _BTN_FILTER,
      _POPUP,
      TreeGrid
    },
    watch: {
      filVal (val, oval) {
        if (val === '') {
          this.currentPage = 1
          this.queryData(this.currentPage, this.pageSize)
        }
      }
    }
  }
</script>
