<template>
  <div class="page-container">
    <el-row :gutter="16" class="full-height">
      <!-- 左侧字典类型 -->
      <el-col :span="6" class="full-height">
        <el-card shadow="never" class="type-card full-height">
          <template #header>
            <div class="card-header">
              <span class="title">字典类型</span>
              <el-button link type="primary" icon="Plus" @click="handleAddType()" v-hasPermi="['system:dict:addType']">新增</el-button>
            </div>
            <div class="search-box">
              <el-input v-model="typeSearch" placeholder="搜索类型名称/编码" prefix-icon="Search" clearable />
            </div>
          </template>

          <el-scrollbar>
            <div v-for="item in filteredTypeList" :key="item.dictId" :class="['type-item', { active: activeType?.dictId === item.dictId }]" @click="handleTypeClick(item)">
              <div class="type-info">
                <div class="type-name">{{ item.dictName }}</div>
                <div class="type-code">{{ item.dictType }}</div>
              </div>
              <div class="type-ops">
                <el-button link type="primary" icon="Edit" @click.stop="handleUpdateType(item)" v-hasPermi="['system:dict:editType']"></el-button>
                <el-button link type="danger" icon="Delete" @click.stop="handleDeleteType(item)" v-hasPermi="['system:dict:removeType']"></el-button>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧字典数据 -->
      <el-col :span="18" class="full-height">
        <el-card shadow="never" class="table-card full-height">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span class="title">{{ activeType?.dictName }}</span>
                <el-tag size="small" type="info" class="ml8">{{ activeType?.dictType }}</el-tag>
              </div>
              <div class="header-right">
                <el-button type="primary" icon="Plus" @click="handleAddData()" v-hasPermi="['system:dict:addData']">新增数据</el-button>
              </div>
            </div>
          </template>

          <el-table v-loading="dataLoading" :data="dataList" style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
            <el-table-column label="字典标签" prop="dictLabel" min-width="120" />
            <el-table-column label="字典键值" prop="dictValue" min-width="120" />
            <el-table-column label="排序" prop="dictSort" width="80" align="center" />
            <el-table-column label="备注" prop="remark" min-width="150" :show-overflow-tooltip="true" />
            <el-table-column label="操作" width="160" align="right" fixed="right">
              <template #default="scope">
                <div class="op-btns">
                  <el-button link type="primary" @click="handleUpdateData(scope.row)" v-hasPermi="['system:dict:editData']">编辑</el-button>
                  <el-button link type="danger" @click="handleDeleteData(scope.row)" v-hasPermi="['system:dict:removeData']">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 字典类型对话框 -->
    <el-dialog v-model="typeDialog.visible" :title="typeDialog.title" width="450px" append-to-body>
      <el-form ref="typeFormRef" :model="typeForm" :rules="typeRules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="typeForm.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="typeForm.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="typeForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTypeForm">确 定</el-button>
          <el-button @click="typeDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 字典数据对话框 -->
    <el-dialog v-model="dataDialog.visible" :title="dataDialog.title" width="500px" append-to-body>
      <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="dataForm.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="dataForm.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataForm">确 定</el-button>
          <el-button @click="dataDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dict" lang="ts">
import { listType, getType, delType, addType, updateType } from '@/api/system/dict/type';
import { listData, getData, delData, addData, updateData } from '@/api/system/dict/data';
import { DictTypeForm, DictTypeVO } from '@/api/system/dict/type/types';
import { DictDataForm, DictDataVO } from '@/api/system/dict/data/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

// 字典类型相关
const typeList = ref<DictTypeVO[]>([]);
const activeType = ref<DictTypeVO | null>(null);
const typeSearch = ref('');
const typeLoading = ref(false);
const typeDialog = reactive({ visible: false, title: '' });
const typeFormRef = ref<ElFormInstance>();
const typeForm = ref<DictTypeForm>({
  dictId: undefined,
  dictName: '',
  dictType: '',
  remark: ''
});
const typeRules = {
  dictName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  dictType: [{ required: true, message: '编码不能为空', trigger: 'blur' }]
};

// 字典数据相关
const dataList = ref<DictDataVO[]>([]);
const dataLoading = ref(false);
const dataDialog = reactive({ visible: false, title: '' });
const dataFormRef = ref<ElFormInstance>();
const dataForm = ref<DictDataForm>({
  dictCode: undefined,
  dictLabel: '',
  dictValue: '',
  dictSort: 0,
  status: '0',
  remark: '',
  dictType: ''
});
const dataRules = {
  dictLabel: [{ required: true, message: '标签不能为空', trigger: 'blur' }],
  dictValue: [{ required: true, message: '键值不能为空', trigger: 'blur' }]
};

const filteredTypeList = computed(() => {
  if (!typeSearch.value) return typeList.value;
  return typeList.value.filter(item => 
    item.dictName.includes(typeSearch.value) || 
    item.dictType.includes(typeSearch.value)
  );
});

// 获取字典类型列表
const getTypeList = async () => {
  typeLoading.value = true;
  const res = await listType({ pageNum: 1, pageSize: 100 } as any);
  typeList.value = res.rows;
  typeLoading.value = false;
  if (!activeType.value && typeList.value.length > 0) {
    handleTypeClick(typeList.value[0]);
  }
};

// 点击字典类型
const handleTypeClick = (item: DictTypeVO) => {
  activeType.value = item;
  getDataList();
};

// 获取字典数据列表
const getDataList = async () => {
  if (!activeType.value) return;
  dataLoading.value = true;
  const res = await listData({ 
    pageNum: 1, 
    pageSize: 100, 
    dictType: activeType.value.dictType 
  } as any);
  dataList.value = res.rows;
  dataLoading.value = false;
};

// 字典类型操作
const handleAddType = () => {
  typeForm.value = { dictId: undefined, dictName: '', dictType: '', remark: '' };
  typeDialog.title = '添加字典类型';
  typeDialog.visible = true;
};
const handleUpdateType = async (item: DictTypeVO) => {
  const res = await getType(item.dictId);
  typeForm.value = res.data;
  typeDialog.title = '修改字典类型';
  typeDialog.visible = true;
};
const handleDeleteType = async (item: DictTypeVO) => {
  await proxy?.$modal.confirm(`确认删除字典类型"${item.dictName}"吗？`);
  await delType(item.dictId);
  if (activeType.value?.dictId === item.dictId) activeType.value = null;
  proxy?.$modal.msgSuccess('删除成功');
  getTypeList();
};
const submitTypeForm = () => {
  typeFormRef.value?.validate(async (valid) => {
    if (valid) {
      typeForm.value.dictId ? await updateType(typeForm.value) : await addType(typeForm.value);
      proxy?.$modal.msgSuccess('操作成功');
      typeDialog.visible = false;
      getTypeList();
    }
  });
};

// 字典数据操作
const handleAddData = () => {
  dataForm.value = {
    dictCode: undefined,
    dictLabel: '',
    dictValue: '',
    dictSort: 0,
    status: '0',
    remark: '',
    dictType: activeType.value?.dictType || ''
  };
  dataDialog.title = '添加字典数据';
  dataDialog.visible = true;
};
const handleUpdateData = async (item: DictDataVO) => {
  const res = await getData(item.dictCode);
  Object.assign(dataForm.value, res.data);
  dataDialog.title = '修改字典数据';
  dataDialog.visible = true;
};
const handleDeleteData = async (item: DictDataVO) => {
  await proxy?.$modal.confirm('确认删除吗？');
  await delData(item.dictCode);
  proxy?.$modal.msgSuccess('删除成功');
  getDataList();
};
const submitDataForm = () => {
  dataFormRef.value?.validate(async (valid) => {
    if (valid) {
      dataForm.value.dictCode ? await updateData(dataForm.value) : await addData(dataForm.value);
      proxy?.$modal.msgSuccess('操作成功');
      dataDialog.visible = false;
      getDataList();
    }
  });
};

onMounted(() => {
  getTypeList();
});
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background-color: #f5f7f9;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.full-height {
  height: 100%;
}

.type-card {
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__header) {
    padding: 16px;
    border-bottom: none;
  }
  
  :deep(.el-card__body) {
    padding: 0;
    flex: 1;
    overflow: hidden;
  }
}

.table-card {
  :deep(.el-card__header) {
    padding: 18px 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .header-left {
    display: flex;
    align-items: center;
  }
  
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.search-box {
  margin-top: 12px;
  
  :deep(.el-input__wrapper) {
    background-color: #f4f5f7;
    box-shadow: none;
  }
}

.type-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 3px solid transparent;

  &:hover {
    background-color: #f0f7ff;
    
    .type-ops {
      display: flex;
    }
  }

  &.active {
    background-color: #e6f1fc;
    border-left-color: #409eff;
    
    .type-name {
      color: #409eff;
    }
  }
}

.type-info {
  flex: 1;
  overflow: hidden;
  
  .type-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
  }
  
  .type-code {
    font-size: 12px;
    color: #909399;
  }
}

.type-ops {
  display: none;
  gap: 4px;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  
  .el-button {
    font-weight: 400;
  }
}

.ml8 {
  margin-left: 8px;
}

:deep(.el-table) {
  --el-table-border-color: #f0f0f0;
  
  th.el-table__cell {
    font-weight: 600;
  }
}
</style>
