<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="productAttributesName">
              <el-input v-model="queryParams.productAttributesName" placeholder="请输入属性名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品类别" prop="categoryId">
              <el-tree-select
                v-model="queryParams.categoryId"
                :data="categoryOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                check-strictly
                :render-after-expand="false"
                show-checkbox
                :check-on-click-node="true"
                node-key="id"
                clearable
                placeholder="请选择商品类别"
              >
                <template #default="{ data }">
                  <span>{{ getCategoryFullPath(data.id) }}</span>
                </template>
              </el-tree-select>
            </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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['product:attributes:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['product:attributes:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['product:attributes:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['product:attributes:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="attributesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" width="120" />
        <el-table-column label="属性名称" align="center" prop="productAttributesName" />
        <el-table-column label="商品类别" align="center" prop="categoryId" min-width="200">
          <template #default="scope">
            <span>{{ getCategoryFullPath(scope.row.categoryId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="属性是否可选" align="center" prop="isOptional" width="120">
          <template #default="scope">
            <dict-tag :options="[
              { label: '是', value: '1' },
              { label: '否', value: '0' }
            ]" :value="String(scope.row.isOptional)" />
          </template>
        </el-table-column>
        <el-table-column label="属性值的输入方式" align="center" prop="entryMethod" width="140">
          <template #default="scope">
            <dict-tag :options="[
              { label: '唯一属性', value: '1' },
              { label: '单选属性', value: '0' },
              { label: '复选属性', value: '2' }
            ]" :value="String(scope.row.entryMethod)" />
          </template>
        </el-table-column>
        <el-table-column label="可选值列表" align="center" prop="attributesList" show-overflow-tooltip />
        <el-table-column label="是否必填" align="center" prop="required" width="100">
          <template #default="scope">
            <dict-tag :options="[
              { label: '是', value: '1' },
              { label: '否', value: '0' }
            ]" :value="String(scope.row.required)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:attributes:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['product:attributes:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
   <!-- 添加或修改产品属性定义（用于动态属性配置）对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="650px" append-to-body>
      <el-form ref="attributesFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="属性名称" prop="productAttributesName">
          <el-input v-model="form.productAttributesName" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="关联类别" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="categoryOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            check-strictly
            :render-after-expand="false"
            clearable
            placeholder="请选择关联类别（必须选择第三级）"
          >
            <template #default="{ node, data }">
              <span :style="{ color: !node.isLeaf && node.level < 3 ? '#999' : '' }">
                {{ getCategoryFullPath(data.id) }}
              </span>
            </template>
          </el-tree-select>
        </el-form-item>
        <el-form-item label="是否可选" prop="isOptional">
          <el-radio-group v-model="form.isOptional">
            <el-radio :value="1">唯一属性</el-radio>
            <el-radio :value="0">单选属性</el-radio>
            <el-radio :value="2">复选属性</el-radio>
          </el-radio-group>
          <div class="text-gray-500 text-sm mt-2">
            选择"单选/复选属性"时，可以对商品属性设置多个值，同时还能对不同属性值设定不同的价格，用户购买商品时需要选择具体的属性值后才能加入购物车。用户购买商品时需要先选择具体的属性值。选择"唯一属性"时，商品的该属性值只能是唯一一个值，用户只能查看具体的属性值。
          </div>
        </el-form-item>
        <el-form-item label="录入方式" prop="entryMethod">
          <el-radio-group v-model="form.entryMethod">
            <el-radio value="1">手工录入</el-radio>
            <el-radio value="2">从下面的列表中选择</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="加入筛选" prop="isFilter">
          <el-radio-group v-model="form.isFilter">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-radio-group v-model="form.required">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可选值列表" prop="attributesList" v-if="form.entryMethod === 'select'">
          <el-input 
            v-model="form.attributesList" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入属性值，各属性值请用逗号隔开并来示意。例如：A4,70g,100g" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Attributes" lang="ts">
import { listAttributes, getAttributes, delAttributes, addAttributes, updateAttributes } from '@/api/pmsProduct/attributes';
import { AttributesVO, AttributesQuery, AttributesForm } from '@/api/pmsProduct/attributes/types';
import { categoryTree } from '@/api/pmsProduct/base';
import { categoryTreeVO } from '@/api/pmsProduct/category/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

const attributesList = ref<AttributesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const categoryOptions = ref<categoryTreeVO[]>([]);

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

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

const initFormData: AttributesForm = {
  id: undefined,
  categoryId: undefined,
  productAttributesCode: undefined,
  productAttributesName: undefined,
  isOptional: 1,
  entryMethod: '1',
  isFilter: 1,
  attributesList: undefined,
  required: 0,
  remark: undefined,
}
const data = reactive<PageData<AttributesForm, AttributesQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    productAttributesCode: undefined,
    productAttributesName: undefined,
    isOptional: undefined,
    entryMethod: undefined,
    isFilter: undefined,
    attributesList: undefined,
    required: undefined,
    platformCode: undefined,
    params: {
    }
  },
  rules: {
    categoryId: [
      { required: true, message: "商品类别不能为空", trigger: "change" },
      { 
        validator: (rule: any, value: any, callback: any) => {
          if (!value) {
            callback();
            return;
          }
          // 检查是否为第三级类别
          const isThirdLevel = checkIsThirdLevel(value);
          if (!isThirdLevel) {
            callback(new Error('请选择第三级类别'));
          } else {
            callback();
          }
        },
        trigger: "change"
      }
    ],
    productAttributesCode: [
      { required: true, message: "属性编码不能为空", trigger: "blur" }
    ],
    productAttributesName: [
      { required: true, message: "属性名称不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询产品属性定义（用于动态属性配置）列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAttributes(queryParams.value);
  attributesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询分类树 */
const getCategoryTree = async () => {
  const res = await categoryTree();
  categoryOptions.value = res.data || [];
  // 设置默认选中第一项
  if (categoryOptions.value.length > 0) {
    setDefaultCategory();
  }
}

/** 设置默认类别（选择第一个一级分类） */
const setDefaultCategory = () => {
  if (categoryOptions.value.length > 0) {
    const firstCategory = categoryOptions.value[0];
    if (!form.value.id && !form.value.categoryId) {
      form.value.categoryId = firstCategory.id;
    }
  }
}

/** 检查是否为第三级类别 */
const checkIsThirdLevel = (categoryId: string | number): boolean => {
  const findLevel = (nodes: categoryTreeVO[], targetId: string | number, level: number = 1): number | null => {
    for (const node of nodes) {
      if (node.id === targetId) {
        return level;
      }
      if (node.children && node.children.length > 0) {
        const result = findLevel(node.children, targetId, level + 1);
        if (result !== null) return result;
      }
    }
    return null;
  };

  const level = findLevel(categoryOptions.value, categoryId);
  return level === 3;
};

/** 获取分类完整路径 */
const getCategoryFullPath = (categoryId: string | number): string => {
  const findPath = (nodes: categoryTreeVO[], targetId: string | number, path: string[] = []): string[] | null => {
    for (const node of nodes) {
      const currentPath = [...path, node.label];
      if (node.id === targetId) {
        return currentPath;
      }
      if (node.children && node.children.length > 0) {
        const result = findPath(node.children, targetId, currentPath);
        if (result) return result;
      }
    }
    return null;
  };

  const pathArray = findPath(categoryOptions.value, categoryId);
  return pathArray ? pathArray.join(' / ') : '';
}

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: AttributesVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/product/attributes/edit',
    query: {
      type: 'add'
    }
  });
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AttributesVO) => {
  const _id = row?.id || ids.value[0];
  router.push({
    path: '/product/attributes/edit',
    query: {
      id: _id,
      type: 'edit'
    }
  });
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: AttributesVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品属性定义（用于动态属性配置）编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAttributes(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('product/attributes/export', {
    ...queryParams.value
  }, `attributes_${new Date().getTime()}.xlsx`)
}

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