<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="1000px" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="knowledgeForm" :size="size" label-position="right" label-width="80px">
      <el-row type="flex" justify="center">
        <el-col :span="24">
          <el-form-item label="标题" prop="name">
            <el-input v-model.trim="knowledgeForm.name" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="12">
          <el-form-item label="关键词" prop="keywords">
            <el-input v-model.trim="knowledgeForm.keywords" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属类别" prop="type">
            <select-tree v-model="knowledgeForm.type" :options="typeTreeList" :props="typeProps" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="知识内容" prop="info">
            <!--<tinymce v-model="knowledgeForm.info" :height="300"/>-->
            <el-input v-model="knowledgeForm.info" type="textarea" rows="10" placeholder="必填"/>
          </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 SelectTree from '@/components/SelectTree/singleSelect'
// import { getDeptTreeList } from '@/api/system/dept'
import { getTypeList, addKnowledge, updateKnowledge, knowledgeDetail } from '@/api/knowledge'
import Tinymce from '../../components/Tinymce/index'

export default {
  name: 'EditKnowledge',
  components: { Tinymce, SelectTree },
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      btnLoading: false, // 保存按钮的加载中状态
      size: 'small',
      knowledgeForm: {
        id: '', // 编号
        type: '', // 父级编号
        name: '', // 类别名
        keywords: '', // 关键词
        info: '' // 内容
      }, // 表单
      typeProps: {
        parent: 'pid',
        value: 'id',
        label: 'typeName',
        children: 'children'
      },
      typeTreeList: [], // 类别树列表数据
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      rules: {
        name: [{ required: true, message: '标题不能为空', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '类别必选', trigger: ['blur', 'change'] }],
        keywords: [{ required: true, message: '关键词必填', trigger: ['blur', 'change'] }],
        info: [{ 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.fetchKnowledgeDetail(row.kId)
      }
    },
    // 获取知识详情
    fetchKnowledgeDetail(id) {
      knowledgeDetail(id).then(response => {
        if (response.data) {
          this.knowledgeForm = {
            id: response.data.kId, // id
            type: response.data.kType, // 类型
            name: response.data.kName, // 类别名
            keywords: response.data.keywords, // 关键词
            info: response.data.kInfo // 内容
          }
        }
      })
    },
    // 加载类别树形下拉菜单
    fetchTypeTree: function() {
      getTypeList().then(response => {
        if (response.data) {
          this.typeTreeList = toTreeList(response.data, '-1')
        }
      })
    },
    // 重置表单
    resetForm() {
      this.knowledgeForm = {
        id: '', // 编号
        type: '', // 父级编号
        name: ''// 类别名
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        // console.log(this.knowledgeForm)
        if (valid) {
          this.btnLoading = true
          addKnowledge(this.knowledgeForm).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
          updateKnowledge(this.knowledgeForm).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>
