<script lang="ts" setup>
import { ref, onMounted} 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 reset_password_blue from '@/assets/svg/reset_password_blue.svg'
import icon_add from '@/assets/svg/add_white.svg'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { ElTable,ElTree } from 'element-plus'
import { getOrganizationById } from '@/api/permission/organization'
import { queryUsers,addUser,updateUser,setStatus,deleteUserById,deleteUserByIds,resetPassword } from '@/api/permission/user'
const props = defineProps({
  applicationId:String
})
const treeData:any = ref([])
const defaultProps = {
  children: 'children',
  label: 'orgname'
}
const treeloading = ref(false);
const tableloading = ref(false);
const currentNodeId = ref(null);
const dialogVisible = ref(false);
const title = ref('新增用户');
const ruleForm:any = ref({});
const ruleFormRef = ref<FormInstance>()
const treeRef = ref<InstanceType<typeof ElTree>>()
const rules = ref({
  username: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
  ],
  usertype: [
    { required: true, message: '请选择所属角色', trigger: 'change' },
  ],
})
const preventcombo = ref(false)
const querynickname = ref('')
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
const tableData = ref([])
const typeoptions = ref([
  { value: '1', label: '管理员' },
  { value: '2', label: '普通用户' },
])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid:any) => {
    if (valid) {
      if(preventcombo.value){
        return
      }
      preventcombo.value = true
      if(ruleForm.value.id !== ''){
        updateUser(ruleForm.value).then(res => {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
          dialogVisible.value = false
          preventcombo.value = false
          getuserinfo()
        })
      }else{
        addUser(ruleForm.value).then(res => {
          ElMessage({
            type: 'success',
            message: '新增成功',
          })
          dialogVisible.value = false
          preventcombo.value = false
          getuserinfo()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
onMounted(() => {
  treeData.value = []
  gettree()
})
function gettree(){
  treeloading.value = true
  getOrganizationById(props.applicationId).then(res => {
    if(res.data.data.length>0){
      treeData.value = gettreeData(res.data.data)
    }
    treeloading.value = false
  })
}
function gettreeData(orglist:any) {
  const res = {};
  for (const row of orglist) {
  // 处理 parentid 并解构需要字段
    const parentid = row.parentid || "0";
    const { id, orgcode, orgname, appId, orgtype, isvaild } = row;
    // 统一节点数据对象
    const nodeData = { parentid, id, orgcode, orgname, appId, orgtype, isvaild }
    // 更新或创建节点
    if (res[id]) {
      Object.assign(res[id], nodeData);
    } else {
      res[id] = { ...nodeData, children: [] };
    }
    // 处理父子关系
    if (res[parentid]) {
      res[parentid].children.push(res[id]);
    } else {
      res[parentid] = { children: [res[id]] };
    }
  }
  return res[0].children;
}
function getuserinfo(){
  tableloading.value = true
  const params = {
    appId: props.applicationId,
    orgid:currentNodeId.value,
    nickname:'',
    current:1,
    size:10
  }
  queryUsers(params).then(res => {
    tableData.value = res.data.data.records
    total.value = Number(res.data.data.total)
    tableloading.value = false
  })
}
function queryuserinfo(){
  tableloading.value = true
  const params = {
    appId: props.applicationId,
    orgid:currentNodeId.value,
    nickname:querynickname.value,
    current:currentPage.value,
    size:pageSize.value
  }
  queryUsers(params).then(res => {
    tableData.value = res.data.data.records
    total.value = Number(res.data.data.total)
    tableloading.value = false
  })
}
function nodeclick(data:any,node:any){
  if(data.orgtype == '01'){
    treeRef.value!.setCurrentKey(null)
    return
  }
  currentNodeId.value = node.key
  currentPage.value = 1
  pageSize.value = 10
  getuserinfo()
}
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(() => {
    deleteUserById(row.id).then(res => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getuserinfo()
      })
    })
    .catch(() => {
    })
}
function deltables(){
  ElMessageBox.confirm(
    '确定删除该条信息吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const arr = []
      multipleSelection.value.forEach(e => {
        arr.push(e.id)
      });
      deleteUserByIds(arr.join()).then(res => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getuserinfo()
      })
    })
    .catch(() => {
      
    })
}
function addtable(){
  if(currentNodeId.value == '' || currentNodeId.value == null){
    ElMessage({
      type: 'warning',
      message: '请选择部门！',
    })
    return
  }
  ruleFormRef.value?.resetFields();
  ruleForm.value = {
    id:'',
    appId:props.applicationId,
    orgid:currentNodeId.value,
    username: '',
    usertype: '',
    nickname:'',
    email:'',
    phone:'',
    status:'1',
  }
  title.value = '新增用户'
  dialogVisible.value = true
}

function handleClose() {
  ruleFormRef.value?.resetFields();
  dialogVisible.value = false;
}
function handleSizeChange(val: number){
  pageSize.value = val
  queryuserinfo()
}
function handleCurrentChange(val: number){
  currentPage.value = val
  queryuserinfo()
}
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){
  const params = {
    id:row.id,
    status:row.status
  }
  setStatus(params).then(res => {
    if(res.code == '0'){
      getuserinfo()
      ElMessage.success('设置成功')
    }else{
      ElMessage.error('设置失败')
    }
  })
}
function resetclick(row:any){
  ElMessageBox.confirm(
    '是否重置该用户密码?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      resetPassword(row.id).then(res => {
        if(res.data.code == '0'){
          ElMessage.success('重置成功')
        }else{
          ElMessage.error('重置失败')
        }
      })
    })
    .catch(() => {})
}
</script>
<template>
   <div class="organization-box">
      <div class="organization-leftbox">
        <div class="leftbox-title">列表</div>
        <el-tree v-loading="treeloading" ref="treeRef" :data="treeData" node-key="id" :props="defaultProps"
         highlight-current default-expand-all :expand-on-click-node="false"
          @node-click="nodeclick">
        </el-tree>
      </div>
      <div class="organization-rightbox">
        <div class="querybox">
          <div>
            <el-input v-model="querynickname" placeholder="请输入用户名称" style="width: 200px;margin-right: 10px;" />
            <el-button type="primary" style="min-width: 50px;" @click="queryuserinfo">搜索</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%" height="calc(100vh - 230px)"
         @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" /> 
          <!-- <el-table-column prop="orgcode" label="用户编号"/> -->
          <el-table-column prop="nickname" label="用户姓名"/>
          <el-table-column prop="username" label="登录账号"/>
          <el-table-column prop="usertype" label="所属角色">
            <template #default="scope">
              <span v-if="scope.row.usertype == '1'">管理员</span>
              <span v-else-if="scope.row.usertype == '2'">普通用户</span>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱"/>
          <el-table-column prop="phone" label="手机号"/>
          <el-table-column prop="status" label="状态" width="110">
            <template #default="scope">
              <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"  style="margin-right: 10px;" @change="setisValid(scope.row)" /> 
              <span v-if="scope.row.status == '1'" style="color: #0089ff;font-size: 14px;">有效</span>
              <span v-else-if="scope.row.status == '0'" style="color: #bbbfc4;font-size: 14px;">无效</span>
            </template>
          </el-table-column>
          <el-table-column prop="lastmodifier" label="最近修改者"/>
          <el-table-column prop="lastmodifydate" label="最近修改日期" width="170">
            <template #default="scope">
                <span>{{formatDateTime(scope.row.lastmodifydate)}}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template  #default="scope">
              <el-icon 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="resetclick(scope.row)">
                <reset_password_blue class="svg-icon"/> 
              </el-icon>
              <el-icon 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-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 50, 100]" 
         background layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 20px;"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
      <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="nickname">
            <el-input v-model="ruleForm.nickname" />
          </el-form-item>
          <el-form-item label="登录账号" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="所属角色" prop="usertype">
            <el-select v-model="ruleForm.usertype" 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="email">
            <el-input v-model="ruleForm.email" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="ruleForm.phone" />
          </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>
    </div>
</template>

<style lang="less" scoped>
.organization-box{
  width: 100%;
  height: 100%;
  display: flex;
  .organization-leftbox{
    width: 240px;
    height: 100%;
    background: #ffffff;
    box-shadow: 0px 0px 10px rgba(219, 225, 236, 1);
    border-radius: 5px;
    margin-right: 15px;
    .leftbox-title{
      width: 100%;
      height: 44px;
      line-height: 44px;
      font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
      font-weight: 700;
      font-style: normal;
      font-size: 15px;
      color: #000000;
      border-bottom: 1px solid #e8e8e8;
      padding-left: 20px;
    }
    .leftbox-btn{
      width: 200px;
      height: 40px;
      border-width: 1px;
      border-style: solid;
      border-color: rgba(0, 137, 255, 1);
      border-radius: 3px;
      font-size: 14px;
      color: #0089FF;
      margin: 0 auto;
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    :deep(.el-tree-node__content){
      height: 40px;
      line-height: 40px;
    }
    :deep(.custom-tree-node){
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
    :deep(.el-tree-node__content>.ed-tree-node__expand-icon){
      padding: 2px;
    }
    :deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content .el-text){
      color: #409eff;
    }
  }
  .organization-rightbox{
    width: calc(100% - 240px);
    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;
  }
}
</style>