<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" placeholder="请输入角色名" />
          </el-form-item>
        </el-col>
      </el-row>
    
      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>

      <!-- 权限设置 -->
      <el-form-item label="权限设置">
        <div class="permission-area">
          <div class="all-select">
            <el-checkbox v-model="allPermissionsSelected" @change="handleAllPermissionsChange">全选</el-checkbox>
          </div>
          <div class="permission-list">
            <div v-for="(item, index) in permissionList" :key="index" class="permission-item">
              <!-- 父级权限项 -->
              <div class="permission-header" @click="toggleExpand(item)">
                <div class="left">
                  <el-icon class="expand-icon" :class="{ expanded: item.expanded }">
                    <component :is="item.expanded ? 'ArrowDown' : 'ArrowRight'" />
                  </el-icon>
                  <el-checkbox 
                    v-model="item.selected"
                    :indeterminate="item.indeterminate"
                    @change="(val) => handlePermissionChange(item, val)"
                  >
                    {{ item.name }}
                  </el-checkbox>
                </div>
                <div class="right">
                  <el-tag size="small" v-if="item.children">{{ item.children.length }}</el-tag>
                </div>
              </div>
              <!-- 子级权限列表 -->
              <div v-if="item.children" class="sub-permissions" v-show="item.expanded">
                <el-checkbox 
                  v-for="child in item.children" 
                  :key="child.id"
                  v-model="child.selected"
                  @change="(val) => handleSubPermissionChange(item, child, val)"
                >
                  {{ child.name }}
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      </el-form>
      </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 } from 'vue'
import { queryAll as queryAllMenu } from '@/api/safetyManagement/menuConfig.js'
import { ArrowRight, ArrowDown } from '@element-plus/icons-vue'

// 定义组件名称
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({
  realname: '',
  roleName: '',
  password: '',
  confirmPassword: '',
  email: '',
  userGroup: '',
  remark: '',
  isDisabled: false
})

// 表单校验规则
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: 1,
    name: '管理首页',
    selected: false,
    expanded: false,
    indeterminate: false
  },
  {
    id: 2,
    name: '项目管理',
    selected: false,
    expanded: false
  },
  {
    id: 3,
    name: '规则管理',
    selected: false,
    expanded: false,
    indeterminate: false,
    children: [
      { id: '3-1', name: '规则管理子项1', selected: false },
      { id: '3-2', name: '规则管理子项2', selected: false }
    ]
  },
  {
    id: 4,
    name: '资产库',
    selected: false
  },
  {
    id: 5,
    name: '系统设置',
    selected: false,
    expanded: false,
    indeterminate: false,
    children: [
      { id: '5-1', name: '设置子项1', selected: false },
      { id: '5-2', name: '设置子项2', selected: false }
    ]
  },
  {
    id: 6,
    name: '用户管理',
    selected: false,
    expanded: false,
    indeterminate: false,
    children: [
      { id: '6-1', name: '用户管理子项1', selected: false },
      { id: '6-2', name: '用户管理子项2', selected: false }
    ]
  }
])

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

// 监听props变化
watch(() => props.visible, (val) => {
  if (val && props.formData) {
    Object.assign(form, {
      ...props.formData,
      password: '',
      confirmPassword: ''
    })
  }
})

// 方法
const handleClose = () => {
  emit('update:visible', false)
  nextTick(() => {
    formRef.value?.resetFields()
    Object.assign(form, {
      realname: '',
      roleName: '',
      password: '',
      confirmPassword: '',
      email: '',
      userGroup: '',
      remark: '',
      isDisabled: false
    })
  })
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
      const params = { ...form }
      // 如果是编辑模式且没有修改密码，则不提交密码字段
      if (props.formData && !params.password) {
        delete params.password
        delete params.confirmPassword
      }
      
      console.log('submit form', params)
      // 调用接口保存数据
      emit('success')
      handleClose()
    }
  })
}

const handleSelectAll = (val) => {
  if (props.roles) {
    props.roles.forEach(role => {
      role.selected = val
    })
  }
}

const handleRoleSelect = (role, val) => {
  role.selected = val
  allSelected.value = props.roles?.every(role => role.selected) || false
}

const addSelected = () => {
  const selected = props.roles?.filter(role => role.selected) || []
  selectedRoles.value = [...new Set([...selectedRoles.value, ...selected])]
  // 这里应该更新props.roles，但由于是props，需要通过emit事件通知父组件更新
  allSelected.value = false
}

const removeSelected = () => {
  // 这里应该将selectedRoles添加回props.roles，但由于是props，需要通过emit事件通知父组件更新
  selectedRoles.value = []
}

const clearSelected = () => {
  // 这里应该将selectedRoles添加回props.roles，但由于是props，需要通过emit事件通知父组件更新
  selectedRoles.value = []
}

// 权限相关方法
const handleAllPermissionsChange = (val) => {
  // 处理全选
  permissionList.value.forEach(item => {
    item.selected = val
    if (item.children) {
      item.children.forEach(child => {
        child.selected = val
      })
    }
    item.indeterminate = false
  })
  allPermissionsSelected.value = val
}

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
  })
}

const toggleExpand = (item) => {
  // 展开/收起子菜单
  item.expanded = !item.expanded
}
</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>
