<template>
  <div class="admin-role">
    <el-form :inline="true">
      <el-form-item v-if="$permission('/admin/role/check')">
        <el-input v-model="queryParams.name" size="small" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item class="tenant" v-if="userinfo.rList?(userinfo.rList.filter(item=>item.roleId==1))[0]:''">
        <el-select v-model="queryParams.tenant" @change="getList2" clearable placeholder="根据租户查询">
          <el-option
              v-for="item in tenantList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="" size="small" @click="getList2" v-if="$permission('/admin/role/check')">查询</el-button>
        <el-button type="primary" size="small" @click="handleAdd()" v-if="$permission('/admin/role/add')">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        header-row-class-name="custom-table-header"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="角色名称" align="" show-overflow-tooltip>

      </el-table-column>
      <el-table-column label="功能权限" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="item in scope.row.permissionData" :key="item.id">{{ item.functionName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="数据权限" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="item in scope.row.dataList" :key="item.id">{{ item.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="tenantName" label="所属租户" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-dropdown split-button type="primary" size="small">
            <p v-if="$permission('/admin/role/modify')" @click="handleEdit(scope.row)">编辑</p>
            <p v-else :disabled="true">编辑</p>
            <el-dropdown-menu slot="dropdown" class="text-align_center">
              <!-- <el-dropdown-item @click.native="handleAdd(scope.row.id)">新增</el-dropdown-item> -->
              <el-dropdown-item class="color-red" @click.native="handleDelete(scope.row)" divided
                                v-if="$permission('/admin/role/delete')">删除
              </el-dropdown-item>
              <el-dropdown-item @click.native="distributionPersonnel(scope.row)" divided>分配人员
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total"
                     @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper"
                     background></el-pagination>
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="visible" width="1100px" max-height="800" :before-close="close">
      <div style="height: 500px">
        <el-form v-if="visible" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px"
                 label-position="left">
          <el-form-item label="所属租户" prop="tenant">
            <el-select style="width:100%" v-model="ruleForm.tenant"
                       :disabled="(userinfo.rList?!(userinfo.rList.filter(item=>item.roleId==1))[0]:'')||disabled"
                       placeholder="请选择">
              <el-option
                  v-for="item in tenantList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="function">
            <el-table
                :row-key="functionList.id"
                :data="functionList"
                v-loading="loading"
                max-height="330"
            >
              <el-table-column type="expand">
                <template style="width:80%;" slot-scope="scope">
                  <div>
                    <el-table
                        border
                        :data="scope.row.children"
                        row-key="id"
                        ref="multiTable"

                        @selection-change="handleSelectionChange"
                    >

                      <el-table-column label="功能名称" align="left" prop="name">
                        <template slot-scope="scope">
                          <el-checkbox-group v-model="checkList" style="display:inline-block"
                                             @change="handleCheckedCitiesChange(scope.row)">
                            <el-checkbox :label="scope.row.id" @change="getFunInfo(scope.row.id)"
                            >
                              {{ scope.row.name }}
                            </el-checkbox>
                          </el-checkbox-group>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                          <span v-if="checkList.filter(item=>item==scope.row.id)[0]">
                            <span
                                v-if="(permissionData.filter(item=>item.functionId == scope.row.id))[0]">{{
                                (permissionData.filter(item => item.functionId == scope.row.id))[0].data.name
                              }}</span>
                            <span class="hov" style="margin-left: 10px" :underline="false"
                                  v-if="(permissionData.filter(item=>item.functionId == scope.row.id))[0].data.id"
                                  @click="editpremissVisibale(scope.row,(permissionData.filter(item=>item.functionId == scope.row.id))[0].data)">修改</span>
                            <span class="hov" style="margin-left:10px" :underline="false"
                                  v-else-if="checkList.filter(item=>item==scope.row.id)[0]"
                                  @click="addpremissVisibale(scope.row)">添加</span>
                          </span>


                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="应用名称" align="left">
                <template slot-scope="scope">
                  <span>{{ scope.row.name }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea" maxlength="100"
                      show-word-limit></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增中选中功能后的添加弹窗 -->
    <el-dialog :title="permissTitle" :visible.sync="permissVisible" width="1100px" :before-close="premissClose"
               custom-class="permiss">
      <div style="height: 500px;">
        <DataPermission
            :fun="fun"
            @getPremissData="getPremissData"
        >
        </DataPermission>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="premissClose">取 消</el-button>
        <el-button type="primary" @click="premissSubmit" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer
        title="分配人员"
        :visible.sync="drawer"
        direction="rtl"
        append-to-body
        destroy-on-close
        size="900px">
      <el-container class="project-form">
        <el-main class="project-form-main">

          <el-form label-width="98px" label-position="left">
            <el-form-item label="角色名称">
              <el-input v-model="distributionParam.roleName" placeholder="请输入专题库名称" :disabled="true"></el-input>
            </el-form-item>
            
            <el-row>
              <el-col :span="12">
                <el-form-item label="人员名称">
                  <el-input placeholder="请输入人员名称" v-model="personnel.name" @change="getPerList" style="width: 217.5px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="租户名称" style="margin-left: 16.2%">
                  <el-select v-model="personnel.tenant" :disabled="(userinfo.rList?!(userinfo.rList.filter(item=>item.roleId==1))[0]:'')||disabled" @change="getPerList" clearable placeholder="根据租户查询">
                    <el-option
                        v-for="item in tenantList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="部门名称">
                  <el-cascader
                    placeholder="请选择部门"
                    :options="department"
                    v-model="name"
                    :props="{value:'id',label:'name',multiple:true,checkStrictly: true}"
                    @change="getPerList()"
                  >
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位名称" style="margin-left: 16.2%">
                  <el-select
                    filterable
                    multiple
                    v-model="personnel.positionIds"
                    placeholder="请选择职位"
                    @change="getPerList()"
                  >
                    <el-option
                      v-for="item in positionList"
                      :key="item.name"
                      :label="item.position"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            
          </el-form>

          <el-table v-loading="load" :data="personnelTableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="人员名称" prop="name" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="所属角色" prop="name" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="item in scope.row.roleList">{{ item.name }},
                </span>
              </template>
            </el-table-column>
            <el-table-column label="所属部门" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="item in scope.row.positions">{{ item.departmentName }},
                </span>
              </template>
            </el-table-column>
            <el-table-column label="所属职位" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="item in scope.row.positions">{{ item.positionName }},
                </span>
              </template>
            </el-table-column>
            <el-table-column label="所属租户" prop="tenantName" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip></el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination :current-page.sync="personnel.current" :page-size="personnel.size" :total="personnelTotal"
                           @current-change="getPerList" layout="total, prev, pager, next, jumper"
                           background></el-pagination>
          </div>
        </el-main>
        <el-footer class="footer-common">
          <el-button @click="addRolePersonnelBatch" type="primary" :loading="loading">确 定</el-button>
          <el-button @click="closeDrawer">取 消</el-button>
        </el-footer>
      </el-container>
    </el-drawer>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import DataPermission from '../dataPermission'

export default {
  components: {
    Treeselect,
    DataPermission
  },
  data() {
    return {
      distributionParam: {},
      drawer: false,
      direction: 'rtl',
      labelPosition: 'right',
      personnelTableData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      fun: [],
      functionName: '',
      functionInfo: [],
      pdata: '',
      permissionData: [],
      checkList: [],
      checked: true,
      visible: false,
      loading: false,
      load: false,
      btnLoading: false,
      permissVisible: false,
      total: 0,
      personnelTotal: 0,
      tableData: [],
      tenantList: [],
      title: '',
      permissTitle: '',
      showDataList: false,
      functionList: [],
      dataList: [],
      multipleSelection: [],
      expands: [],
      disabled: false,
      department: [],
      name: [],
      positionList: [],
      position:{
        positionIds: [],
      },
      queryParams: {
        size: 10,
        current: 1,
        name: ''
      },
      personnel: {
        size: 10,
        current: 1,
        name: '',
      },
      ruleForm: {
        function: []
      },
      rules: {
        name: [{required: true, message: '请输入角色名称', trigger: 'blur'},],
        tenant: [{required: true, message: "请选择", trigger: "change"}],
      },
    }
  },
  mounted() {
    this.getList()
    var a = ''
    this.getFunctionList(a)
    this.getTenantList()
  },
  computed: {
    userinfo() {
      return this.$store.state.admin.userinfo
    }
  },
  // watch:{
  //   "ruleForm.function"(val){
  //     if(val.length!=0){
  //       this.showDataList=true
  //     }else{
  //       this.showDataList=false
  //     }
  //   }
  // },
  methods: {
    // getCheckedNodes()

    // a() {
    //   console.log(this.personnel.position)

    // },
    // b() {
    //   console.log(this.name)
    //   this.personnel.departmentIds=[]
    //   this.name.forEach(item => {
    //     this.personnel.departmentIds.push(item[item.length-1])
    //   })
    // },
    getPremissData(id, name, data) {
      // console.log(id, name, data)
      this.pdata = {
        functionId: id,
        data: data
      }
      // console.log(this.pdata)
    },
    premissSubmit() {
      if (this.permissionData.filter(item => item.functionId == this.pdata.functionId)[0]) {
        // console.log(this.pdata.data)
        if (this.pdata.data) {
          this.permissionData.filter(item => item.functionId == this.pdata.functionId)[0].data = this.pdata.data
        } else {
          //  console.log(this.permissionData)
          //   var index = this.permissionData.findIndex((item) => {
          //       return item.functionId == this.pdata.functionId;
          //     });
          //     // console.log(index)
          // this.permissionData.splice(index,1)
          this.permissionData.filter(item => item.functionId == this.pdata.functionId)[0].data = {}
        }

      } else {
        if (this.pdata.data) {
          this.permissionData.push(this.pdata)
        }

      }

      this.permissVisible = false
    },
    getFunInfo(val) {
      if (!this.checkList.includes(val)) {
        var index = this.permissionData.findIndex((item) => {
          return item.functionId == val;
        });
        if (index != -1) {
          this.permissionData.splice(index, 1)
        }
      } else {
        this.permissionData.push({
          functionId: val,
          data: {}
        })
      }
    },
    handleCheckedCitiesChange(value) {
      // console.log(value,this.checkList.includes(71),this.checkList.includes(value.id))

      if (this.checkList.includes(value.id)) {
        // console.log(value.hasOwnProperty('children'))
        if (value.hasOwnProperty('children') == true) {
          this.addCheck(value.children)
        }
        if (value.path !== 0) {
          var aa = value.path.split(",")
          aa.splice(0, 1)
          // console.log(aa)
          for (var j = 0; j < aa.length; j++) {
            // console.log(Number(aa[j]))
            // console.log(this.checkList.indexOf(Number(aa[j])))
            if (this.checkList.indexOf(Number(aa[j])) > -1) {

            } else {
              this.checkList.push(Number(aa[j]))
              this.getFunInfo(Number(aa[j]))
            }
            // this.checkList.push(Number(aa[j]))
            // this.getFunInfo(Number(aa[j]))
          }
        }

      } else if (!this.checkList.includes(value.id)) {
        // console.log(this.checkList.includes(value.id),value.id)
        if (value.hasOwnProperty('children') == true) {
          this.delCheck(value.children)
        }
      }

      // console.log(this.checkList,this.permissionData)
      // this.checkList
    },
    delCheck(vals) {
      for (var i = 0; i < vals.length; i++) {
        this.checkList.splice(this.checkList.indexOf(vals[i].id), 1)
        this.getFunInfo(vals[i].id)
        if (vals[i].hasOwnProperty('children') == true) {
          this.delCheck(vals[i].children)
        }
      }
    },
    addCheck(vals) {
      //  console.log(vals)
      for (var i = 0; i < vals.length; i++) {
        // console.log(this.checkList.indexOf(vals[i].id))
        if (this.checkList.indexOf(vals[i].id) > -1) {

        } else {
          this.checkList.push(vals[i].id)
          this.getFunInfo(vals[i].id)
        }

        if (vals[i].hasOwnProperty('children') == true) {
          this.addCheck(vals[i].children)
        }
      }

    },
    handleSelectionChange(val) {
      // console.log(val,this.$refs.multipleTable.selection)
      this.multipleSelection = val;
      // console.log(val)
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
      }
    },
    handleAdd() {
      this.title = '新增角色'
      this.visible = true
      this.checkList = []
      this.ruleForm = {
        tenant: this.userinfo.tenantId,
        function: []
      }
      this.disabled = false
    },
    handleEdit(row) {
      // console.log(row)
      this.disabled = true
      this.title = '编辑角色'
      this.visible = true
      this.ruleForm = {...row}
      for (let i = 0; i < row.permissionData.length; i++) {
        this.checkList.push(row.permissionData[i].functionId)
      }
      this.permissionData = row.permissionData
      if ((this.userinfo.rList.filter(item => item.roleId == 1))[0]) {
        this.getFunctionList(row.tenant)
      }
    },
    addpremissVisibale(val) {
      this.permissTitle = '添加数据权限管理'
      this.permissVisible = true
      this.fun = {fun: val}
    },
    editpremissVisibale(val, permission) {
      this.permissTitle = '修改数据权限管理'
      this.permissVisible = true
      this.fun = {fun: val, permission: permission}
    },
    close() {
      this.visible = false
      this.permissionData = []
      this.checkList = []
      this.getList()
    },

    premissClose() {
      this.permissVisible = false
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },

    getFunctionList(tenant) {
      this.$api.getFuncListByTypeIsShow({tenant: tenant}).then(response => {
        this.functionList = response.data
      })
    },
    getTenantList() {
      this.$api.getAllTenantList().then(response => {
        this.tenantList = response.data
      })
    },
    //根据条件查询
    getList2() {
      this.queryParams.current = 1
      this.getList()
    },
    getList() {
      this.loading = true
      this.$api.getRoleList(this.queryParams).then(response => {
        this.tableData = response.data
        // console.log(response.data)
        this.total = response.pageColumn.total
        this.loading = false
      }).catch(error => {
        this.loading = false
      })
    },
    getclient() {
      this.$api.getAllDepartmentList().then(response => {
        this.department = response.data
        // console.log(this.department)
      })
    },
    getPositionList() {
      this.$api.getAllPositionList().then(response => {
        this.positionList = response.data
        // console.log(this.positionList)
      })
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // this.ruleForm.functions=[]
          this.ruleForm.permissionData = this.permissionData
          this.btnLoading = true
          if (this.ruleForm.id) {
            this.$api.editRole(this.ruleForm).then(response => {
              this.$message.success('编辑成功')
              this.btnLoading = false
              this.getList()
              this.close()
            }).catch(error => {
              this.btnLoading = false
            })
          } else {

            this.$api.addRole(this.ruleForm).then(response => {
              this.$message.success('新增成功')
              this.btnLoading = false
              this.getList()
              this.close()
            }).catch(error => {
              this.btnLoading = false
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteRole({id: row.id}).then(response => {
          this.$message.success('删除成功')
          this.loading = false
          this.getList()
        }).catch(error => {
          this.loading = false
        })
      })
    },
    getPerList() {
      this.load = true
      this.personnel.departmentIds=[]
      this.name.forEach(item => {
        this.personnel.departmentIds.push(item[item.length-1])
      })
      this.$api.getPersonnelList(this.personnel).then(response => {
        this.personnelTableData = response.data
        // console.log(response)
        this.personnelTotal = response.pageColumn.total
        this.load = false
      }).catch(error => {
        this.load = false
      })
    },
    // getPerListCheck() {
    //   this.load = true
    //   // this.personnel.positionIds = []
    //   // console.log(this.position.positionIds)
    //   // this.position.positionIds.forEach(item => {
    //   //   // console.log(item)
    //   //   this.personnel.positionIds .push(item)
    //   // })
    //   this.$api.getPersonnelList(this.personnel).then(response => {
    //     this.personnelTableData = response.data
    //     this.personnelTotal = response.pageColumn.total
    //     this.load = false
    //   }).catch(error => {
    //     this.load = false
    //   })
    // },
    distributionPersonnel(row) {
      this.drawer = true
      this.distributionParam.roleName = row.name
      this.distributionParam.description = row.remark
      this.distributionParam.id = row.id
      // console.log(this.distributionParam)
      this.getPerList()
      this.getclient()
      this.getPositionList()
    },
    closeDrawer() {
      this.drawer = false
      this.multipleSelection = ''
      // console.log(this.distributionParam)
      // console.log(this.multipleSelection)
    },
    addRolePersonnelBatch() {
      this.distributionParam.personnelIds = []
      this.multipleSelection.forEach(item => {
        this.distributionParam.personnelIds.push(item.id)
      })
      // console.log(this.distributionParam)
      this.$api.addRolePersonnelBatch(this.distributionParam).then(response => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.admin-role {

}

.permiss {
  height: 2000px;
}

.hov {
  margin: auto 10px;
  cursor: pointer;
}

.hov:hover {
  color: #409EFF;
}

.project-form {
  .project-form-main {
    background: #fff;
    padding: 20px;
  }
}
</style>