<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:mallGoodsClass:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="mallGoodsClassList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类名称" prop="name" />
      <el-table-column label="图片链接" align="center" prop="icon">
        <template slot-scope="scope">
          <el-image :src="scope.row.icon" style="width: 80px" :preview-src-list="[scope.row.icon]"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="添加时间" align="center" prop="createAt" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:mallGoodsClass:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-if="scope.row.id !== 62 && scope.row.id !== 63"
            v-hasPermi="['mall:mallGoodsClass:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.id !== 62 && scope.row.id !== 63"
            v-hasPermi="['mall:mallGoodsClass:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级" prop="parentId">
          <treeselect v-model="form.parentId" :options="mallGoodsClassOptions" :normalizer="normalizer" placeholder="请选择父类ID" />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="轮播图片" prop="icon" >
          <el-upload
            class="upload-demo"
            :limit="1"
            accept=".jpg, .png"
            :action="upload.url"
            :file-list="upload.fileList"
            :headers="upload.headers"
            list-type="picture"
            :on-success="handleFileSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过1M
            </div>
          </el-upload>
          <el-input v-model="form.icon" v-if="false" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMallGoodsClass, getMallGoodsClass, delMallGoodsClass, addMallGoodsClass, updateMallGoodsClass, exportMallGoodsClass } from "@/api/mall/mallGoodsClass";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";

export default {
  name: "MallGoodsClass",
  components: {
    Treeselect
  },
  data() {
    return {
      //状态
      statusOptions: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 商品类型表格数据
      mallGoodsClassList: [],
      // 商品类型树选项
      mallGoodsClassOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id: null,
        name: null,
        status: null,
        isHome: null,
        icon: null,
        parentId: null,
        sort: null,
        createAt: null,
        updateAt: null,
        delFlag: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("mall_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.form.icon = response.url;
    },
    /** 查询商品类型列表 */
    getList() {
      this.loading = true;
      listMallGoodsClass(this.queryParams).then(response => {
        this.mallGoodsClassList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换商品类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询商品类型下拉树结构 */
    getTreeselect() {
      listMallGoodsClass().then(response => {
        this.mallGoodsClassOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.mallGoodsClassOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: "0",
        isHome: null,
        icon: null,
        parentId: null,
        sort: null,
        createAt: null,
        updateAt: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.upload.fileList = []
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加商品类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.upload.fileList = []
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getMallGoodsClass(row.id).then(response => {
        this.form = response.data;
        this.upload.fileList = [{ name: '', url: row.icon }];
        this.open = true;
        this.title = "修改商品类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMallGoodsClass(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.upload.fileList = []
            });
          } else {
            addMallGoodsClass(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.upload.fileList = []
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除商品类型编号为"' + row.id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delMallGoodsClass(row.id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
