<template>
  <div class="data-permission-manage">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Setting /></el-icon>
            <span>数据权限管理</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddType">
              <el-icon><Plus /></el-icon>
              新增权限类型
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card" class="permission-manage-tabs">
        <!-- 权限类型管理 -->
        <el-tab-pane label="权限类型管理" name="types">
          <div class="types-manage">
            <div class="table-header">
              <el-form :model="typeQuery" inline class="search-form">
                <el-form-item label="类型名称">
                  <el-input
                    v-model="typeQuery.typeName"
                    placeholder="请输入权限类型名称"
                    clearable
                    @keyup.enter="loadPermissionTypes"
                  />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="typeQuery.status" placeholder="请选择状态" clearable>
                    <el-option label="正常" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="loadPermissionTypes">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetTypeQuery">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table v-loading="typesLoading" :data="permissionTypes" stripe border>
              <el-table-column label="类型ID" prop="typeId" width="80" align="center" />
              <el-table-column label="权限类型编码" prop="typeCode" width="150" />
              <el-table-column label="权限类型名称" prop="typeName" width="150" />
              <el-table-column label="描述" prop="description" show-overflow-tooltip />
              <el-table-column label="状态" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                    {{ row.status === '0' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="sortOrder" width="80" align="center" />
              <el-table-column label="创建时间" prop="createTime" width="160" />
              <el-table-column label="操作" width="200" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleEditType(row)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button type="success" link @click="handleManageValues(row)">
                    <el-icon><List /></el-icon>
                    管理权限值
                  </el-button>
                  <el-button type="danger" link @click="handleDeleteType(row)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 权限值管理 -->
        <el-tab-pane label="权限值管理" name="values" :disabled="!selectedTypeId">
          <div class="values-manage">
            <div class="values-header">
              <div class="type-info">
                <el-tag type="primary" size="large">
                  {{ selectedTypeName }}
                </el-tag>
                <span class="type-desc">权限值管理</span>
              </div>
              <div class="header-actions">
                <el-button type="primary" @click="handleAddValue">
                  <el-icon><Plus /></el-icon>
                  新增权限值
                </el-button>
                <el-button @click="activeTab = 'types'">
                  <el-icon><Back /></el-icon>
                  返回类型管理
                </el-button>
              </div>
            </div>

            <div class="table-header">
              <el-form :model="valueQuery" inline class="search-form">
                <el-form-item label="权限值名称">
                  <el-input
                    v-model="valueQuery.valueName"
                    placeholder="请输入权限值名称"
                    clearable
                    @keyup.enter="loadPermissionValues"
                  />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="valueQuery.status" placeholder="请选择状态" clearable>
                    <el-option label="正常" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="loadPermissionValues">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetValueQuery">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table
              v-loading="valuesLoading"
              :data="permissionValues"
              stripe
              border
              row-key="valueId"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            >
              <el-table-column label="权限值名称" prop="valueName" min-width="200" />
              <el-table-column label="权限值编码" prop="valueCode" width="150" />
              <el-table-column label="层级" width="80" align="center">
                <template #default="{ row }">
                  <el-tag size="small">{{ getNodeLevel(row) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === '0' ? 'success' : 'danger'" size="small">
                    {{ row.status === '0' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="sortOrder" width="80" align="center" />
              <el-table-column label="创建时间" prop="createTime" width="160" />
              <el-table-column label="操作" width="160" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link size="small" @click="handleEditValue(row)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button type="success" link size="small" @click="handleAddChildValue(row)">
                    <el-icon><Plus /></el-icon>
                    添加子级
                  </el-button>
                  <el-button type="danger" link size="small" @click="handleDeleteValue(row)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 权限类型表单对话框 -->
    <el-dialog
      v-model="typeFormVisible"
      :title="typeFormMode === 'add' ? '新增权限类型' : '编辑权限类型'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="typeFormRef" :model="typeForm" :rules="typeRules" label-width="120px">
        <el-form-item label="类型ID" prop="typeId">
          <el-input-number
            v-model="typeForm.typeId"
            :min="1"
            :max="15"
            :disabled="typeFormMode === 'edit'"
            placeholder="请输入类型ID(1-15)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="权限类型编码" prop="typeCode">
          <el-input v-model="typeForm.typeCode" placeholder="请输入权限类型编码" />
        </el-form-item>
        <el-form-item label="权限类型名称" prop="typeName">
          <el-input v-model="typeForm.typeName" placeholder="请输入权限类型名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="typeForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="typeForm.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="typeForm.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="typeFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="typeFormLoading" @click="handleSaveType">
          确 定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限值表单对话框 -->
    <el-dialog
      v-model="valueFormVisible"
      :title="getValueFormTitle()"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="valueFormRef" :model="valueForm" :rules="valueRules" label-width="120px">
        <el-form-item label="上级权限值">
          <el-tree-select
            v-model="valueForm.parentId"
            :data="parentValueOptions"
            :props="{ value: 'valueId', label: 'valueName', children: 'children' }"
            placeholder="请选择上级权限值（可选）"
            clearable
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="权限值编码" prop="valueCode">
          <el-input v-model="valueForm.valueCode" placeholder="请输入权限值编码" />
        </el-form-item>
        <el-form-item label="权限值名称" prop="valueName">
          <el-input v-model="valueForm.valueName" placeholder="请输入权限值名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="valueForm.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="valueForm.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="valueFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="valueFormLoading" @click="handleSaveValue">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, ref } from 'vue';
import api from '@/api/system/userDataPermission';
import {
  DataPermissionTypeVO,
  DataPermissionValueVO,
  DataPermissionQuery,
  DataPermissionValueQuery,
  convertToTree
} from '@/api/system/userDataPermission/types';

// ======================== 基础设置 ========================
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// ======================== 响应式数据 ========================
const activeTab = ref('types');
const selectedTypeId = ref<number>();
const selectedTypeName = ref<string>('');

// 权限类型相关
const permissionTypes = ref<DataPermissionTypeVO[]>([]);
const typesLoading = ref(false);
const typeQuery = reactive<DataPermissionQuery>({
  typeName: '',
  status: ''
});

// 权限值相关
const permissionValues = ref<DataPermissionValueVO[]>([]);
const valuesLoading = ref(false);
const valueQuery = reactive<DataPermissionValueQuery>({
  valueName: '',
  status: ''
});

// 表单相关
const typeFormVisible = ref(false);
const typeFormMode = ref<'add' | 'edit'>('add');
const typeFormLoading = ref(false);
const typeFormRef = ref();

const valueFormVisible = ref(false);
const valueFormMode = ref<'add' | 'edit' | 'addChild'>('add');
const valueFormLoading = ref(false);
const valueFormRef = ref();

// 表单数据
const typeForm = reactive({
  typeId: undefined,
  typeCode: '',
  typeName: '',
  description: '',
  status: '0',
  sortOrder: 0
});

const valueForm = reactive({
  valueId: undefined,
  typeId: undefined,
  parentId: 0,
  valueCode: '',
  valueName: '',
  status: '0',
  sortOrder: 0
});

// 父级选项
const parentValueOptions = computed(() => {
  return convertToTree(permissionValues.value.filter(v => v.valueId !== valueForm.valueId));
});

// ======================== 表单验证规则 ========================
const typeRules = {
  typeId: [{ required: true, message: '请输入类型ID', trigger: 'blur' }],
  typeCode: [{ required: true, message: '请输入权限类型编码', trigger: 'blur' }],
  typeName: [{ required: true, message: '请输入权限类型名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

const valueRules = {
  valueCode: [{ required: true, message: '请输入权限值编码', trigger: 'blur' }],
  valueName: [{ required: true, message: '请输入权限值名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// ======================== 方法 ========================
// 获取节点层级
const getNodeLevel = (node: DataPermissionValueVO): number => {
  let level = 1;
  let parent = permissionValues.value.find(v => v.valueId === node.parentId);
  while (parent && parent.parentId !== 0) {
    level++;
    parent = permissionValues.value.find(v => v.valueId === parent!.parentId);
  }
  return level;
};

// 获取权限值表单标题
const getValueFormTitle = (): string => {
  switch (valueFormMode.value) {
    case 'add':
      return '新增权限值';
    case 'edit':
      return '编辑权限值';
    case 'addChild':
      return '添加子级权限值';
    default:
      return '权限值管理';
  }
};

// 加载权限类型
const loadPermissionTypes = async () => {
  try {
    typesLoading.value = true;
    const res = await api.listDataPermissionTypes();
    permissionTypes.value = res.data;
  } catch (error) {
    proxy?.$modal.msgError('加载权限类型失败');
  } finally {
    typesLoading.value = false;
  }
};

// 加载权限值
const loadPermissionValues = async () => {
  if (!selectedTypeId.value) return;

  try {
    valuesLoading.value = true;
    const res = await api.listDataPermissionValues(selectedTypeId.value);
    permissionValues.value = res.data;
  } catch (error) {
    proxy?.$modal.msgError('加载权限值失败');
  } finally {
    valuesLoading.value = false;
  }
};

// 重置查询条件
const resetTypeQuery = () => {
  Object.assign(typeQuery, {
    typeName: '',
    status: ''
  });
  loadPermissionTypes();
};

const resetValueQuery = () => {
  Object.assign(valueQuery, {
    valueName: '',
    status: ''
  });
  loadPermissionValues();
};

// 权限类型操作
const handleAddType = () => {
  Object.assign(typeForm, {
    typeId: undefined,
    typeCode: '',
    typeName: '',
    description: '',
    status: '0',
    sortOrder: 0
  });
  typeFormMode.value = 'add';
  typeFormVisible.value = true;
};

const handleEditType = (row: DataPermissionTypeVO) => {
  Object.assign(typeForm, { ...row });
  typeFormMode.value = 'edit';
  typeFormVisible.value = true;
};

const handleDeleteType = async (row: DataPermissionTypeVO) => {
  try {
    await proxy?.$modal.confirm(`确定删除权限类型"${row.typeName}"吗？`);
    await api.deleteDataPermissionType(row.typeId);
    proxy?.$modal.msgSuccess('删除成功');
    loadPermissionTypes();
  } catch (error) {
  }
};

const handleManageValues = (row: DataPermissionTypeVO) => {
  selectedTypeId.value = row.typeId;
  selectedTypeName.value = row.typeName;
  activeTab.value = 'values';
  loadPermissionValues();
};

const handleSaveType = async () => {
  try {
    await typeFormRef.value?.validate();
    typeFormLoading.value = true;

    if (typeFormMode.value === 'add') {
      await api.addDataPermissionType(typeForm);
      proxy?.$modal.msgSuccess('新增成功');
    } else {
      await api.updateDataPermissionType(typeForm as DataPermissionTypeVO);
      proxy?.$modal.msgSuccess('修改成功');
    }

    typeFormVisible.value = false;
    loadPermissionTypes();
  } catch (error) {
    proxy?.$modal.msgError('保存失败');
  } finally {
    typeFormLoading.value = false;
  }
};

// 权限值操作
const handleAddValue = () => {
  Object.assign(valueForm, {
    valueId: undefined,
    typeId: selectedTypeId.value,
    parentId: 0,
    valueCode: '',
    valueName: '',
    status: '0',
    sortOrder: 0
  });
  valueFormMode.value = 'add';
  valueFormVisible.value = true;
};

const handleEditValue = (row: DataPermissionValueVO) => {
  Object.assign(valueForm, { ...row });
  valueFormMode.value = 'edit';
  valueFormVisible.value = true;
};

const handleAddChildValue = (row: DataPermissionValueVO) => {
  Object.assign(valueForm, {
    valueId: undefined,
    typeId: selectedTypeId.value,
    parentId: row.valueId,
    valueCode: '',
    valueName: '',
    status: '0',
    sortOrder: 0
  });
  valueFormMode.value = 'addChild';
  valueFormVisible.value = true;
};

const handleDeleteValue = async (row: DataPermissionValueVO) => {
  try {
    await proxy?.$modal.confirm(`确定删除权限值"${row.valueName}"吗？`);
    await api.deleteDataPermissionValue(row.valueId);
    proxy?.$modal.msgSuccess('删除成功');
    loadPermissionValues();
  } catch (error) {
  }
};

const handleSaveValue = async () => {
  try {
    await valueFormRef.value?.validate();
    valueFormLoading.value = true;

    if (valueFormMode.value === 'edit') {
      await api.updateDataPermissionValue(valueForm as DataPermissionValueVO);
      proxy?.$modal.msgSuccess('修改成功');
    } else {
      await api.addDataPermissionValue(valueForm);
      proxy?.$modal.msgSuccess('新增成功');
    }

    valueFormVisible.value = false;
    loadPermissionValues();
  } catch (error) {
    proxy?.$modal.msgError('保存失败');
  } finally {
    valueFormLoading.value = false;
  }
};

// ======================== 生命周期 ========================
onMounted(() => {
  loadPermissionTypes();
});
</script>

<style lang="scss" scoped>
.data-permission-manage {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .permission-manage-tabs {
    .types-manage,
    .values-manage {
      .table-header {
        margin-bottom: 16px;

        .search-form {
          margin-bottom: 0;
        }
      }
    }

    .values-manage {
      .values-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding: 16px;
        background: #f5f7fa;
        border-radius: 6px;

        .type-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .type-desc {
            color: #606266;
            font-size: 14px;
          }
        }

        .header-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .data-permission-manage {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }

    .values-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;

      .header-actions {
        align-self: stretch;

        .el-button {
          flex: 1;
        }
      }
    }

    .search-form {
      .el-form-item {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
