<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">商户分类管理</span>
          </div>
          <div class="header-right">
            <el-input
              v-model="queryParams.name"
              placeholder="搜索分类名称"
              class="search-input"
              prefix-icon="Search"
              clearable
              @keyup.enter="handleQuery"
            />
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:tenantCategories:add']">新增分类</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="tenantCategoriesList" style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
        <el-table-column label="分类名称" prop="name" min-width="200" />
        <el-table-column label="图标" align="center" width="120">
          <template #default="scope">
            <div class="icon-wrapper">
              <image-preview :src="scope.row.iconUrl" :width="40" :height="40" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="120" />
        <el-table-column label="状态" align="center" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'" size="small" effect="light" class="status-tag">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" width="140" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:tenantCategories:edit']">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['system:tenantCategories:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <pagination
          v-show="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 添加或修改商户分类对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="tenantCategoriesFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <image-upload v-model="form.icon" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TenantCategories" lang="ts">
import {
  listTenantCategories,
  getTenantCategories,
  delTenantCategories,
  addTenantCategories,
  updateTenantCategories
} from '@/api/system/tenantCategories';
import { TenantCategoriesVO, TenantCategoriesQuery, TenantCategoriesForm } from '@/api/system/tenantCategories/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tenantCategoriesList = ref<TenantCategoriesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tenantCategoriesFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TenantCategoriesForm = {
  id: undefined,
  name: undefined,
  sort: 0,
  icon: undefined,
  status: true
};
const data = reactive<PageData<TenantCategoriesForm, TenantCategoriesQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: undefined,
    params: {
      createTime: undefined,
      updateTime: undefined
    }
  },
  rules: {
    name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商户分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenantCategories(queryParams.value);
  tenantCategoriesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 处理更多菜单命令 */
const handleCommand = (command: string, row: TenantCategoriesVO) => {
  if (command === 'delete') {
    handleDelete(row);
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  tenantCategoriesFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加商户分类';
};

/** 修改按钮操作 */
const handleUpdate = async (row: TenantCategoriesVO) => {
  reset();
  const res = await getTenantCategories(row.id);
  Object.keys(initFormData).forEach((key) => {
    form.value[key] = res.data[key];
  });
  dialog.visible = true;
  dialog.title = '修改商户分类';
};

/** 提交按钮 */
const submitForm = () => {
  tenantCategoriesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTenantCategories(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenantCategories(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: TenantCategoriesVO) => {
  await proxy?.$modal.confirm(`是否确认删除分类"${row.name}"？`);
  loading.value = true;
  await delTenantCategories(row.id).finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background-color: #f5f7f9;
  min-height: 100%;
}

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.header-right {
  display: flex;
  gap: 12px;
  
  .search-input {
    width: 240px;
    
    :deep(.el-input__wrapper) {
      background-color: #f4f5f7;
      box-shadow: none;
      border: 1px solid transparent;
      
      &:hover, &.is-focus {
        border-color: #409eff;
        background-color: #fff;
      }
    }
  }
}

.icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.status-tag {
  border: none;
  font-weight: 500;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 16px;

  .more-btn {
    display: flex;
    align-items: center;
    color: #409eff;
  }
}

.delete-item {
  color: #f56c6c !important;
  &:hover {
    color: #f56c6c !important;
    background-color: #fef0f0 !important;
  }
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

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