<template>
  <d2-container>
	<div class="d2-table-view-full">
	  <div class="d2-table-view-header"></div>
	  <div class="d2-table-view-content">
    <div class="d2-table-view-handle">
					<el-button   @click="operVisible = !operVisible" size="small" icon="el-icon-plus" slot="headerButton">新增角色</el-button>
				</div>
		<d2-crud
				title="角色列表"
				ref="d2Crud"
				:options="tableOptions"
				:loading="loading"
				:columns="columns"
				:data="data"
				:rowHandle="rowHandle"
				@menu="handleMenu"
				@func="handleFunc"
				@edit="handleRowEdit"
				@delete="handleRowRemove">
		  
		  <!--<el-button @click="exportOperation" size="small" type="success" icon="el-icon-download" slot="headerButton">导出</el-button>-->
		</d2-crud>
	  </div>
	  <div class="d2-table-view-footer">
		<el-pagination
						@current-change="handleCurrentChange"
						@size-change="handleSizeChange"
						:current-page.sync="currentPage"
						:page-size="tableOptions.pageList[0]"
						:page-sizes="tableOptions.pageList"
						layout="total,sizes, prev, pager, next,jumper"
						:total="pagination.total">
		</el-pagination>
	  </div>
	</div>
	<el-dialog
			:title="diaLogName"
			:visible.sync="operVisible"
			@close="clearForm"
			width="50%"
			:close-on-click-modal="false">
	  <el-form ref="roleForm" :model="form" :rules="rulesForm"  label-width="80px" labelPosition="right">
		<el-row :gutter="20">
		  <el-col :span="12">
			<el-form-item label="角色代码" prop="roleCode">
			  <el-input maxlength="10" :disabled="form.roleId?true:false" v-model="form.roleCode"/>
			</el-form-item>
		  </el-col>
		  <el-col :span="12">
			<el-form-item label="角色名称" prop="roleNm">
			  <el-input maxlength="20" v-model="form.roleNm"/>
			</el-form-item>
		  </el-col>
		  <el-col :span="12">
			<el-form-item label="角色序号">
			  <el-input disabled placeholder="系统自动生成" v-model="form.seq"/>
			</el-form-item>
		  </el-col>
		  <el-col :span="24">
			<el-form-item label="角色描述">
			  <el-input type="textarea" maxlength="50" v-model="form.rmk"/>
			</el-form-item>
		  </el-col>
		</el-row>
	  </el-form>
	  <span slot="footer" class="dialog-footer">
    <el-button :loading="roleLoading" @click="operInstance()">确 定</el-button>
  </span>
	</el-dialog>
	<el-dialog
			title="设置菜单"
			:visible.sync="menuVisible"
			width="30%"
			@close="clear"
			:close-on-click-modal="false">
	  <el-tree
			  style="height: 400px;overflow: auto"
			  :props="defaultProps"
			  :default-expanded-keys="['M000']"
			  node-key="id"
			  :data="menuTree"
			  ref="menuTree"
			  show-checkbox>
	  </el-tree>
	  <span slot="footer" class="dialog-footer">
    <el-button :loading="roleLoading" @click="menuTreeSave()">确 定</el-button>
  </span>
	</el-dialog>
	<el-dialog
			title="设置功能"
			:visible.sync="funcVisible"
			width="30%"
			@close="clear"
			:close-on-click-modal="false">
	  <el-tree
			  style="height: 400px;overflow: auto"
			  :props="defaultProps"
			  :default-expanded-keys="['M000']"
			  node-key="id"
			  :data="funcTree"
			  ref="funcTree"
			  show-checkbox>
	  </el-tree>
	  <span slot="footer" class="dialog-footer">
    <el-button :loading="roleLoading" @click="funcTreeSave()">确 定</el-button>
  </span>
	</el-dialog>
  </d2-container>
</template>

<script>
  import {
    RoleList,
    RoleSaveUpdate,
    RoleDelete,
    RoleSaveMenuTree,
    RoleGetMenuTree,
    RoleGetFuncTree,
    RoleSaveFuncTree
  } from '../../../api/per/role'
  import { tableOptions } from '../../../assets/options'

  export default {
    name: 'permission-role',
    data () {
      return {
				roleLoading:false,
				func:{
					addRole:false,
					updateRole:false,
					deleteRole:false,
					SetupMenu:false,
					SetupF:false
				},
        tableOptions,
        loading: false,
        currentPage:1,
        operVisible: false,
        menuVisible: false,
        funcVisible: false,
        isEdit: false,
        currentRoleId: '',
        diaLogName: '新增',
        form: {
          roleCode: '',
          roleNm: '',
          roleId: '',
          seq: '',
          rmk: '',
        },
        filter: {
          pageSize: 10,
          pageNum: 1
        },
        pagination: {
          total: 0
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        columns: [
          {
            title: '序号',
            key: 'index',
            minWidth: '150',
            formatter (row, column, cellValue, index) {
              return index + 1
            }
          },
          {
            title: '角色编码',
            key: 'roleCode',
            minWidth: '150'
          },
          {
            title: '角色名称',
            key: 'roleNm',
            minWidth: '150'
          },
				/* 	{
					  title: '公司名称',
					  key: 'orgName',
					  minWidth: '150',
						showOverflowTooltip: true
					}, */
          {
            title: '角色描述',
            key: 'rmk',
            minWidth: '150'
          },
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '500',
          align: 'center',
          custom: [
            {
              text: '编辑',
              type: 'primary',
              size: 'small',
              emit: 'edit'
            },
            {
              text: '删除',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            },
            {
              text: '设置菜单',
              type: 'success',
              size: 'small',
              emit: 'menu'
            },
            {
              text: '设置功能',
              type: 'success',
              size: 'small',
              emit: 'func'
            },
          ],

        },
        data: [],
        rulesForm: {
          roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
          roleNm: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        },
        menuTree: [{
          title:'请稍候',
		  value:-1
		}],
        menuCheckNode: [],
        funcTree: [
          {
            title:'请稍候',
            value:-1
          }
		],
        funcCheckNode: []
      }
    },
		watch: {
			'form.roleCode':function(val){
				 this.roleLoading=false
			}
		},
    methods: {
      handleNodeClick (data, node, com) {

      },
      handleList (val) {
        if(val){this.filter.pageNum=1
        this.currentPage = 1}
      this.loading = true
       RoleList(this.filter).then(res => {
          this.loading = false
          this.data = res.list.list
          this.pagination.total = res.data.records
        }).catch(err => {
          this.loading = false
        })
      },

      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },
			handleSizeChange (val) {
			this.filter.pageNum = 1
			this.filter.pageSize = val
			this.handleList()
			},
      operInstance () {
        // this.form.orgId = this.filter.orgId
       this.$refs.roleForm.validate((valid) => {
            if (valid) {
							this.roleLoading=true
              RoleSaveUpdate(this.form).then(res => {
								this.roleLoading=false
                this.operVisible = false
                this.$message({
                  message: this.form.roleId ? '编辑成功' : '新增成功',
                  type: 'success'
                })
                this.handleList()
              }).catch(err => {
          this.roleLoading=false
        })
            }
        })

      },
      handleRowEdit ({index, row}) {
        this.isEdit = true
        this.diaLogName = '编辑'
        this.form = row
        this.operVisible = true
      },
      handleRowRemove ({index, row}) {
       this.$confirm(`确定要删除吗?`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          let roleId = row.roleId
          RoleDelete({
            roleId
          }).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.handleList()
          })
        })

      },
      handleMenu ({index, row}) {
        this.menuVisible = true
        this.currentRoleId = row.roleId
        RoleGetMenuTree({
          roleId: this.currentRoleId
        }).then(res => {
          // console.log(res)
          this.menuTree = JSON.parse(res.msgDat)
          this.menuCheckNode = []
          this.menuTreeTraverse(this.menuTree[0])
          // console.log(this.menuCheckNode)
          this.$refs.menuTree.setCheckedKeys(this.menuCheckNode)
        })
      },
      //树遍历找出checked为true的key
      menuTreeTraverse (node) {
        if (!node) {return}
        if (node.checked) {
          this.menuCheckNode.push(node.id)
        }
				if(node.children){
					 node.children.forEach((item) => {
					  this.menuTreeTraverse(item)
					})
				}
      },

      menuTreeSave () {
        // console.log(this.$refs.menuTree.getCheckedKeys())
        // console.log(this.$refs.menuTree.getHalfCheckedKeys())
		
		let menuIds = this.$refs.menuTree.getCheckedKeys().map(item => item).join(',') + ',' + this.$refs.menuTree.getHalfCheckedKeys().map(item => item).join(',')
		// console.log(menuIds)
		this.roleLoading=true
        RoleSaveMenuTree({
          menuIds,
          roleId: this.currentRoleId
        }).then(res => {
          this.menuVisible = false
					this.roleLoading=false
          this.$message({
            message: '菜单设置成功',
            type: 'success'
          })
        }).catch(err => {
          this.roleLoading=true
        })
      },
      handleFunc ({index, row}) {
        this.funcVisible = true
        this.currentRoleId = row.roleId

        RoleGetFuncTree({
          roleId: this.currentRoleId
        }).then(res => {
          // console.log(res)
          this.funcTree = JSON.parse(res.msgDat)
          this.funcCheckNode = []
          this.funcTreeTraverse(this.funcTree[0])
          // console.log(this.menuCheckNode)
          this.$refs.funcTree.setCheckedKeys(this.funcCheckNode)
        })
      },
      funcTreeTraverse (node) {
        if (!node) {return}
        if (node.checked) {
          this.funcCheckNode.push(node.id)
        }
				if(node.children){
					node.children.forEach((item) => {
					  this.funcTreeTraverse(item)
					})
				}
      },

      funcTreeSave () {
				console.log(this.$refs.funcTree.getCheckedKeys())
				this.roleLoading=true
				RoleSaveFuncTree({
				  functionIds: this.$refs.funcTree.getCheckedKeys().map(item => item).join(','),
				  roleId: this.currentRoleId
				}).then(res => {
				  this.funcVisible = false
					this.roleLoading=false
				  this.$message({
				    message: '功能设置成功',
				    type: 'success'
				  })
				}).catch(err => {
				  this.roleLoading=true
				})
      },
      clearForm () {
				 this.roleLoading=false
        this.form = {
          roleCode: '',
          roleNm: '',
          roleId: '',
          seq: '',
          rmk: '',
        }
        this.isEdit = false
        this.diaLogName = '新增'
      },
			clear(){
				this.roleLoading=false
			},
			/* getFunction () {
			  this.$GetFunction({
			    menuUrl:this.$route.path
			  }).then(res=>{
			    res.data.forEach(item=>{
			      if (item.functionType === 'addRole') {
			        if (item.remarks === 'true') {
			          this.func.addRole = true
			        } else {
			          this.func.addRole = false
			        }
			      } else if(item.functionType === 'updateRole') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,0,
			            {
			              text: '编辑',
			              type: 'primary',
			              size: 'small',
			              emit: 'edit'
			            },
			          )
			
			        }
			      }else if(item.functionType === 'deleteRole') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,1,
			            {
			              text: '删除',
			              type: 'danger',
			              size: 'small',
			              emit: 'delete'
			            }
			          )
			        }
			      }else if(item.functionType === 'SetupMenu') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,2,
			            {
			            text: '设置菜单',
			            type: 'success',
			            size: 'small',
			            emit: 'menu'
			           },
			          )
			        }
			      }else if(item.functionType === 'SetupF') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,3,
			            {
			              text: '设置功能',
			              type: 'success',
			              size: 'small',
			              emit: 'func'
			            },
			          )
			        }
			      }
			    })
			  })
			} */
    },
    mounted () {
			//this.getFunction ()
			this.filter.pageSize = this.tableOptions.pageList[0]
      this.tableOptions = this.$calcTableHeight(tableOptions,0)
      this.handleList()
    }
  }
</script>
