<template>
    <div class="app-container">
       <!-- 查询和其他操作 -->
       <div class="filter-container">
        <el-input
        class="filter-item" style="width: 200px;"
            v-model="listQuery.categoryCode"
            placeholder="请输入类别编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
          <el-input
          class="filter-item" style="width: 200px;"
            v-model="listQuery.categoryName"
            placeholder="请输入类别名称"
            clearable
            @keyup.enter.native="handleQuery"
          />   
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleQuery">查找</el-button>
          <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
          <el-button class="filter-item" v-waves icon="el-icon-download" @click="handleDownLoad">导出</el-button>
          <el-button class="filter-item" type="info" icon="el-icon-sort" @click="toggleExpandAll">展开/折叠</el-button>

        </div>
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="categoryCode" label="类型编号" align="center"></el-table-column>
        <el-table-column prop="categoryName" label="类型名称" min-width="180px"></el-table-column>
        <!-- <el-table-column prop="parentId" label="备注" align="center"></el-table-column> -->
        <el-table-column label="创建时间" align="center" prop="createDate">
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="110px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="small"
              type="success"
              @click="handleAdd(scope.row)"
            >添加</el-button>
            <el-button
              v-if="!scope.row.children"
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 添加或修改类别对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24" v-if="isShowParent">
              <el-form-item label="上级名称" prop="parentId">
                <treeselect v-model="form.parentId" @select="departTreeSelected" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级类型" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="isShowParent">
              <el-form-item label="上级编号" prop="categoryParentCode">
                <el-input v-model="form.categoryParentCode" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="类别名称" prop="categoryName">
                <el-input v-model="form.categoryName" placeholder="请输入类别类型" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="类别编号" prop="categoryCode">
                <el-input v-model="form.categoryCode" placeholder="请输入类别编号" />
              </el-form-item>
            </el-col>
          </el-row>
        </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 { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/goodsTypeList";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import waves from "@/directive/waves"; // 水波纹指令
  export default {
    components: { Treeselect },
    directives: { waves },
    data() {
      return {
        isShowParent:false,
        downloadLoading: false,
        // 遮罩层
        loading: true,
        // 表格树数据
        deptList: [],
        // 类别树选项
        deptOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否展开，默认全部展开
        isExpandAll: true,
        // 重新渲染表格状态
        refreshTable: true,
        // 查询参数
        listQuery: {
          categoryCode: undefined,
          categoryName: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          parentId: [
            { required: true, message: "上级类型不能为空", trigger: "blur" }
          ],
          categoryParentCode: [
            { required: true, message: "上级编号不能为空", trigger: "blur" }
          ],
          categoryName: [
            { required: true, message: "类别名称不能为空", trigger: "blur" }
          ],
          categoryCode: [
            { required: true, message: "类别编号不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      //选中树形选项
      departTreeSelected(node,instanceId){
        console.log(node,instanceId);
        this.form.categoryParentCode = node.categoryCode;
      },
      handleDownLoad(){
            window.location.href = process.env.BASE_API + '/product-category/export/category';
        },
      /** 查询类别列表 */
      getList() {
        this.loading = true;
        listDept(this.listQuery).then(response => {
          this.deptList = this.handleTree(response.data.data,'id');
          console.log(this.deptList);
          this.loading = false;
        });
      },
      /** 转换类别数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.categoryName,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          parentId: undefined,
          categoryParentCode:undefined,
          categoryName: undefined,
          categoryCode: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.listQuery = {
          categoryCode: undefined,
          categoryName: undefined,
        };
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        this.isShowParent = false;
        if (row.id) {
          this.isShowParent = true;
          this.form.parentId = row.id;
          this.form.categoryParentCode = row.categoryCode;
        }
        this.open = true;
        this.title = "添加类别";
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data.data, "id");
        });
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.isShowParent = false;
        getDept({id:row.id}).then(response => {
          let data = response.data.data;
          this.form = data;
          if (data.parentId) {
            this.isShowParent = true;
          }
          this.open = true;
          this.title = "修改类别";
          listDept().then(response => {
            this.deptOptions = this.handleTree(response.data.data, "id");
          });
          // listDeptExcludeChild({id:row.id}).then(response => {
          //   this.deptOptions = this.handleTree(response.data.data, "id");
          //   if (this.deptOptions.length == 0) {
          //     const noResultsOptions = { id: this.form.parentId, children: [] };
          //     // const noResultsOptions = { id: this.form.parentId, categoryName: this.form.parentName, children: [] };
          //     this.deptOptions.push(noResultsOptions);
          //   }
          // });
        });

      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateDept(this.form).then(response => {
                this.$notify({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                            duration: 2000
                        })
                this.open = false;
                this.getList();
              });
            } else {
              addDept(this.form).then(response => {
                this.$notify({
                            title: '成功',
                            message: '新增成功',
                            type: 'success',
                            duration: 2000
                        })
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        console.log(row);
        this.$confirm('是否确认删除名称为"' + row.categoryName + '"的数据项？', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
        .then(function() {
          return delDept({id:row.id});
        }).then(() => {
          this.getList();
          this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
        }).catch(() => {});
      }
    }
  };
  </script>
  