<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      ref="crud"
      @search-change="searchChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @tree-load="treeLoad"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button size="small" type="primary" @click="addFirst">新增一级分类</el-button>
      </template>
      <template slot="menu" slot-scope="{row}">
        <el-button size="small" type="text" @click="modify(row)">编辑</el-button>
        <el-button size="small" type="text" @click="del(row)">删除</el-button>
        <el-button size="small" type="text" @click="addSecond(row)" v-if="!row.firstId">新增二级</el-button>
      </template>
    </avue-crud>
    <!-- 新增、编辑 -->
    <el-drawer :title="drawerTitle" :visible.sync="viewDrawer" size="60%">
      <el-form :model="formOption" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item v-if="formOption.firstId" label="分类名称" prop="secondName">
          <el-input v-model="formOption.secondName"></el-input>
        </el-form-item>
        <el-form-item v-else label="分类名称" prop="name">
          <el-input v-model="formOption.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')" :loading="btnLoading">保存</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </basic-container>
</template>

<script>
  import {getContentCategoryFirstList,
    contentCategoryAdd,
    contentCategoryFirstEdit,
    contentCategoryFirstDel,
    contentCategorySecondAdd,
    contentCategorySecondEdit,
    contentCategorySecondDel
  } from '@/api/help/content/classify'
  import {
    getAllContentCategorySecondList
  } from '@/api/help/classify'
  export default {
    name: "index",
    data () {
      return {
        btnLoading:false,
        loading:false,
        viewDrawer:false,
        drawerTitle: '新增一级分类',
        formOption: {
          name: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { max: 20, message: '最大输入20个汉字', trigger: 'blur'}
          ],
          secondName: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { max: 6, message: '最大输入6个汉字', trigger: 'blur'}
          ]
        },
        option: {
          height: "auto",
          expandRowKeys:[],
          lazy:true,
          tip: false,
          searchShow: true,
          searchMenuSpan: 4,
          border: true,
          index: true,
          indexLabel: "序号",
          selection: false,
          viewBtn: false,
          addBtn: false,
          editBtn:false,
          delBtn: false,
          columnBtn: false,
          menuWidth: 300,
          labelWidth: 151,
          dialogClickModal: false,
          dialogType: "drawer",
          dialogFullscreen: true,
          column: [
            {
              label: "一级分类",
              prop: "name",
              display: false,
            },
            {
              label: "二级分类",
              prop: "secondName",
              display: false,
            },
            {
              label: "创建日期",
              prop: "createTime",
              display: false,
              type: "datetime",
              format: "yyyy/MM/dd",
            }
          ]
        },
        data: [
          {
            id: 1,
            title: '测试标题',
            type: '常见问题',
            tag: '规范',
            time: '2021.7.2',
            note: '<p>测试内容</p>',
            hasChildren: true
          }
        ],
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 100,
        },
        firstObj: {}
      }
    },
    methods: {
      treeLoad (tree, treeNode, resolve) {
        const parentId = tree.id;
        getAllContentCategorySecondList(parentId).then(res => {
          res.data.data.forEach(e => {
            e.secondName = JSON.parse(JSON.stringify(e.name))
            delete e.name
          })
          resolve(res.data.data);
        })
      },
      addFirst () {
        this.drawerTitle = '新增一级分类'
        this.add()
      },
      addSecond (row) {
        this.firstObj = JSON.parse(JSON.stringify(row))
        this.drawerTitle = '新增二级分类'
        this.add()
      },
      add () {
        this.formOption = {}
        this.viewDrawer = true
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate();
        })
      },
      modify (row) {
        this.formOption = JSON.parse(JSON.stringify(row))
        this.drawerTitle = row.firstId ? "编辑二级分类":'编辑一级分类'
        this.viewDrawer = true
        this.option.expandRowKeys = []
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate();
        })
      },
      del (row) {
        this.$confirm('是否删除此数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(row.firstId) {
            contentCategorySecondDel(JSON.stringify(row)).then(res => {
              this.option.expandRowKeys = []
              this.$message({
                message: res.data.msg,
                type: 'success',
              })
              this.refreshChange()
            })
          } else {
            contentCategoryFirstDel(JSON.stringify(row)).then(res => {
              this.$message({
                message: res.data.msg,
                type: 'success',
              })
              this.refreshChange()
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnLoading = true
            if (this.drawerTitle === '新增一级分类') {
              contentCategoryAdd(JSON.stringify(this.formOption)).then(res => {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                })
                this.refreshChange()
                this.viewDrawer = false
                this.btnLoading = false
              }).catch(() => {
                this.btnLoading = false
              })
            }else if(this.drawerTitle === '编辑一级分类') {
              contentCategoryFirstEdit(JSON.stringify(this.formOption)).then(res => {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                })
                this.refreshChange()
                this.viewDrawer = false
                this.btnLoading = false
              }).catch(() => {
                this.btnLoading = false
              })
            }else if(this.drawerTitle === '新增二级分类') {
              var data = {
                firstId: this.firstObj.id,
                ...this.formOption
              }
              contentCategorySecondAdd(JSON.stringify(data)).then(res => {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                })
                this.refreshChange()
                this.viewDrawer = false
                this.btnLoading = false
              }).catch(() => {
                this.btnLoading = false
              })
            }else if(this.drawerTitle === '编辑二级分类') {
              this.formOption.name = JSON.parse(JSON.stringify(this.formOption.secondName))
              delete this.formOption.secondName
              var data = {
                firstId: this.firstObj.id,
                ...this.formOption
              }
              contentCategorySecondEdit(JSON.stringify(data)).then(res => {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                })
                this.viewDrawer = false
                this.btnLoading = false
              }).catch(() => {
                this.btnLoading = false
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.viewDrawer = false
        this.$refs[formName].resetFields();
      },
      /* 表格方法 */
      onLoad(page, params = {}) {
        this.loading = true;
        var data = {
          current: page.currentPage,
          size: page.pageSize
        }
        getContentCategoryFirstList(data).then((res) => {
          this.data = res.data.data.records;
          this.page.total = res.data.data.total;
          this.loading = false;
        });
      },
      searchChange(params,done) {},
      currentChange(val) {
        this.page.currentPage = val
      },
      sizeChange(val) {
        this.page.currentPage = 1
        this.page.pageSize = val
      },
      refreshChange () {
        this.page.currentPage = 1;
        this.data = []
        this.onLoad(this.page)
      }
    }
  }
</script>

<style scoped>
  .el-form-item{
    margin-bottom: 22px !important;
  }
</style>
