<template>
  <div>
  <div class="app-container" style="margin-bottom: 20px;border-radius: 10px;">
    <el-button 
      type="primary" 
      plain 
      icon="Plus" 
      @click="showpop(1)"
    >新增</el-button>
    <el-table
      :data="dictlist"
      style="width: 100%;margin-top: 10px;"
      border
      stripe
      highlight-current-row
      row-key="id"
      max-height="600px"
    >
      <el-table-column label="角色类型" align="center" prop="type">
        <template #default="scope">
          <div v-if="scope.row.type == 1">开发者</div>
          <div v-else-if="scope.row.type == 2">运营方</div>
          <div v-else>客户</div>
        </template> 
      </el-table-column>
      <el-table-column label="角色名称" align="center" prop="name" />
      <el-table-column label="角色编码" align="center" prop="rcode" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <div v-if="scope.row.status == 1">启用</div>
          <div v-else>禁用</div>
        </template>
      </el-table-column>
      <el-table-column label="是否内置角色" align="center" prop="readonly">
        <template #default="scope">
          <div v-if="scope.row.readonly == 1">是</div>
          <div v-else>否</div>
        </template>
      </el-table-column>
      <el-table-column label="功能描述" align="center" prop="mark" />
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <el-button v-if="scope.row.readonly != 1" link type="primary" icon="CircleCheck" @click="fenpqx(scope.row)">分配权限</el-button>
          <el-button v-if="scope.row.readonly != 1" link type="primary" icon="Edit" @click="showpop(2,scope.row)">修改</el-button>
          <el-button v-if="scope.row.readonly != 1" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
   
    
  </div>
    <!--:row-style="{background: '#cde0f3'}"-->
    
    <!--添加字典类型-->
    <el-dialog 
      v-model="popshow" 
      :title="poptit" 
      width="500px" 
      append-to-body
      align-center
    >
      <el-form ref="typeform" :model="addObj" :rules="rules" label-width="120px">
        <el-form-item label="角色类型" prop="type">
          <el-radio-group v-model="addObj.type">
            <el-radio :value="1">开发者</el-radio>
            <el-radio :value="2">运营方</el-radio>
            <el-radio :value="3">客户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addObj.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="rcode">
          <el-input v-model="addObj.rcode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addObj.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内置角色" prop="readonly">
          <el-radio-group v-model="addObj.readonly">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="功能描述" prop="mark">
          <el-input v-model="addObj.mark" placeholder="请输入功能描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="save">确 定</el-button>
          <el-button @click="canceltype">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
        v-model="treedrawer"
        title="分配权限"
        size="1200"
        :before-close="handleClose"
      >
      <el-row style="padding-left: 20px;">
        <el-col :span="10" style="margin-right: 50px;padding: 20px;box-shadow: 0 0 10px 2px rgba(193, 193, 193, 0.5);border-radius: 10px;">
          <div style="padding-bottom: 10px;font-size: 20px;border-bottom: 1px solid #ccc;">菜单分配</div>
          <div style="display: flex;justify-content: space-between;padding: 10px 0;">
            <div>{{roleName}}</div>
            <el-button 
            type="primary" 
            plain
            size="small"
            @click="addquanx"
          >保存</el-button>
          </div>
          <el-tree
            ref="menutree"
            style="width: 100%;"
            :data="menuTree[0]?.subMenuList"
            default-expand-all
            @node-click="treeNode"
            @check="treecheck"
            node-key="pkId"
            highlight-current
            :default-checked-keys="defKeys"
            :props="{
              children: 'subMenuList',
              label: 'name'
            }"
            show-checkbox
          />
        </el-col>
        <el-col :span="12" style="padding: 20px;box-shadow: 0 0 10px 2px rgba(193, 193, 193, 0.5);border-radius: 10px;">
          <div style="padding-bottom: 10px;font-size: 20px;border-bottom: 1px solid #ccc;">接口权限分配</div>
          <div style="display: flex;justify-content: space-between;padding: 10px 0;">
            <div>{{roleName}}</div>
            <el-button 
            type="primary" 
            plain
            size="small"
            @click="jkqxsave"
          >保存</el-button>
          </div>
          <el-table
            ref="multipleTableRef"
            style="margin-top: 20px;"
            :data="jklist"
            border
            stripe
            @selection-change="handleSelectionChange" 
          >
          <el-table-column type="selection" width="55" />
            <el-table-column label="接口名称" width="140" align="center" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="请求方式" width="80" align="center" prop="requestType" :show-overflow-tooltip="true" />
            <el-table-column label="URL" width="260" align="center" prop="uri" :show-overflow-tooltip="true" />
          </el-table>
        </el-col>
      </el-row>       
      </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { 
    getjslist,
    addrole,
    updaterole,
    delrole,
    allAddpermi,
    getinter
  } from '@/api/systemSet/role'
  import { 
    getInter,
  } from '@/api/systemSet/menu'
  import { 
    getRouters
  } from '@/api/menu'
  import { ref,reactive } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  
  //查询  

   let dictlist = ref<any>([])
   function querytype() {
    dictlist.value.splice(0)
    getjslist('').then(rps => {
      if(rps.data){
        dictlist.value = rps.data
      }
      
    })
   }

   //新增、修改
   let cztype = ref(1)
   let typeform = ref()
   let popshow = ref(false) 
   let poptit = ref('添加角色')
   let addObj = reactive({
      pkId:'',
      name:'',	                //角色名称
      rcode:'',	                //角色编码
      mark:'',	                //功能描述
      status:1,	                //状态
      type:1,	                //角色类型：1-开发者，2-运营方，3-客户
      readonly:0	              //是否内置角色，内置角色不允许修改
    })
    const rules = {
      type: [
          { required: true, message: "请选择角色类型", trigger: "blur" },
      ],
      name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
      ],
      rcode:[
          { required: true, message: "请输入角色编码", trigger: "blur" },
      ]
    }
    function caoztype() {
      if(cztype.value == 1){
        return addrole(addObj) 
      }
      return updaterole(addObj)
    }

    function showpop(type:number,row?:any) {
      cztype.value = type
      popshow.value = true
      poptit.value = type == 1?'添加角色':'修改角色'
      typeform.value?.resetFields()
      if(row){
        addObj.name = row.name	                
        addObj.rcode = row.rcode	              
        addObj.mark = row.mark	                
        addObj.status = row.status	            
        addObj.type = row.type	                
        addObj.readonly = row.readonly
        addObj.pkId = row.pkId	                   
      }else{    
        addObj.name = ''	                
        addObj.rcode = ''	              
        addObj.mark = ''	                
        addObj.status = 1	            
        addObj.type = 1	                
        addObj.readonly = 0	      
      }
    }

    //保存
    function save() {
      typeform.value?.validate((valid:Boolean) => {
        if (valid) {
          caoztype().then(() => {
            ElMessage({
              type: 'success',
              message: cztype.value == 1?'添加成功':'修改成功'
            })
            setTimeout(() => {
              popshow.value = false
              querytype()
            },1000)
          })
        }
      })
    }

    //删除
    function handleDelete(row:any) {
      ElMessageBox.confirm(
      `确定删除：${row.name}`,
      '温馨提示',
      {
        // confirmButtonText: '',
        // cancelButtonText: 'Cancel',
        type: 'warning',
      }
    ).then(() => {
      delrole(row.pkId).then(rps => {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          querytype()
        })
      })
    }

    function canceltype() {
      popshow.value = false
    }

    //菜单分配
    let menuTree = ref<any>([])
    let treedrawer = ref(false)
    let roleName = ref('')
    let defKeys = ref<any>([])

    let jklist = ref<any>([])
    let menutree = ref()
    let checkArr = ref([])
    let quanxpar = reactive({
      rcode:'',	                //角色编码
      types:'MENU',	            //类型，不同类型之间用';' SYS-系统，MENU-菜单，PER-资源权限         示例 SYS;MENU;PER
      sourceIds:''	            //资源ID。同一类型之间用','隔开，不同类型之间用';'隔开，与type对应   跟types顺序保持一致   示例 123,4561;asd,sdd;ms11,4d4s
    })
    function fenpqx(row:any) {
      roleName.value = row.name
      treedrawer.value = true
      quanxpar.rcode = row.rcode
      quanxpar.sourceIds = ''
      defKeys.value.splice(0)
      jklist.value.splice(0)
      jkobj.sourceIds = ''
      getRouters().then(rps => {
        menuTree.value = rps.data
        return  getinter({
          rcode:row.rcode,             //角色编码
          resourceType:'MENU'          //资源类型??
        })
      }).then(rps => {
        if(rps.data){
          defKeys.value = (rps.data as any).map((n:any) => {
            return n.resourceId
          })
          quanxpar.sourceIds = defKeys.value.join(',')
        }
        
      })
    }

    
    //接口权限分配
    let jkobj = reactive({
      rcode:'',
      types:'PER',	            
      sourceIds:''	            
    })
    let defjk = ref<any>([])
    let multipleTableRef = ref()
    function treeNode(n:any){
      jklist.value.splice(0)
      jkobj.sourceIds = ''
      getInter(n.pkId).then(rps => {
        if(rps.data){
          jklist.value = rps.data
        }
        return  getinter({
          rcode:quanxpar.rcode,             
          resourceType:'PER'
        })
      }).then(rps => {
        if(rps.data){
          defjk.value = (rps.data as any).map((m:any) => {
            return m.resourceId
          })
          jkobj.sourceIds = defKeys.value.join(',')

          //回显接口权限
          jklist.value.forEach((v:any) => {
            if (defjk.value.includes(v.pkId)) {
              (multipleTableRef.value as any).toggleRowSelection(v, true)
            }
          })
        }
      })
    }
    
    
    function addquanx(){
      if(quanxpar.sourceIds.length > 0){
        allAddpermi(quanxpar).then(() => {
          ElMessage({
            type: 'success',
            message: '菜单权限分配成功'
          })
        })
      }else{
        ElMessage({
          type: 'warning',
          message: '请选择菜单'
        })
      }
    }

    function treecheck(n:any,v:any){
      //checkArr.value = menutree.value.getCheckedNodes(true,true)
      console.log(v,2) //.checkedKeys

      // let ids = checkArr.value.map((n:any) => {
      //   return n.pkId
      // })
      let ids = [...v.checkedKeys,...v.halfCheckedKeys]
      quanxpar.sourceIds = ids.join(',')
    }
    
    
    //接口权限
     function jkqxsave(){
      if(jkobj.sourceIds.length > 0){
        jkobj.rcode = quanxpar.rcode
        allAddpermi(jkobj).then(() => {
          ElMessage({
            type: 'success',
            message: '接口权限分配成功'
          })
        })
      }else{
        ElMessage({
          type: 'warning',
          message: '请选择接口权限'
        })
      }
    }

     function handleSelectionChange(n:any) {
      if(n.length > 0){
        let ids = n.map((m:any) => {
          return m.pkId
        })
        jkobj.sourceIds = ids.join(',')
      }
      
     }

    function handleClose() {  
      treedrawer.value = false
    }

   querytype()
</script>
