<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="typeForm" label-position="right" label-width="80px">
      <el-row type="flex" justify="center">
        <el-col :span="15">
          <el-form-item label="类别名称" prop="typeName">
            <el-input v-model.trim="typeForm.typeName" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="15">
          <el-form-item label="上级" prop="pid">
            <select-tree v-model="typeForm.pid" :options="typeTreeList" :props="typeProps" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { toTreeList } from '@/utils/structure'
import DeptSelect from '@/components/DeptSelect'
import SelectTree from '@/components/SelectTree/singleSelect'
// import { getDeptTreeList } from '@/api/system/dept'
import { getTypeList, addType, updateType } from '@/api/knowledge'

export default {
  name: 'EditKType',
  components: { SelectTree, DeptSelect },
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      btnLoading: false, // 保存按钮的加载中状态
      typeForm: {
        id: '', // 编号
        pid: '', // 父级编号
        typeName: ''// 类别名
      }, // 表单
      typeProps: {
        parent: 'pid',
        value: 'id',
        label: 'typeName',
        children: 'children'
      },
      typeTreeList: [], // 类别树列表数据
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      rules: {
        typeName: [{ required: true, message: '类别名称不能为空', trigger: ['blur', 'change'] }],
        pid: [{ required: true, message: '父类别必选', trigger: ['blur', 'change'] }]
      } // 前端校验规则
    }
  },
  created: function() {
    this.fetchTypeTree()
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      this.btnLoading = false
      this.fetchTypeTree()
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.typeForm = {
          id: row.id, // 编号
          pid: row.pid, // 父级编号
          typeName: row.typeName // 类别名
        }
      }
    },
    // 加载类别树形下拉菜单
    fetchTypeTree: function() {
      getTypeList(this.listQuery).then(response => {
        // response.data = [
        //   { typeName: '大类', id: '1', pid: '', deptName: '顶级', num: '1' },
        //   { typeName: '小类1', id: '2', pid: '1', deptName: '顶级', num: '1' },
        //   { typeName: '小类2', id: '3', pid: '1', deptName: '顶级', num: '1' }
        // ]
        if (response.data) {
          this.typeTreeList = toTreeList(response.data, '-1')
          // console.log(this.typeTreeList)
        }
      })
    },
    // 重置表单
    resetForm() {
      this.typeForm = {
        id: '', // 编号
        pid: '', // 父级编号
        typeName: ''// 类别名
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          addType(this.typeForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.btnLoading = false
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                  this.fetchTypeTree()
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
              })
            }
          }).catch(_ => { // 异常情况，loading置为false
            this.btnLoading = false
          })
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          updateType(this.typeForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
          }).catch(_ => { // 异常情况，loading置为false
            this.btnLoading = false
          })
        }
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

  .el-dialog{
    width:700px
  }
  .el-select{
    width: 100%;
  }
</style>
