<template>
<div class="app-container calendar-list-container">
  <div class="filter-container">
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="姓名或账户" v-model="listQuery.name"> </el-input>
    <el-button class="filter-item" type="primary" plain @click="handleFilter">搜索</el-button>
    <el-button class="filter-item" type="primary" plain @click="cleanFilter">清除搜索</el-button>
    <el-button class="filter-item" v-if="groupTypeManager_btn_add" style="margin-left: 10px;" @click="handleCreate(1)" type="primary"><i class="el-icon-plus"></i>添加角色</el-button>
  </div>
  <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
    <el-table-column type="index" align="center" label="序号" width="98"></el-table-column>
    <el-table-column align="center" label="角色名称">
      <template slot-scope="scope">
        <span>{{scope.row.name}}</span>
      </template>
    </el-table-column>
    <el-table-column align="center" label="描述">
      <template slot-scope="scope">
        <span>{{scope.row.description}}</span>
      </template>
    </el-table-column>
    <el-table-column align="center" label="操作" width="260px">
      <template slot-scope="scope">
        <el-button v-if="groupTypeManager_btn_edit" size="small"  type="text" @click="handleUpdate(scope.row)">基础信息</el-button>
        <el-button v-if="groupTypeManager_btn_edit" size="small"  type="text" @click="setRights(scope.row)">权限设置</el-button>
        <el-button v-if="groupTypeManager_btn_del" size="small"  type="text" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div v-show="!listLoading" class="pagination-container">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
  </div>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" placeholder="请输入描述"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel('form')">取 消</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>
  <!--权限设置-->
  <el-dialog title="权限设置" class="rights-main" :visible.sync="rightDialogVisible" lock-scroll :before-close="closeRightBtn">
    <el-row class="table-row-header">
      <el-col :span="4" class="tc border-r tc-header">一级</el-col>
      <el-col :span="20">
        <el-row>
          <el-col :span="8" class="tc border-r tc-header" >二级</el-col>
          <el-col :span="16">
            <el-row class="tc">
              <el-col :span="8" class="tc border-r tc-header">三级</el-col>
              <el-col :span="8" class="tc tc-header">功能</el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row class="border-b border-r" v-for="menu in menuData" :key="menu.id">
        <!--一级-->
        <el-col :span="4" class="tc tc-header">
          <el-checkbox v-if="menu.type !=0" v-model="menu.checked" @change="selectAllMenuChildren(menu)">{{menu.label}}</el-checkbox>
          <el-checkbox v-else v-model="menu.checked" @change="selectAllMenuChildren(menu)">{{menu.label}}</el-checkbox>
        </el-col>
        <!--二级-->
        <el-col :span="20" class="border-l">
          <el-row :class="{borderB: index != menu.children.length-1}" v-for="(item, index) in menu.children" :key="item.id" v-if="menu.children.length>0">
            <el-col :span="8" :class="{borderR:item.children.length<=0}" >
              <el-checkbox class="second-checkbox" v-if="item.type !=0" v-model="item.checked" @change="selectAllChildren(menu, item)">{{item.label}}</el-checkbox>
              <el-checkbox class="second-checkbox" v-else @change="selectAllChildren(menu, item)" v-model="item.checked">{{item.label}}</el-checkbox>
            </el-col>
            <el-col :span="16" class="border-l" v-if="item.children.length>0">
              <el-row :class="{borderB: icndex != item.children.length-1 && item.children.length>0 && ictem.type !=2}" v-if="ictem.type !=2" v-for="(ictem, icndex) in item.children" :key="ictem.id">
                <el-col :span="8" class="tc-header">
                  <el-checkbox v-if="ictem.type!=2" @change="selectAllThirdChildren(menu, item, ictem)" v-model="ictem.checked" :label="ictem.name" :key="ictem.id">{{ictem.label}}</el-checkbox>
                </el-col>
                <el-col :span="16" class="border-l">
                  <el-checkbox v-if="iitem.type==2" class="tc-header-btn" @change="selectOneT(menu, item, ictem, iitem)"  v-for="iitem in ictem.children" v-model="iitem.checked" :label="iitem.label" :key="iitem.id">{{iitem.label}}</el-checkbox>
                </el-col>
              </el-row>
              <el-row v-if="item.children[0].type ==2">
                <el-col :span="8" class="tc-header" ></el-col>
                <el-col :span="16" class="border-l" >
                  <el-checkbox v-for="(ictem, icndex) in item.children" v-if="ictem.type ==2" @change="selectOne(menu, item, ictem)" class="tc-header-btn" v-model="ictem.checked" :label="ictem.name" :key="ictem.id">{{ictem.label}}</el-checkbox>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="16" v-else></el-col>
          </el-row>
        </el-col>
      </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeRightBtn()">取 消</el-button>
      <el-button type="primary" @click="handleOkRight()">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script type="javascript">
  import {objDeepCopy} from "../../../utils";
import {
  page,
  addGroup,
  putGroup,
  delObj,
  putObj
} from 'api/admin/groupType/index';
import {
  fetchTree
} from 'api/admin/menu';
import {
  modifyMenuAndBtnAuthority,
  getMenuAuthority
} from 'api/admin/group/index'
import { mapGetters } from 'vuex';
export default {
  name: 'groupType',
  data() {
    return {
      form: {
        code: 'wuquanxian2',
        groupType: 1, // 1--运营平台；2--商家平台,
        name: undefined,
        description: undefined,
        parentId: -1
      },
      rightDialogVisible: false, // 权限设置弹窗
      rules: {
        code: [{
          required: true,
          message: '请输入编码',
          trigger: 'blur'
        }, {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入类型名称',
          trigger: 'blur'
        }, {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }],
        description: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }, {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }]
      },
      menuData: [], // 菜单列表
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      groupTypeManager_btn_edit: false,
      groupTypeManager_btn_del: false,
      groupTypeManager_btn_add: false,
      groupId: 0, // 角色id
      textMap: {
        update: '基础信息',
        create: '创建'
      },
      tableKey: 0
    }
  },
  created() {
    this.getList();
    this.groupTypeManager_btn_edit = this.elements['groupTypeManager:btn_edit'];
    this.groupTypeManager_btn_del = this.elements['groupTypeManager:btn_del'];
    this.groupTypeManager_btn_add = this.elements['groupTypeManager:btn_add'];
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    getList() {
      this.listLoading = true;
      page(this.listQuery).then(response => {
        this.list = response.data.data;
        this.total = response.data.totalCount;
        this.listLoading = false;
      })
    },
    /**
     * 一级菜单全选
     * */
    selectAllMenuChildren(menu) {
      if (menu.checked) {
        // 一级菜单全选
        menu.children.map(function(m){
          m.checked = !0;
          if(m.children.length>0){
            m.children.map(function(c) {
              c.checked = !0;
              if(c.children){
                c.children.map(function(iitem){
                  iitem.checked = !0;
                });
              }
            });
          }
        });
      } else {
        // 二级菜单取消全选
        menu.children.map(function(m){
          m.checked = !1;
          if(m.children.length>0){
            m.children.map(function(c) {
              c.checked = !1;
              if(c.children){
                c.children.map(function(iitem){
                  iitem.checked = !1;
                });
              }
            });
          }
        });
      }
      // wxAppMenu.map(function (ii) {
      //   if (ii.id == menu.id) {
      //     ii = firstMenu;
      //   }
      // })
      // menu = firstMenu;
    },
    /**
     * 二级菜单全选
     * */
    selectAllChildren(menu, item) {
      if (item.checked) {
        // 下级选中--上级选中
        menu.checked = !0;
      } else {
        let c = 0;
        for (let i = 0; i < menu.children.length; i++){
          if (menu.children[i].checked) {
            // 有一个选中--上级就选中
            menu.checked = !0;
          } else {
            c++;
          }
        }
        if (c == menu.children.length){
          // 全未选中
          menu.checked = !1;
        }
      }
      if (item.children.length > 0) {
        if (item.checked) {
          // 二级菜单全选
          item.children.map(function(m) {
            m.checked = !0; // 二级菜单选中，下面三级子菜单全选中
            if (m.children.length > 0) {
              m.children.map(function(ii) {
                ii.checked = !0;
              });
            }
          });
        } else {
          // 二级菜单取消全选
          item.children.map(function(m) {
            m.checked = !1; // 二级菜单取消选中，下面三级子菜单全取消选中
            if (m.children.length > 0) {
              m.children.map(function(ii) {
                ii.checked = !1;
              });
            }
          });
        }
      }
    },
    /**
     * 三级菜单全选
     */
    selectAllThirdChildren(menu, item, ictem) {
      if (ictem.checked) {
        // 下级选中--上级选中
        item.checked = !0;
        menu.checked = !0;
      } else {
        let c = 0;
        // 下级未选中--上级判断是否选中
        for (let i = 0; i< item.children.length; i++){
          if (item.children[i].checked){
            // 下级有一个选中
            item.checked = !0;
            break;
          } else {
            c++;
          }
        }
        if (c == item.children.length) {
          // 全未选中--上级不选中
          item.checked = !1;
          let mm = 0;
          // 判断二级是否有选中--有则一级选中，无则一级不选中
          for (let j = 0; j < menu.children.length; j++) {
            if (menu.children[j].checked) {
              menu.checked = !0;
              break;
            } else {
              mm++;
            }
          }
          if (mm == menu.children.length) {
            menu.checked = !1;
          }
        }
      }
      if (ictem.children.length > 0) {
        if (ictem.checked) {
          // 三级菜单全选
          ictem.children.map(function(m) {
            m.checked = !0; // 三级菜单选中，下面三级子菜单全选中
          });
        } else {
          // 三级菜单取消全选
          ictem.children.map(function(m) {
            m.checked = !1; // 三级菜单取消选中，下面三级子菜单全取消选中
          });
        }
      }
    },
    /**
     * 操作下级，上级菜单联动处理   二级菜单下按钮
     * */
    selectOne(menu, item, ictem) {
      if (ictem.checked) {
        // 下级选中--上级选中
        item.checked = !0;
        menu.checked = !0;
      }
    },
    /**
     * 三级菜单下按钮
     * */
    selectOneT(menu, item, ictem, iitem){
      if(iitem.checked){
        menu.checked = !0
        ictem.checked = !0;
        item.checked = !0;
      }
    },
    /**
     * 关闭权限弹框
     * */
    closeRightBtn() {
      this.groupId = 0
      this.rightDialogVisible = false;
    },
    /**
     * 计算选中的按钮权限
     */
    getCheckedBtn(){
      let wxAppMenu = objDeepCopy(this.menuData);
      let menuArr = [];
      wxAppMenu.map(function(menu) {
        if (menu.checked && menu.type ==2){
          menuArr.push(menu.id);
        } else if (menu.children) {
          menu.children.map(function(item) {
            if (item.checked && item.type ==2) {
              menuArr.push(item.id);
            }
            if (item.children) {
              item.children.map(function (iitem) {
                if (iitem.checked && iitem.type ==2) {
                  menuArr.push(iitem.id);
                }
                if (iitem.children) {
                  iitem.children.map(function (ictem) {
                    if (ictem.checked && ictem.type ==2) {
                      menuArr.push(ictem.id);
                    }
                  });
                }
              });
            }
          })
        }
      });
      return menuArr;
    },
    /**
     * 计算选中的权限
     * */
    getCheckedMenu() {
      let wxAppMenu = objDeepCopy(this.menuData);
      let menuArr = [];
      wxAppMenu.map(function(menu) {
        if (menu.checked && menu.type !=2){
          menuArr.push(menu.id);
        }
        if (menu.children.length > 0) {
          menu.children.map(function(item) {
            if (item.checked && item.type !=2) {
              menuArr.push(item.id);
              menuArr.push(menu.id);
            }
            if (item.children.length > 0) {
              item.children.map(function (iitem) {
                if (iitem.checked && iitem.type !=2) {
                  menuArr.push(iitem.id);
                  menuArr.push(item.id);
                  menuArr.push(menu.id);
                }
                if (iitem.children > 0) {
                  iitem.children.map(function (ictem) {
                    if (ictem.checked && ictem.type !=2) {
                      menuArr.push(ictem.id);
                    }
                  });
                }
              });
            }
          })
        }
      });
      return menuArr;
    },
    /**
     * 数组去重
     */
    unique1(arr){
      var hash=[];
      for (var i = 0; i < arr.length; i++) {
        if(hash.indexOf(arr[i]) == -1){
          hash.push(arr[i]);
        }
      }
      return hash;
    },
    /**
     * 保存权限设置
     */
    handleOkRight() {
      let menu = objDeepCopy(this.getCheckedMenu());
      menu = this.unique1(menu)
      let elements = objDeepCopy(this.getCheckedBtn());
      console.log(menu);
      console.log(elements)
      modifyMenuAndBtnAuthority(this.groupId, {
        menuTrees: menu.join(','),
        elementTrees: elements.join(',')
      }).then( (response) => {
        if (response.status == 200) {
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          });
          this.rightDialogVisible = false
        } else {
          this.$notify({
            title: '失败',
            message: response.message,
            type: 'error',
            duration: 2000
          });
        }
      });
    },
    handleFilter() {
      this.getList();
    },
    cleanFilter(){
      this.listQuery = {
        page: 1,
        limit: 20,
        name: undefined
      }
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate(groupType) {
      this.form = {
        code: 'wuquanxian2',
        groupType: groupType, // 1--运营平台；2--商家平台,
        name: undefined,
        description: undefined,
        parentId: -1
      }
      // this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
    },
    /**
     * 基础信息--编辑按钮
     */
    handleUpdate(row) {
      this.form = {
        code: 'wuquanxian2',
        id: row.id,
        groupType: row.groupType, // 1--运营平台；2--商家平台,
        name: row.name,
        description: row.description,
        parentId: -1
      }
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
    },
    /**
     * 设置权限
     */
    setRights(row) {
      this.rightDialogVisible = true
      this.groupId = row.id
      fetchTree().then(response => {
        response.map(function(item){
          item.checked = false
          if(item.elements.length>0){
            item.type = 1 // 菜单
            item.elements.map(function(ittem){
              ittem.checked = false
              ittem.label = ittem.name
              ittem.type = 2 // button
            })
            item.children = item.elements
          } else if(item.children.length>0){
            item.type = 0 // 目录  一级菜单
            item.children.map(function(iitem){
              iitem.checked = false
              if(iitem.elements.length > 0){
                iitem.children = iitem.elements
                iitem.type = 1 // 菜单   二级菜单
                iitem.elements.map(function(ittem){
                  ittem.checked = false
                  ittem.label = ittem.name
                  ittem.type = 2 // button
                })
              } else if(iitem.children.length>0){
                iitem.type = 0 // 目录  二级目录
                iitem.children.map(function(ictem){
                  ictem.checked = false
                  if(ictem.elements.length > 0){
                    ictem.type = 1 // 三级菜单
                    ictem.children = ictem.elements
                    ictem.elements.map(function(ittem){
                      ittem.checked = false
                      ittem.label = ittem.name
                      ittem.type = 2 // button
                    })
                  }
                })
              }
            })
          }
        })
        console.log(response)
        this.menuData = response;
        this.getCurrentRoleMenu()
        this.loading = false;
      });
    },
    /**
     * 获取当前角色菜单权限
     */
    getCurrentRoleMenu(){
      let _this = this
      getMenuAuthority(this.groupId).then( (response) => {
        if (response.status == 200) {
          if(response.data.length > 0){
            let arr =  response.data[0].elementIds ? response.data[0].elementIds : [];
            let totalIds = []
            arr.map(function(item){
              totalIds.push({id: item})
            })
            response.data.map(function(item){
              totalIds.push({id: item.id})
            })
            for(let i = 0; i < totalIds.length; i++){
              let obj1 = totalIds[i]
              for(let j = 0; j < _this.menuData.length; j++){
                let obj2 = _this.menuData[j]
                if(obj1.id == obj2.id){
                  obj2.checked = true
                  break
                }
                if(obj2.children.length > 0){
                  for(let j1 = 0; j1 < obj2.children.length; j1++){
                    let obj3 = obj2.children[j1]
                    if(obj3.id == obj1.id){
                      obj3.checked = true
                      break
                    }
                    if(obj3.children.length > 0){
                      for(let j2 = 0; j2 < obj3.children.length; j2++){
                        let obj4 = obj3.children[j2]
                        if(obj4.id == obj1.id){
                          obj4.checked = true
                          break
                        }
                        console.log(obj4)
                        if(obj4.children){
                          // 按钮权限
                          for(let j3 = 0; j3 < obj4.children.length; j3++){
                            let obj5 = obj4.children[j3]
                            if(obj5.id == obj1.id){
                              obj5.checked = true
                              break
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        } else {
          this.$notify({
            title: '失败',
            message: response.message,
            type: 'error',
            duration: 2000
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
          const index = this.list.indexOf(row);
          this.list.splice(index, 1);
        });
      });
    },
    create(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addGroup(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            });
          })
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    /**
     * 基础信息--编辑
     * @param formName
     */
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          putGroup(this.form.id ,this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    resetTemp() {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        password: undefined,
        description: undefined
      };
    }
  }
}
</script>
<style>
  .rights-main .el-dialog__body{
    height: 500px;
    overflow: auto;
  }
  .table-row-header{
    background: #f1f2f2;
  }
  .border-r, .borderR{
    border-right: 1px solid #e9e9e9;
  }
  .borderR{
    /*width: 201px !important;*/
  }
  .border-b, .borderB{
    border-bottom: 1px solid #e9e9e9;
  }
  .border-l{
    border-left: 1px solid #e9e9e9;
  }
  .tc{
    text-align: center;
  }
  .tc-header, .second-checkbox{
    padding: 10px;
  }
  .tc-header-btn{
    padding: 10px;
    margin: 0;
  }
</style>
