<script lang="ts" setup>
import { ref, onMounted,nextTick} from 'vue'
import permission_table_edit_blue from '@/assets/svg/permission_table_edit_blue.svg'
import permission_table_del_blue from '@/assets/svg/permission_table_del_blue.svg'
import perission_role_blue from '@/assets/svg/perission_role_blue.svg'
import icon_add from '@/assets/svg/add_white.svg'
import type { FormInstance } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { ElTable,ElTree,ElMessage, ElMessageBox } from 'element-plus'
import { listRole,addRole,updateRole,setIsValid,deleteRoleById,deleteRoleByIds,permissionAssignment,setMenuByRoleId } from '@/api/permission/role'
const props = defineProps({
  applicationId:String
})
const tableloading = ref(false)
const dialogVisible = ref(false);
const title = ref('新增角色');
const preventcombo = ref(false)
const ruleForm = ref();
const ruleFormRef = ref<FormInstance>()
const rules = ref({
  rolename: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择角色类别', trigger: 'change' },
  ],
})
const queryrolename = ref('')
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
const tableData = ref([])
const typeoptions = ref([
  { value: '1', label: '管理员' },
  { value: '2', label: '普通用户' },
])
const configdialog = ref(false)
const treeData:any = ref([])
const defaultProps = {
  children: 'children',
  label: 'name'
}
const treeloading = ref(false);
const treeRef = ref<InstanceType<typeof ElTree>>()
const currenttableid = ref('')
const Passparameter = ref([])
//默认展开节点的key数组
const DefaultDeployment: any = ref([])
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if(preventcombo.value){
        return
      }
      preventcombo.value = true
      if(ruleForm.value.id !== ''){
        updateRole(ruleForm.value).then(res => {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
          dialogVisible.value = false
          preventcombo.value = false
          queryrolename.value = ''
          gettable()
        })
      }else{
        addRole(ruleForm.value).then(res => {
          ElMessage({
            type: 'success',
            message: '新增成功',
          })
          dialogVisible.value = false
          preventcombo.value = false
          queryrolename.value = ''
          gettable()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}

const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
onMounted(() => {
  gettable()
})
function permissionset(row:any){
  currenttableid.value = row.id
  configdialog.value = true
  treeloading.value = true
  const params = { 
    roleId: row.id,
    appId: props.applicationId,
  }
  permissionAssignment(params).then(res => {
    treeData.value = res.data
    let ids: any = []
    menuChange(res.data, ids)
    nextTick(() => {
      treeRef.value!.setCheckedKeys(ids)
    })
    treeloading.value = false
   })
   
}
function gettable(){
  tableloading.value = true
  const params = {
    appId: props.applicationId,
    rolename:''
  }
  listRole(params).then(res => {
    tableData.value = res.data
    tableloading.value = false
  })
}
function querytable(){
  tableloading.value = true
  const params = {
    appId: props.applicationId,
    rolename:queryrolename.value
  }
  listRole(params).then(res => {
    tableData.value = res.data
    tableloading.value = false
  })
}
function edittable(data:any){ 
  title.value = '修改角色'
  ruleForm.value = JSON.parse(JSON.stringify(data))
  dialogVisible.value = true
}
function deltable(row:any){ 
  ElMessageBox.confirm(
    '确定删除该条信息吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      deleteRoleById(row.id).then(res => {
        if(res.code == '0'){
          gettable()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }else{
          ElMessage.error('删除失败')
        }
      })
    }).catch(() => { 
    })
}
function deltables(){
  ElMessageBox.confirm(
    '确定删除该条信息吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const arr = []
    multipleSelection.value.forEach(e => {
      arr.push(e.id)
    });
    deleteRoleByIds(arr.join()).then(res => {
      if(res.data.code == '0'){
        gettable()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }else{
        ElMessage.error('删除失败')
      }
    }) 
  }).catch(() => {})
}
function addtable(){
  ruleForm.value = {
    id:'',
    appId:props.applicationId,
    rolename: '',
    rolecode: '',
    type: '',
    description:'',
    isvaild:'1',
  }
  title.value = '新增角色'
  dialogVisible.value = true
}
function handleClose() {
  ruleFormRef.value?.resetFields();
  dialogVisible.value = false;
}
function formatDateTime(dateArray:any){
  if (!Array.isArray(dateArray) || dateArray.length < 6) return 'Invalid Date'
  
  const pad = (n: number) => n.toString().padStart(2, '0')
  
  return `${dateArray[0]}-${pad(dateArray[1])}-${pad(dateArray[2])} ` +
         `${pad(dateArray[3])}:${pad(dateArray[4])}:${pad(dateArray[5])}`
}
function setisValid(row:any){
  tableloading.value = true
  const params = {
    id:row.id,
    isvaild:row.isvaild
  }
  setIsValid(params).then(res => {
    if(res.code == '0'){
      gettable()
      ElMessage.success('设置成功')
    }else{
      ElMessage.error('设置失败')
    }
    tableloading.value = false
  })
}
function confighandleClose(){ 
  configdialog.value = false
}
function consfigsubmit(){
  const params = { 
    id: currenttableid.value,
    menuIds: Passparameter.value.join(',') 
  }
  setMenuByRoleId(params).then(res => {
    if(res.code == '0'){
      gettable()
      ElMessage.success('设置成功')
    }else{
      ElMessage.error('设置失败')
    }
  })
  configdialog.value = false
}
function currentChecked(nodeObj: any, SelectedObj: any){
  Passparameter.value = SelectedObj.checkedKeys.concat(SelectedObj.halfCheckedKeys)
}
function menuChange(data: any, ids: any) {
  data.forEach((item: any) => {
    if (item.checkinfo == true) {
      ids.push(item.id)
      DefaultDeployment.value.push(item.id)
    }
    if (item.children) {
      menuChange(item.children, ids)
    }
  })
}
</script>
<template>
   <div class="organization-box">
      <div class="querybox">
        <div>
          <el-input v-model="queryrolename" placeholder="请输入角色名称" style="width: 200px;margin-right: 10px;" />
          <el-button type="primary" style="min-width: 50px;" @click="querytable">搜索</el-button>
        </div>
        <div>
          <el-button type="primary" style="min-width: 50px;" @click="addtable">
            <el-icon style="margin-right: 3px;">
              <icon_add class="svg-icon" />
            </el-icon>新增
          </el-button>
          <el-button :type="multipleSelection.length>0?'primary':''" :disabled="multipleSelection.length>0?false:true" @click="deltables" style="min-width: 50px;">
            <el-icon style="margin-right: 3px;"><Delete /></el-icon>删除
          </el-button>
        </div>
      </div>
      <el-table v-loading="tableloading"  ref="multipleTableRef" :data="tableData" border style="width: 100%"
        @selection-change="handleSelectionChange"  height="calc(100vh - 175px)">
        <el-table-column type="selection" width="55" /> 
        <el-table-column prop="rolecode" label="角色编号" width="130"/>
        <el-table-column prop="rolename" label="角色名称"/>
        <el-table-column prop="type" label="角色级别" width="150">
          <template #default="scope">
            <span v-if="scope.row.type == '1'" style="font-size: 14px;">管理员</span>
            <span v-else-if="scope.row.type == '2'" style="font-size: 14px;">普通用户</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="角色描述"/>
        <el-table-column prop="isvaild" label="是否有效" width="110">
          <template #default="scope">
            <el-switch v-model="scope.row.isvaild" active-value="1" inactive-value="0"  style="margin-right: 10px;" @change="setisValid(scope.row)"/> 
            <span v-if="scope.row.isvaild == '1'" style="color: #0089ff;font-size: 14px;">有效</span>
            <span v-else-if="scope.row.isvaild == '0'" style="color: #bbbfc4;font-size: 14px;">无效</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastmodifier" label="最近修改者" width="120"/>
        <el-table-column prop="lastmodifydate" label="最近修改日期" width="170">
            <template #default="scope">
              <span v-if="scope.row.lastmodifydate">{{formatDateTime(scope.row.lastmodifydate)}}</span>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template  #default="scope">
            <el-icon title="修改" style="font-size: 16px;cursor: pointer;" @click="edittable(scope.row)">
              <permission_table_edit_blue class="svg-icon"/> 
            </el-icon>
            <el-icon title="权限分配" style="font-size: 16px;margin:0px 10px;cursor: pointer;" @click="permissionset(scope.row)">
              <perission_role_blue class="svg-icon"/> 
            </el-icon>
            <el-icon title="删除" style="font-size: 16px;cursor: pointer;" @click="deltable(scope.row)">
              <permission_table_del_blue class="svg-icon"/> 
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm">
          <el-form-item label="角色编号" prop="rolecode">
            <el-input v-model="ruleForm.rolecode" disabled  placeholder="系统自动生成"/>
          </el-form-item>
          <el-form-item label="角色名称" prop="rolename">
            <el-input v-model="ruleForm.rolename" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色级别" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择角色级别" style="width:100%;">
              <el-option v-for="item in typeoptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="ruleForm.description"  placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="configdialog" title="角色权限配置" width="30%" :before-close="confighandleClose">
        <el-tree v-loading="treeloading" ref="treeRef" :data="treeData" node-key="id" :props="defaultProps"
          default-expand-all :expand-on-click-node="false" show-checkbox @check="currentChecked"
          style="height: calc(100vh - 300px);overflow: auto;">
        </el-tree>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="confighandleClose">取消</el-button>
            <el-button type="primary" @click="consfigsubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
</template>

<style lang="less" scoped>
.organization-box{
  width: 100%;
  height: 100%;
  background: #ffffff;
  box-shadow: 0px 0px 10px rgba(219, 225, 236, 1);
  border-radius: 5px;
  padding: 20px;
  .querybox{
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
:deep(.ed-dialog__body){
  padding: 10px 24px;
}
</style>