<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="groupname">
            <el-input v-model="form.groupname" 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="role-transfer">
          <div class="transfer-list">
            <div class="transfer-header">
              <span>角色列表</span>
              <el-checkbox v-model="allSelected" @change="handleSelectAll">全选</el-checkbox>
            </div>
            <el-input v-model="searchRole" placeholder="请输入搜索内容" />
            <div class="role-list">
              <div v-for="role in filteredRoles" :key="role.id" class="role-item">
                <el-checkbox 
                  v-model="role.selected"
                  @change="(val) => handleRoleSelect(role, val)"
                >
                  {{ role.name }}
                </el-checkbox>
              </div>
            </div>
          </div>
          <div class="transfer-operation">
            <el-button type="primary" plain icon="ArrowRight" @click="addSelected" />
            <el-button type="primary" plain icon="ArrowLeft" @click="removeSelected" />
          </div>
          <div class="transfer-list">
            <div class="transfer-header">
              <span>已选择角色列表</span>
              <el-button link type="primary" @click="clearSelected">清空</el-button>
            </div>
            <div class="selected-list">
              <div v-for="role in selectedRoles" :key="role.id" class="role-item">
                {{ role.name }}
              </div>
            </div>
          </div>
        </div>
      </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 }">
                    <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>
export default {
  name: 'GroupEdit',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => null
    }
  },
  emits: ['update:visible', 'success'],
  watch: {
    visible(val) {
      if (val && this.formData) {
        this.form = {
          ...this.formData,
          password: '',
          confirmPassword: ''
        }
      }
    }
  },
  data() {
    // 密码验证
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.form.confirmPassword !== '') {
          this.$refs.formRef.validateField('confirmPassword')
        }
        callback()
      }
    }
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      form: {
        groupname: '',
        remark: '',
      },
      rules: {
        groupname: [
          { required: true, message: '请输入用户组名', trigger: 'blur' }
        ]
      },
      allSelected: false,
      searchRole: '',
      roles: [
        { id: 1, name: '系统管理员', selected: false },
        { id: 2, name: '2222', selected: false }
      ],
      selectedRoles: [],
      allPermissionsSelected: false,
      permissionList: [
        {
          id: 1,
          name: '管理首页',
          selected: false,
          expanded: false,
          indeterminate: false
        },
        {
          id: 2,
          name: '项目管理',
          selected: false,
          expanded: false
        },
        {
          id: 3,
          name: '规则管理',
          selected: 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,
          children: [
            { id: '5-1', name: '设置子项1', selected: false },
            { id: '5-2', name: '设置子项2', selected: false }
          ]
        },
        {
          id: 6,
          name: '用户组管理',
          selected: false,
          children: [
            { id: '6-1', name: '用户组管理子项1', selected: false },
            { id: '6-2', name: '用户组管理子项2', selected: false }
          ]
        }
      ]
    }
  },
  computed: {
    filteredRoles() {
      return this.roles.filter(role => 
        role.name.toLowerCase().includes(this.searchRole.toLowerCase())
      )
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
      this.$refs.formRef?.resetFields()
      this.form = {
        realname: '',
        groupname: '',
        password: '',
        confirmPassword: '',
        email: '',
        userGroup: '',
        remark: '',
        isDisabled: false
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 提交表单逻辑
          const params = { ...this.form }
          // 如果是编辑模式且没有修改密码，则不提交密码字段
          if (this.formData && !params.password) {
            delete params.password
            delete params.confirmPassword
          }
          
          console.log('submit form', params)
          // 调用接口保存数据
          this.$emit('success')
          this.handleClose()
        }
      })
    },
    handleSelectAll(val) {
      this.roles.forEach(role => {
        role.selected = val
      })
    },
    handleRoleSelect(role, val) {
      role.selected = val
      this.allSelected = this.roles.every(role => role.selected)
    },
    addSelected() {
      const selectedRoles = this.roles.filter(role => role.selected)
      this.selectedRoles = [...new Set([...this.selectedRoles, ...selectedRoles])]
      this.roles = this.roles.filter(role => !role.selected)
      this.allSelected = false
    },
    removeSelected() {
      this.roles = [...this.roles, ...this.selectedRoles]
      this.selectedRoles = []
    },
    clearSelected() {
      this.roles = [...this.roles, ...this.selectedRoles]
      this.selectedRoles = []
    },
    // 权限相关方法
    handleAllPermissionsChange(val) {
      // 处理全选
      this.permissionList.forEach(item => {
        item.selected = val
        if (item.children) {
          item.children.forEach(child => {
            child.selected = val
          })
        }
      })
    },
    handlePermissionChange(item, val) {
      // 处理父级权限选择
      item.selected = val
      item.indeterminate = false // 清除半选状态
      if (item.children) {
        item.children.forEach(child => {
          child.selected = val
        })
      }
      this.checkAllPermissionsStatus()
    },
    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
      }
      this.checkAllPermissionsStatus()
    },
    checkAllPermissionsStatus() {
      // 检查是否全部选中
      this.allPermissionsSelected = this.permissionList.every(item => {
        if (item.children) {
          return item.selected && item.children.every(child => child.selected)
        }
        return item.selected
      })
    },
    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;

  .all-select {
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
  }

  .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>
