<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-form :model="listQuery" size="small" :inline="true" label-position="top">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="商品类别编号">
            <el-input
              clearable
              placeholder="请输入商品类别编号"
              v-model="listQuery.categoryCode"
              @keyup.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品类别名称">
            <el-input
              clearable
              placeholder="请输入商品类别名称"
              v-model="listQuery.categoryName"
              @keyup.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="搜索">
            <el-button style="width: 100%;" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重置">
            <el-button style="width: 100%;" icon="el-icon-refresh" type="primary" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" class="editButton" size="small" icon="el-icon-plus" @click="handleAdd">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="small" @click="handleDownLoad">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-sort" size="small" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
    </el-row>

    <!-- 查询结果 -->
    <div class="border-card">
      <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 label="创建时间" align="center" prop="createDate"></el-table-column>
        <el-table-column label="操作" align="center" min-width="240px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              class="editText"
              size="small"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-plus"
              class="plusText"
              size="small"
              @click="handleAdd(scope.row)"
            >添加</el-button>
            <el-button
              v-if="!scope.row.children"
              type="text"
              icon="el-icon-delete"
              class="deleteText"
              size="small"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改商品类别对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" style='margin: 0 50px;'>
        <el-row :gutter="20">
          <el-col :span="12" v-if="isShowParent">
            <el-form-item label="上级商品类别名称" prop="parentId">
              <el-cascader
                style="width: 100%;"
                v-model="form.parentId"
                :options="deptList"
                :props="{
                  label: 'categoryName',
                  value: 'id',
                  emitPath: false,
                  checkStrictly: true
                }"
                placeholder="请选择上级类别"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="isShowParent">
            <el-form-item label="上级商品类别编号" prop="categoryParentCode">
              <el-input v-model="form.categoryParentCode" readonly placeholder="上级类别编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品类别名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入商品类别名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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 @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept } 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: [],
      // 弹出层标题
      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 && row.id) {
        this.isShowParent = true
        this.form.parentId = row.id
        this.form.categoryParentCode = row.categoryCode
      }
      this.open = true
      this.title = '添加商品类别'
    },
    /** 展开/折叠操作 */
    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 => {
        const data = response.data.data
        this.form = data
        if (data.parentId) {
          this.isShowParent = true
        }
        this.open = true
        this.title = '修改商品类别'
      })
    },
    /** 提交按钮 */
    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(() => {
          return delDept({ id: row.id })
        })
        .then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
        .catch(() => {})
    }
  }
}
</script>