<template>
  <!-- 分类详情表单，使用 Element UI -->
  <el-card class="form-container" shadow="never">
    <el-form :model="productCate"
             :rules="rules"
             ref="productCateFrom"
             label-width="150px">

      <!-- 分类名称输入框 -->
      <el-form-item label="分类名称：" prop="name">
        <el-input v-model="productCate.name"></el-input>
      </el-form-item>

      <!-- 上级分类选择框 -->
      <el-form-item label="上级分类：">
        <el-select v-model="productCate.parentId" placeholder="请选择分类">
          <el-option
            v-for="item in selectProductCateList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 数量单位输入框 -->
      <el-form-item label="数量单位：">
        <el-input v-model="productCate.productUnit"></el-input>
      </el-form-item>

      <!-- 排序输入框 -->
      <el-form-item label="排序：">
        <el-input v-model="productCate.sort"></el-input>
      </el-form-item>

      <!-- 是否显示单选按钮 -->
      <el-form-item label="是否显示：">
        <el-radio-group v-model="productCate.showStatus">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 是否显示在导航栏 -->
      <el-form-item label="是否显示在导航栏：">
        <el-radio-group v-model="productCate.navStatus">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 分类图标上传组件 -->
      <el-form-item label="分类图标：">
        <single-upload v-model="productCate.icon"></single-upload>
      </el-form-item>

      <!-- 筛选属性列表 -->
      <el-form-item v-for="(filterProductAttr, index) in filterProductAttrList"
                    :label="index | filterLabelFilter"
                    :key="filterProductAttr.key">
        <el-cascader
          clearable
          v-model="filterProductAttr.value"
          :options="filterAttrs">
        </el-cascader>
        <!-- 删除按钮 -->
        <el-button style="margin-left: 20px" @click.prevent="removeFilterAttr(filterProductAttr)">删除</el-button>
      </el-form-item>

      <!-- 新增筛选属性按钮 -->
      <el-form-item>
        <el-button size="small" type="primary" @click="handleAddFilterAttr()">新增</el-button>
      </el-form-item>

      <!-- 关键词输入框 -->
      <el-form-item label="关键词：">
        <el-input v-model="productCate.keywords"></el-input>
      </el-form-item>

      <!-- 分类描述输入框 -->
      <el-form-item label="分类描述：">
        <el-input type="textarea" :autosize="true" v-model="productCate.description"></el-input>
      </el-form-item>

      <!-- 提交和重置按钮 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit('productCateFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('productCateFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  // API 引入
  import {fetchList, createProductCate, updateProductCate, getProductCate} from '@/api/productCate';
  import {fetchListWithAttr} from '@/api/productAttrCate';
  import {getProductAttrInfo} from '@/api/productAttr';
  import SingleUpload from '@/components/Upload/singleUpload';

  const defaultProductCate = {
    description: '',
    icon: '',
    keywords: '',
    name: '',
    navStatus: 0,
    parentId: 0,
    productUnit: '',
    showStatus: 0,
    sort: 0,
    productAttributeIdList: []
  };

  export default {
    name: "ProductCateDetail",
    components: { SingleUpload },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        productCate: Object.assign({}, defaultProductCate),
        selectProductCateList: [], // 上级分类列表
        rules: {
          name: [
            { required: true, message: '请输入品牌名称', trigger: 'blur' },
            { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
          ]
        },
        filterAttrs: [], // 筛选属性列表
        filterProductAttrList: [{ value: [] }] // 已选筛选属性
      };
    },
    created() {
      if (this.isEdit) {
        // 编辑模式下，获取分类详情数据
        getProductCate(this.$route.query.id).then(response => {
          this.productCate = response.data;
        });
        // 获取筛选属性数据
        getProductAttrInfo(this.$route.query.id).then(response => {
          if (response.data != null && response.data.length > 0) {
            this.filterProductAttrList = response.data.map((item, index) => ({
              key: Date.now() + index,
              value: [item.attributeCategoryId, item.attributeId]
            }));
          }
        });
      }
      this.getSelectProductCateList();
      this.getProductAttrCateList();
    },
    methods: {
      // 获取上级分类列表
      getSelectProductCateList() {
        fetchList(0, { pageSize: 100, pageNum: 1 }).then(response => {
          this.selectProductCateList = response.data.list;
          this.selectProductCateList.unshift({ id: 0, name: '无上级分类' });
        });
      },
      // 获取筛选属性分类及其属性
      getProductAttrCateList() {
        fetchListWithAttr().then(response => {
          this.filterAttrs = response.data.map(category => ({
            label: category.name,
            value: category.id,
            children: category.productAttributeList.map(attr => ({
              label: attr.name,
              value: attr.id
            }))
          }));
        });
      },
      // 提交表单数据
      onSubmit(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', { type: 'warning' }).then(() => {
              this.productCate.productAttributeIdList = this.getProductAttributeIdList();
              if (this.isEdit) {
                updateProductCate(this.$route.query.id, this.productCate).then(() => {
                  this.$message.success('修改成功');
                  this.$router.back();
                });
              } else {
                createProductCate(this.productCate).then(() => {
                  this.resetForm(formName);
                  this.$message.success('提交成功');
                });
              }
            });
          } else {
            this.$message.error('验证失败');
          }
        });
      },
      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.productCate = Object.assign({}, defaultProductCate);
      },
      // 获取选中的筛选属性ID列表
      getProductAttributeIdList() {
        return this.filterProductAttrList
          .filter(item => item.value.length === 2)
          .map(item => item.value[1]);
      },
      // 删除筛选属性
      removeFilterAttr(filterAttr) {
        const index = this.filterProductAttrList.indexOf(filterAttr);
        if (index > -1) this.filterProductAttrList.splice(index, 1);
      },
      // 添加筛选属性
      handleAddFilterAttr() {
        if (this.filterProductAttrList.length < 3) {
          this.filterProductAttrList.push({ value: [], key: Date.now() });
        } else {
          this.$message.warning('最多添加三个');
        }
      }
    },
    filters: {
      // 自定义过滤器，为第一个筛选属性设置标签
      filterLabelFilter(index) {
        return index === 0 ? '筛选属性：' : '';
      }
    }
  };
</script>

<style scoped>
/* 本地样式，样式只对当前组件生效 */
</style>
