<template>
  <el-dialog
    title="编辑角色"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="800px"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    :align-center="true"
    :fullscreen="false"
    @close="handleClose"
    class="user-edit-dialog"
  >
    <div class="dialog-content" style="padding: 20px; padding-bottom: 80px;height: 700px;overflow-y: auto;">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
      <!-- 姓名和角色名 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色名" prop="rolename">
            <el-input v-model="form.rolename" :disabled="!!form.id" placeholder="请输入角色名" @blur="changeCheckNameExit" />
          </el-form-item>
        </el-col>
      </el-row>
    
      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          placeholder="请输入备注"
        />
      </el-form-item>
      </el-form>
      <!-- 权限设置 -->
        <PermissionArea
          :permissionList="permissionList"
          :allPermissionsSelected="allPermissionsSelected"
          @update:allPermissionsSelected="val => allPermissionsSelected = val"
          @permission-change="handlePermissionChange"
          @sub-permission-change="handleSubPermissionChange"
        />
      </div>
    <template #footer>
      <div class="dialog-footer">
        <div class="footer-buttons">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { queryAll as queryAllMenu } from '@/api/safetyManagement/menuConfig.js'
import { initEdit, add, modify, checkNameExit } from '@/api/safetyManagement/roleConfig.js'
import { ArrowRight, ArrowDown } from '@element-plus/icons-vue'
import PermissionArea from '@/components/PermissionArea/index.vue'
import { id } from 'element-plus/es/locales.mjs'
// 定义组件名称
defineOptions({
  name: 'RoleEdit'
})

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => null
  }
})

// 定义emits
const emit = defineEmits(['update:visible', 'success'])

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null, 
  rolename: '',
  remark: ''
})

// 表单校验规则
const rules = {
  rolename: [
    { required: true, message: '请输入角色名', trigger: 'blur' }
  ]
}

// 响应式数据
const allSelected = ref(false)
const searchRole = ref('')
const selectedRoles = ref([])
const allPermissionsSelected = ref(false)
const permissionList = ref([])
// 用户当前具有的权限ID列表
const menuIdList = ref([])

// 获取菜单权限列表
const fetchPermissionList = async () => {
  try {
    const res = await queryAllMenu()
    if (res.code === 'POP_00014') {
      permissionList.value = mapMenuToPermissions(res.data || [])
    } else {
      console.error('获取权限菜单失败:', res.msg)
    }
  } catch (error) {
    console.error('获取权限菜单异常:', error)
  }
}

// 将菜单数据转换为权限列表格式
const mapMenuToPermissions = (menuArr) => {
  return menuArr.filter(item => item.type !== '3' || item.type === 1).map(item => {
    const hasChildren = Array.isArray(item.children) && item.children.length > 0
    let children = hasChildren ? mapMenuToPermissions(item.children) : null
    
    return {
      id: item.id,
      name: item.type === '2' ? '项目管理-' + item.name : item.name,
      selected: false,
      indeterminate: false,
      expanded: false,
      children
    }
  })
}

// 计算属性
const filteredRoles = computed(() => {
  return props.roles?.filter(role => 
    role.name.toLowerCase().includes(searchRole.value.toLowerCase())
  ) || []
})

// 监听props变化
watch(() => props.visible, async (val) => {
  if (val) {
    // 获取所有可选权限列表
      const menuRes = await queryAllMenu()
    
    if (props.formData && props.formData.id) {
      try {
        // 调用接口获取角色详情
        const res = await initEdit({ roleid: props.formData.id })
        if (res.code === 'POP_00014') {
          // 填充表单数据
          Object.assign(form, {
            ...res.data.roles
          })

          // 如果返回了权限列表，更新权限数据
          permissionList.value = mapMenu(menuRes.data, res.data.menuIdList ? res.data.menuIdList.map(m => m.menuid) : [])

        } else {
          console.error('获取角色详情失败:', res.msg)
        }
      } catch (error) {
        console.error('获取角色详情异常:', error)
      }
    } else {
      // 新增角色时重置表单
      resetForm()
       // 获取所有可选权限列表
      const menuRes = await queryAllMenu()
      permissionList.value = mapMenu(menuRes.data, [])
    }
  }
})

// 方法
// 重置表单数据
const resetForm = () => {
  nextTick(() => {
    formRef.value?.resetFields()
    form.id = null
    Object.assign(form, {
      id: null,
      rolename: '',
      remark: ''
    })

    console.log('reset form', form)
  })
}

 // 权限
  function mapMenu(menuArr, selectedIds = []) {
    return (menuArr || []).filter(item => item.type !== '3' || item.type === 1).map(item => {
      const hasChildren = Array.isArray(item.children) && item.children.length > 0
      let children = hasChildren ? mapMenu(item.children, selectedIds) : null
      let selected = selectedIds.includes(item.id)
      let indeterminate = false
      if (hasChildren) {
        const selectedCount = children.filter(c => c.selected).length
        if (selectedCount === 0) {
          selected = false
          indeterminate = false
        } else if (selectedCount === children.length) {
          selected = true
          indeterminate = false
        } else {
          selected = false
          indeterminate = true
        }
      }
      return {
        id: item.id,
        name: item.type === '2'? '项目管理-'+item.name : item.name,
        selected,
        indeterminate,
        expanded: false,
        children
      }
    })
  }


const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
      const params = { roles: {
        rolename: form.rolename,
        remark: form.remark,
        id: form.id
      } }
      
      // 收集选中的菜单权限
      const selectedMenuIds = []
      const collectSelectedMenus = (menus) => {
        menus.forEach(menu => {
          if (menu.selected) {
            selectedMenuIds.push(menu.id)
          }
          if (menu.children && menu.children.length > 0) {
            collectSelectedMenus(menu.children)
          }
        })
      }
      
      collectSelectedMenus(permissionList.value)
      params.idList = selectedMenuIds

      console.log('submit form', params)
      if(form.id){
        // 调用modify方法 
        modify(params).then(res => {
          if (res.code === 'POP_00014') {
            console.log('角色添加成功', res);
            emit('success');
            handleClose();
          } else {
            console.error('角色添加失败:', res.msg);
          }
        }).catch(error => {
          console.error('角色添加异常:', error);
        });
          
      }else{
        const res = checkNameExit({ rolename: form.rolename });
        if (res.code !== 'POP_00014') {
          console.error('角色名已存在:', res.msg);
          return
        }
         // 调用add方法 
        add(params).then(res => {
          if (res.code === 'POP_00014') {
            console.log('角色添加成功', res);
            emit('success');
            handleClose();
          } else {
            console.error('角色添加失败:', res.msg);
          }
        }).catch(error => {
          console.error('角色添加异常:', error);
        });
      }
      handleClose()
    }
  })
}



const handlePermissionChange = (item, val) => {
  // 处理父级权限选择
  item.selected = val
  item.indeterminate = false // 清除半选状态
  if (item.children) {
    item.children.forEach(child => {
      child.selected = val
    })
  }
  checkAllPermissionsStatus()
}

const handleSubPermissionChange = (parent, child, val) => {
  // 处理子级权限选择
  child.selected = val
  // 检查父级状态
  if (parent.children) {
    // 如果所有子项都选中，父级完全选中
    const allSelected = parent.children.every(c => c.selected)
    // 如果部分子项选中，父级半选
    const someSelected = parent.children.some(c => c.selected)
    
    parent.selected = allSelected
    parent.indeterminate = !allSelected && someSelected
  }
  checkAllPermissionsStatus()
}

const checkAllPermissionsStatus = () => {
  // 检查是否全部选中
  allPermissionsSelected.value = permissionList.value.every(item => {
    if (item.children) {
      return item.selected && item.children.every(child => child.selected)
    }
    return item.selected
  })
}

// 组件挂载后初始化权限列表
onMounted(() => {
  // 初始获取权限列表
  fetchPermissionList()
})

// 验证角色名是否存在
const changeCheckNameExit = async () => {
  if (form.rolename && !form.id) {
    try {
      const res = await checkNameExit({ rolename: form.rolename });
      if (res.code !== 'POP_00014') {
        console.error('角色名已存在:', res.msg);
      } else {
        console.log('角色名可用');
      }
    } catch (error) {
      console.error('验证角色名异常:', error);
    }
  }
};
</script>

<style lang="scss" scoped>
.role-transfer {
  display: flex;
  align-items: flex-start;
  gap: 10px;

  .transfer-list {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    height: 300px;
    display: flex;
    flex-direction: column;

    .transfer-header {
      padding: 8px 12px;
      border-bottom: 1px solid #dcdfe6;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #f5f7fa;
    }

    .role-list, .selected-list {
      flex: 1;
      overflow-y: auto;
      padding: 6px 0;
    }

    .role-item {
      padding: 6px 12px;
      cursor: pointer;

      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  .transfer-operation {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
  }
}

.permission-area {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  display: flex;
  flex-direction: column;
  max-height: 400px;
  overflow-y: auto;

  .all-select {
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
    position: sticky;
    top: 0;
    z-index: 1;
  }

  .permission-list {
    padding: 12px;

    .permission-item {
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }

      .permission-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 0;
        cursor: pointer;

        .left {
          display: flex;
          align-items: center;
          gap: 8px;

          .expand-icon {
            transition: transform 0.3s;
            font-size: 12px;
            color: #909399;

            &.expanded {
              transform: rotate(90deg);
            }
          }
        }
      }

      .sub-permissions {
        padding: 8px 0 8px 32px;
        display: flex;
        flex-direction: column;
        gap: 12px;
        background-color: #f8f9fb;
        border-top: 1px solid #ebeef5;
      }
    }
  }
}

:deep(.el-transfer-panel) {
  width: 100%;
}

.user-edit-dialog {
  :deep(.el-dialog) {
    display: flex;
    flex-direction: column;
    margin: 0 auto !important;
    max-height: 90vh;
    position: relative;

    .el-dialog__body {
      flex: 1;
      overflow: hidden;
      padding: 0;
    }

    .dialog-content {
      height: 100%;
      overflow-y: auto;
      padding: 20px;
      padding-bottom: 80px;
    }
  }
}

.dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #dcdfe6;
  z-index: 9999;
  
  .footer-buttons {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }
}
</style>
