<template>
  <div style="padding: 0px 100px;" class="flex">
    <div class="btn-group auto" style="margin-bottom: 30px">
      <button type="button" class="btn btn-primary" @click="removeData(ids)">批量删除</button>
      <button type="button" class="btn btn-primary" @click="setUser()">设置用户</button>
      <button type="button" class="btn btn-primary" @click="$goto('edit', {data: data})">策略授权</button>
      <button type="button" class="btn btn-primary">移动资源</button>
    </div>
    <rights-list :resource="data"></rights-list>
    <form class="datapanel">
      <h3 class="txtline">&nbsp;&nbsp;【{{data.name}}】角色管理</h3>
      <data-grid  partial='list' v-ref:grid :model="model">
        <template partial='head'>
          <tr>
            <th>全选
              <input type="checkbox" class="all-checked" v-model="checked" @click="$parent.$parent.isAll(checked)">
            </th>
            <th></th>
            <th>用户姓名</th>
            <th>修改</th>
            <th>删除</th>
          </tr>
        </template>
        <template partial='body'>
          <tr>
            <td style="text-align: center;">
              <input type="checkbox"  v-model="$parent.$parent.ids" :value="row">
            </td>
            <td style="text-align: center;"><img :src="$parent.$parent.imgsrc(row.f_icon)" alt=""></td>
            <td style="text-align: center;">{{row.name}}</td>
            <td style="text-align: center;"><img height="15" width="15" src="../../../static/ldaplefticon/修改.png" @click="$parent.$parent.modify(row)"></img></td>
            <td style="text-align: center;"><img height="15" width="15" src="../../../static/ldaplefticon/删除.png" @click="$parent.$parent.removeData([row])"></img></td>
          </tr>
        </template>
      </data-grid>
    </form>

    <!-- 设置用户模态框开始 -->
    <modal v-ref:modal :show.sync="setShow" :backdrop="false" class="auto">
      <header slot="modal-header" class="modal-header">
        <button type="button" class="close" @click="close"><span>&times;</span></button>
        <h4 class="modal-title">设置用户</h4>
      </header>
      <article slot="modal-body" class="modal-body modifystyle">
        <tree :model="usersData" v-ref:tree>
          <span partial>{{row.data.name}}
            <input type="checkbox" v-model="$parent.$parent.$parent.userids" :value="row.data.id">
          </span>
        </tree>
      </article>
      <footer slot="modal-footer" class="footerbtn">
        <button  type="button" class="btn btn-success" @click='save()'>保存</button>
      </footer>
    <modal>
    <!-- 设置用户模态框结束 -->
</template>

<script>
import co from 'co'
import * as Util from '../Util'

// 页面加载前，获取角色下的用户
let gen = function * (self) {
  //self.model = yield self.$post('rs/search', '{source: `tool.getChildren($${self.data.id}$)`, userid: self.userid}',{resolveMsg: null, rejectMsg: null})
  self.model = yield self.$http.post('rs/search', {source: `tool.getChildren($${self.data.id}$)`, userid: self.userid},{resolveMsg: null, rejectMsg: null})
  //self.model = yield self.$http.post('rs/search',data)
  console.log(self.model.body)
  console.log("加载时获取的用户:")
  //var r = self.model.body.filter(function(element,index,self){
   // return self.id.indexOf(element.id) === index;
  //});
  //去重
  function arrayUnique2(arr, name) {
    var hash = {};
    return arr.reduce(function (item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  }
  var r = arrayUnique2(self.model.body, "id")
  console.log(r)
  self.model.body = r
  //self.model.data.forEach((row) => {
  r.forEach((row) => {
    self.userids.push(row.id)
  })
}
// 删除当前角色写的用户
let deleteData = function * (self,data) {
  //yield self.$post('rs/data/deleteUser', {data: {ids: data, roleid: self.data.id}},{resolveMsg:null, rejectMsg:null})
  yield self.$http.post('rs/data/deleteUser', {data: {ids: data, roleid: self.data.id}}).then(function(res) {
    //console.log("删除")
    //console.log(res.bodyText)
    //self.$showMessage(res.bodyText)
    self.ids = []
    self.refresh()
  });
}
// 获取用户
let getUser = function * (self) {
  //let data = {source: `tool.getFullTree(this.getParent().getAllChildrens().where(row.getType() == $user$))`, userid: self.userid}
  //let ret = yield self.$http.post('/rs/search',{source: `tool.getFullTree(this.getParent().getAllChildrens().where(row.getType() == $user$))`, userid: self.userid})
  let ret = yield self.$http.post('/rs/search',{source: `tool.getFullTree(this.getParentByType($organization$).getAllChildrens().where(row.getType() == $user$))`, userid: self.userid})
  self.usersData = ret.data[0].children
  console.log(self.userData)
  self.setShow = true
}
// 设置用户后的保存
let saveUser = function * (self) {
  //let res = yield self.$post('rs/data/setUser', {data: {ids: self.userids, roleid: self.data.id}},{resolveMsg: null, rejectMsg: null})
  console.log("需要保存的用户")
  //var arr = ['apple','strawberry','banana','pear','apple','orange','orange','strawberry'];
  var r = self.userids.filter(function(element,index,self){
         return self.indexOf(element) === index;
  });
  console.log(r);
  console.log(self.userids)
  yield self.$http.post('rs/data/setUser',{data: {ids:r, roleid: self.data.id}}).then(function(res){
    if(res.status == 200){
      self.$showMessage(res.bodyText)
      self.setShow = false
      self.refresh()
    }else{
      self.$showMessage("保存失败")
    }
  });
  //yield self.$showMessage(res.data)

  /*if (res.data === '保存成功') {
    self.setShow = false
    // // 刷新数据

  }*/

}
export default {
  title: '角色管理',
  props: ['data', 'userid'],
  ready() {
    this.$parent.setTitle(this.data.name)
    this.refresh()
  },
  data () {
    return {
      ids: [],
      model: '',
      usersData: '',
      userids: [],
      setShow: false
    }
  },
  methods: {
    // 刷新数据
    refresh () {
      let g = gen(this)
      co(g)
    },
    add(name, row) {
      // console.log(name)
      let parent = this.datas
      let del = delete parent.children
      this.$goto(name, {parent: parent, row: row})
    },
    isAll (checked) {
      this.ids = []
      if (!checked) {
        this.model.data.forEach((row) => {
          this.ids.push(row)
        })
      }
    },
    imgsrc (name) {
      return Util.getImgsrc(name)
    },
    removeData (data) {
      var removeName = ''
      data.forEach((item) => {
        removeName = removeName + item.name + ';'
      })
      this.$showMessage('确定要删除【'+removeName+'】', ['confirm', 'cancel']).then((res) => {
        if (res === 'confirm') {
          let d = deleteData(this,data)
          co(d)
        }
      })
    },
    // 设置用户，弹出模态框设置用户getUser
    setUser () {
      let get = getUser(this)
      co(get)
    },
    // 关闭设置用户模态框
    close () {
      // this.$showMessage('哈哈哈啊哈哈')
      this.setShow = false
    },
    // 保存设置的用户
    save () {
      let s = saveUser(this)
      co(s)
    },
    // modify(row) {
    //   this.$goto("modify-function", {parentname: this.datas.name, parentid: this.datas.id, row: row})
    // }
  }
}
</script>
<style>
  .all-checked {
    vertical-align: text-top;
    margin-left: 10px !important;
  }
  td > .glyphicon {
    cursor: pointer;
  }
  th > input[type="checkbox"], td > input[type="checkbox"] {
    cursor: pointer;
  }
  .modifystyle div{
    margin-left: 0px;
    color: #000;
  }
  .modifystyle span {
    color: #000;
  }
  .modifystyle .list-group-item {
    background-color: #fff;
    border: none;
  }
  .modifystyle .list-group-item.active,
  .modifystyle  .list-group-item.active:hover,
  .modifystyle  .list-group-item.active:focus {
    background-color: #fff;
  }
</style>
