<script setup>
import DepartWrap from './components/DepartWrap.vue'
import { Search, CloseBold,InfoFilled } from '@element-plus/icons-vue'
import { apiSystemUser, apiSystemRole } from '@/api/system'
import { reactive } from 'vue';

// 获取角色
const roleId = ref('')
const roleArr = ref([])
async function getRoleList() {
  const res = await apiSystemRole.roleAllList()
  if (res.Ret !== 200) return
  const list = res.Data.List || []
  roleArr.value = list
}
getRoleList()

const keyword = ref('')

const departId = ref('')
const departLevel=ref(0)

const tableColOpt = [
  {
    label: '姓名',
    key: 'SysRealName'
  },
  {
    label: '工号',
    key: 'SysUserName'
  },
  {
    label: '手机号',
    key: 'Phone'
  },
  {
    label: '邮箱',
    key: 'Email'
  },
  {
    label: '角色',
    key: 'SysRoleName'
  },
  {
    label: '部门/分组',
    key: 'SysDepartmentName'
  },
  {
    label: '在职状态',
    key: 'IsEnabled'
  },
]
const userList = ref([])
const page = ref(1)
const pageSize = ref(10)
const tableLoading = ref(false)
const totals = ref(0)
async function getUserList() {
  tableLoading.value = true
  const res = await apiSystemUser.userList({
    PageSize: pageSize.value,
    CurrentIndex: page.value,
    /* RoleId: roleId.value, */
    KeyWord: keyword.value,
    DepartmentId: departId.value,
    Level:departLevel.value
  })
  tableLoading.value = false
  if (res.Ret === 200) {
    userList.value = res.Data.List || []
    totals.value = res.Data.Paging.Totals
  }
}
getUserList()
function handlePageChange(e) {
  page.value = e
  getUserList()
}
function refreshUserList() {
  page.value = 1
  getUserList()
}

let show = ref(false)
const formState = reactive({
    SysUserId:'',
    SysUserName:'',
    SysRoleId:'',
})
function changeUserAuth(data){
    formState.SysUserId = data.SysUserId||0
    formState.SysUserName = data.SysRealName||''
    formState.SysRoleId = data.SysRoleId||0
    show.value = true
}
function handleSubmitForm(){
    if(!formState.SysRoleId) return ElMessage.warning('请选择角色')
    const {SysUserId,SysUserName,SysRoleId} = formState
    apiSystemUser.userEdit({
        SysUserId,SysUserName,SysRoleId
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success('设置成功')
        getUserList()
        show.value = false
    })
}
const isShowDetail = ref(false)
const curUser = ref({})
const authList = ref([])
const defaultCheckedKeys = ref([])
const checkboxTree=ref(null)
function getUserDetail(row){
    curUser.value = row
    apiSystemRole.roleAuthList({
        SysRoleId:row.SysRoleId
    }).then(res=>{
        if(res.Ret!==200) return 
        authList.value=disabledTree(res.Data.List||[])
        const arr=res.Data?.ChoiceList||[]
        const hArr=res.Data?.HalfChoiceList||[]
        defaultCheckedKeys.value=arr.filter(i=>{
            return !hArr.includes(i)
        })
        checkboxTree.value?.setCheckedKeys(defaultCheckedKeys.value)
        isShowDetail.value = true
    })
}
function disabledTree(arr){
  arr.forEach(item => {
    item.Disabled=true
    if(item.Children){
      disabledTree(item.Children)
    }
  });
  return arr
}
</script>


<template>
  <div class="flex system-userlist-page">
    <DepartWrap 
      v-model:departActive="departId"
      v-model:departLevel="departLevel"
      @change="refreshUserList" 
    />
    <div class="user-wrap">
      <div class="user-top-box">
        <el-input
          placeholder="工号/手机号/邮箱搜索"
          v-model="keyword"
          :prefix-icon="Search"
          clearable
          @input="refreshUserList"
          style="max-width: 359px; float: right"
        >
        </el-input>
      </div>
      <div class="table-wrap">
        <el-table
          :data="userList"
          border
          stripe
          highlight-current-row
          element-loading-text="数据加载中..."
          v-loading="tableLoading"
          @row-click="getUserDetail"
        >
          <el-table-column
            v-for="column in tableColOpt"
            :key="column.key"
            :prop="column.key"
            :label="column.label"
          >
            <template #default="{ row }">
              <span
                v-if="column.key === 'IsEnabled'"
                >{{ row.IsEnabled ? "在职" : "离职" }}</span
              >
              <span v-else>{{ row[column.key] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260">
            <template #default="{ row }">
              <el-button
                v-if="row.SysUserName!=='admin'"
                v-permission="'sysuser:userConfig'"
                type="primary"
                link
                @click.stop="changeUserAuth(row)"
                >配置角色</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="total,prev,pager,next"
          :current-page="page"
          :page-size="pageSize"
          :total="totals"
          @current-change="handlePageChange"
          style="margin-top: 30px; justify-content: flex-end"
        />
        <div class="user-detail" v-if="isShowDetail">
            <div class="close_btn" @click="isShowDetail=false">
                <el-icon :size="16"><CloseBold /></el-icon>
            </div>
            <div class="detail-info">
                <div class="top">
                    <img src="@/assets/imgs/default_user.png"/>
                    <span class="name">{{ curUser.SysRealName }}</span>
                </div>
                <div class="info">
                    <div><p>手机号：</p><p>{{ curUser.Phone }}</p></div>
                    <div><p>邮箱：</p><p>{{curUser.Email}}</p></div>
                    <div><p>部门/分组：</p><p>{{ curUser.SysDepartmentName }}</p></div>
                    <div><p>工号：</p><p>{{curUser.SysUserName}}</p></div>
                    <div><p>职级：</p><p>{{ curUser.PositionName }}</p></div>
                    <div>
                        <p>
                            职级数字
                            <el-tooltip
                                effect="dark"
                                content="60以上为部门负责人级别"
                                placement="top-start"
                            >
                                <el-icon :size="14"><InfoFilled /></el-icon>
                            </el-tooltip>
                            ：
                        </p>
                        <p>{{ curUser.PositionCode }}</p>
                    </div>
                    <div><p>在职状态：</p><p>{{ curUser.IsEnabled?'在职':'离职' }}</p></div>
                </div>
                <el-popover
                    placement="left"
                    :title="curUser.SysRealName+'权限'"
                    width="560"
                    trigger="hover">
                    <div class="auth_cont" style="padding:30px 0;max-height: 70vh; overflow-y: auto;">
                        <el-tree v-if="authList.length"
                            ref="checkboxTree"
                            :data="authList"
                            :props="{ label: 'Name', children: 'Children', disabled: 'Disabled' }"
                            :default-expand-all="true"
                            show-checkbox
                            node-key="SysMenuId"
                            :default-checked-keys="defaultCheckedKeys"
                        >
                        </el-tree>
                        <span v-else style="font-size:16px;color:#999;margin-left:20px;">暂无权限</span>
                    </div>
                    <template #reference>
                        <el-button link type="primary"> 查看权限</el-button>
                    </template>
                </el-popover>
            </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 配置角色弹窗 -->
  <el-dialog v-model="show" width="500" draggable title="配置角色">
    <el-form ref="formRef" :model="formState">
      <el-form-item label="角色" prop="name">
        <el-select v-model="formState.SysRoleId">
            <el-option v-for="item in roleArr" :key="item.SysRoleId" 
                :label="item.SysRoleName"
                :value="item.SysRoleId"
            />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="btn-content" style="text-align: center; padding-bottom: 20px">
        <el-button
          type="primary"
          style="width: 80px; margin-right: 24px"
          @click="handleSubmitForm"
          >保存</el-button
        >
        <el-button style="width: 80px" @click="show = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.system-userlist-page {
  gap: 30px;
  .user-wrap {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .user-top-box{
    display: flex;
    justify-content: flex-end;
  }
  .table-wrap {
    margin-top: 20px;
    position: relative;
    flex:1;
    .user-detail{
        width: 350px;
        background: #fff;
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        overflow-y: hidden;
        z-index: 3;
        padding:20px;
        .close_btn {
            width: 16px;
            height: 16px;
            position: absolute;
            right: 20px;
            top: 20px;
            cursor: pointer;
        }
        .detail-info{
            height: 100%;
            overflow-y:auto;
            .top{
                margin-top: 20px;
                display: flex;
                align-items: center;
                img{
                    width:28px;
                    height: 28px;
                    margin-right: 5px;
                }
            }
            .info{
                margin-top: 30px;
                display: flex;
                flex-direction: column;
                gap:20px;
            }
            .el-button{
                position:absolute;
                left:20px;
                bottom:20px;
            }
        }
    }
  }
}
</style>