<template>
  <div class="p-4">
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">{{ pageTitle }}</span>
          <el-button link type="primary" @click="goBack">返回</el-button>
        </div>
      </template>

      <el-form ref="attributesFormRef" :model="form" :rules="rules" label-width="140px" class="max-w-5xl">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌名称" prop="productAttributesName">
              <el-input v-model="form.productAttributesName" placeholder="请输入品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌首字母" prop="productAttributesCode">
              <el-input v-model="form.productAttributesCode" placeholder="请输入品牌首字母" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <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-col>
          <el-col :span="12">
            <el-form-item label="品牌推荐系数" prop="recommendValue">
              <el-input-number 
                v-model="extendFormData.recommendValue" 
                :min="0" 
                :max="9999" 
                controls-position="right" 
                style="width: 100%" 
                placeholder="请输入推荐系数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="品牌标题" prop="brandTitle">
          <el-input v-model="extendFormData.brandTitle" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="品牌LOGO" prop="brandLogo">
          <image-upload v-model="extendFormData.brandLogo" />
        </el-form-item>

        <el-form-item label="品牌故事" prop="brandStory">
          <el-input v-model="extendFormData.brandStory" type="textarea" :rows="3" placeholder="请输入内容" />
        </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>
          <div class="text-gray-500 text-sm mt-2">
            当品牌下还没有商品的时候。分类的品牌区不会不显示品牌。
          </div>
        </el-form-item>

        <el-form-item label="品牌介绍" prop="brandDescribe">
          <editor v-model="extendFormData.brandDescribe" :min-height="192" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="buttonLoading" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="AttributesEdit">
import { getAttributes, addAttributes, updateAttributes } from '@/api/product/attributes';
import { AttributesForm } from '@/api/product/attributes/types';
import { categoryTree } from '@/api/product/base';
import { categoryTreeVO } from '@/api/product/category/types';

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

const attributesFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const categoryOptions = ref<categoryTreeVO[]>([]);

const pageTitle = computed(() => {
  return route.query.type === 'add' ? '新增属性' : '编辑属性';
});

const initFormData: AttributesForm = {
  id: undefined,
  categoryId: undefined,
  productAttributesCode: undefined,
  productAttributesName: undefined,
  isOptional: 1,
  entryMethod: '1',
  isFilter: 1,
  attributesList: undefined,
  required: 0,
  remark: undefined,
}

// 扩展表单字段（用于品牌风格的表单）
const extendFormData = reactive({
  brandTitle: undefined as string | undefined,
  brandLogo: undefined as string | undefined,
  brandStory: undefined as string | undefined,
  brandDescribe: undefined as string | undefined,
  recommendValue: undefined as number | undefined,
})

const form = ref<AttributesForm>({ ...initFormData });

const rules = reactive({
  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" }
  ],
  brandTitle: [
    { required: false, message: "品牌标题不能为空", trigger: "blur" }
  ],
  recommendValue: [
    { required: false, message: "推荐系数不能为空", trigger: "blur" }
  ]
});

/** 检查是否为第三级类别 */
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 getCategoryTree = async () => {
  const res = await categoryTree();
  categoryOptions.value = res.data || [];
}

/** 获取属性详情 */
const getDetail = async () => {
  const id = route.query.id as string;
  if (id && route.query.type !== 'add') {
    const res = await getAttributes(id);
    Object.assign(form.value, {
      ...res.data,
      isOptional: typeof res.data.isOptional === 'string' ? Number(res.data.isOptional) : res.data.isOptional,
      isFilter: typeof res.data.isFilter === 'string' ? Number(res.data.isFilter) : res.data.isFilter,
      required: typeof res.data.required === 'string' ? Number(res.data.required) : res.data.required,
    });
  }
};

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

/** 返回 */
const goBack = () => {
  router.back();
};

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