<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <el-table
        ref="productCategoryTableRef"
        v-loading="loading"
        :data="productCategoryList"
        row-key="id"
        border
      >
        <el-table-column prop="parentCategoryName" label="分类名称" min-width="600">
        <template #default="scope">
            <span >{{ scope.row.parentCategoryName +"-"+ scope.row.categoryName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="discountRate" align="center" label="折扣率" width="600">
          <template #default="scope">
            <span v-if="scope.row.discountRate">{{ (scope.row.discountRate * 100).toFixed(2) }}%</span>
            <span v-else class="text-gray-400">未设置</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="300">
          <template #default="scope">
            <el-tooltip content="修改折扣率" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改折扣率对话框 -->
    <el-dialog v-model="dialog.visible" title="修改折扣率" destroy-on-close append-to-body width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="form.categoryName" disabled />
        </el-form-item>
        <el-form-item label="折扣率" prop="discountRate">
          <el-input-number
            v-model="form.discountRate"
            :precision="4"
            :min="0"
            :max="1"
            :step="0.01"
            :controls="false"
            style="width: 200px"
          />
          <span class="ml-2 text-gray-500">{{ form.discountRate ? (form.discountRate * 100).toFixed(2) + '%' : '0%' }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductCategoryDiscountRate" lang="ts">
import { listProductCategory, getProductCategory, updateProductCategory } from '@/api/external/productCategory';
import { ProductCategoryVO, ProductCategoryQuery, ProductCategoryDiscountForm } from '@/api/external/productCategory/types';
import cache from '@/plugins/cache';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productCategoryList = ref<ProductCategoryVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);

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

const productCategoryTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();

const initFormData: ProductCategoryDiscountForm = {
  id: undefined,
  itemId: undefined,
  categoryName: undefined,
  discountRate: undefined
};

const data = reactive<PageData<ProductCategoryDiscountForm, Partial<ProductCategoryQuery>>>({
  form: { ...initFormData },
  queryParams: {
    categoryName: undefined,
    itemId: undefined
  },
  rules: {
    discountRate: [
      { required: true, message: '折扣率不能为空', trigger: 'blur' }
    ]
  }
});

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

/** 查询产品分类列表（只加载三级分类） */
const getList = async () => {
  loading.value = true;
  // 只加载三级分类（classLevel = 3）
  const params = {
    ...queryParams.value,
    classLevel: 3
  };
  const res = await listProductCategory(params);
  const responseData = (res as any).rows || res.data || [];
  productCategoryList.value = responseData;
  loading.value = false;
};

/** 初始化项目Key（从缓存获取） */
const initProjectKey = () => {
  const currentProject = cache.local.getJSON('currentProject');
  if (currentProject && currentProject.id) {
    queryParams.value.itemId = currentProject.id;
  }
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 修改按钮操作 */
const handleUpdate = async (row: ProductCategoryVO) => {
  reset();
  const res = await getProductCategory(row.id, queryParams.value.itemId?.toString());
  form.value = {
    id: res.data.id,
    itemId: res.data.itemId,
    categoryName: res.data.categoryName,
    discountRate: res.data.discountRate ?? undefined
  };
  dialog.visible = true;
  dialog.title = '修改折扣率';
};

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await updateProductCategory({
        id: form.value.id,
        itemId: form.value.itemId,
        discountRate: form.value.discountRate
      } as any);
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

onMounted(() => {
  // 从缓存获取项目Key并初始化
  initProjectKey();
  if (queryParams.value.itemId) {
    getList();
  }
});
</script>
