<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="cancel" 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="必填" maxlength="100"/>
          </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="必填" maxlength="99"/>
          </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-col :span="8">
          <el-form-item label="权属单位" prop="deptId">
            <dept-select v-model="knowledgeForm.deptId" :dept-show="true" :need-top="false"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="知识内容" prop="info">
            <!--<wangeditor ref="editor" v-model="knowledgeForm.info" height="300"/>-->
            <!--<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-row>
        <el-col :span="24">
          <el-form-item label="附件" prop="file">
            <el-upload
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :on-change="handleChange"
              :file-list="fileList"
              :on-success="handleSuccess"
              :limit="3"
              :http-request="uploadFile"
              :before-remove="beforeRemove"
              :before-upload="handleBeforeUpload"
              action="string"
              multiple
            >
              <el-button v-show="!hideUpload" size="small" type="primary">点击上传</el-button>
              <span slot="tip" class="el-upload__tip"> 只能上传word, excel, pdf，图片文件，且不超过10M</span>
            </el-upload>
          </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 { UploadFile } from '@/api/common'
import { getTypeList, addKnowledge, updateKnowledge, knowledgeDetail } from '@/api/knowledge'
import Tinymce from '../../components/Tinymce/index'
import Wangeditor from '../../components/wangeditor/wangeditor'
import DeptSelect from '../../components/DeptSelect/index'

export default {
  name: 'EditKnowledge',
  components: { DeptSelect, Wangeditor, Tinymce, SelectTree },
  data() {
    return {
      uploadPath: process.env.BASE_API + '/file/upload',
      staticPath: process.env.BASE_API + '/static/',
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      btnLoading: false, // 保存按钮的加载中状态
      size: 'small',
      knowledgeForm: {
        id: '', // 编号
        type: '', // 父级编号
        name: '', // 类别名
        keywords: '', // 关键词
        info: '', // 内容
        deptId: ''
      }, // 表单
      typeProps: {
        parent: 'pid',
        value: 'id',
        label: 'typeName',
        children: 'children'
      },
      typeTreeList: [], // 类别树列表数据
      fileList: [], // 上传附件列表
      upFileList: [], // 上传File列表，上传参数
      hideUpload: false,
      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'] }],
        deptId: [{ 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.hideUpload = false
        this.fileList = []
        if (!this.knowledgeForm.deptId) {
          this.knowledgeForm.deptId = this.$store.state.user.deptId
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          // this.$refs['editor'].initEditor()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.fetchKnowledgeDetail(row.kId)
      }
    },
    // 获取知识详情
    fetchKnowledgeDetail(id) {
      // this.$refs.editor.initEditor()
      knowledgeDetail(id).then(response => {
        if (response.data) {
          debugger
          // 处理fileList
          if (response.data.file && response.data.file !== '') {
            const file_strs = response.data.file.split(';')
            const fileList = []
            for (const item of file_strs) {
              const strs = item.split(':')
              fileList.push({
                name: strs[0],
                url: this.staticPath + strs[1]
              })
            }
            this.fileList = fileList
          }
          // 处理表单
          this.knowledgeForm = {
            id: response.data.kId, // id
            type: response.data.kType, // 类型
            name: response.data.kName, // 类别名
            keywords: response.data.keywords, // 关键词
            info: response.data.kInfo // 内容
          }
        }
        if (!this.knowledgeForm.deptId) {
          this.knowledgeForm.deptId = this.$store.state.user.deptId
        }
      })
    },
    // 加载类别树形下拉菜单
    fetchTypeTree: function() {
      getTypeList().then(response => {
        if (response.data) {
          this.typeTreeList = toTreeList(response.data, '-1')
        }
      })
    },
    // 重置表单
    resetForm() {
      this.knowledgeForm = {
        id: '', // 编号
        type: '', // 父级编号
        name: ''// 类别名
      }
    },
    // 保存数据
    saveData: function() {
      // 处理附件
      const urls = this.fileList.map(item => {
        let index = item.url.indexOf('/static/')
        if (index !== -1) {
          index += 8
        }
        return item.name + ':' + item.url.substring(index)
      })
      this.knowledgeForm.file = urls.join(';')
      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('refresh')
                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.$emit('refresh')
              this.$message.success('修改成功')
              this.dialogFormVisible = false
            }
          }).catch(_ => { // 异常情况，loading置为false
            this.btnLoading = false
          })
        }
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.fileList = []
      this.$emit('watchChild')
    },
    // 文件上传
    uploadFile(file) {
      console.log('uploadFile:' + file.file.name)
      UploadFile(file).then(res => {
        if (res.code === 200) {
          // this.fileList = fileList
          this.fileList.push({ name: file.file.name, url: this.staticPath + res.data })
        }
      })
    },
    // 上传前判断文件格式及大小
    handleBeforeUpload(file) {
      debugger
      console.log('beforeUpload')
      let isFile = false
      if (file.type === '') {
        isFile = (file.name.indexOf('.doc') > -1) || (file.name.indexOf('.xls') > -1)
      } else {
        isFile = (file.type.indexOf('word') > -1) || (file.type.indexOf('sheet') > -1) || (file.type.indexOf('excel') > -1) || (file.type === 'application/pdf') || (file.type.indexOf('image') > -1)
      }
      let res = true
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isFile) {
        this.$message.error('上传文件只能是word或excel或pdf或图片!')
        res = false
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        res = false
      }
      for (const i in this.fileList) {
        if (this.fileList[i].name === file.name) {
          this.$message.error('该文件已上传过，请选择其他文件图片')
          res = false
        }
      }
      return res
    },
    // 移除后操作删除文件
    handleRemove(file, fileList) {
      console.log('handleRemove')
      debugger
      for (const i in this.fileList) {
        if (this.fileList[i].uid === file.uid) {
          this.fileList.splice(i, 1)
          this.hideUpload = this.fileList.length >= 3
          return
        }
      }
    },
    // 上传文件时触发，如果文件个数超过3个则hideUpload
    handleChange(file, fileList) {
      console.log('handleChange')
      if (fileList) {
        this.hideUpload = fileList.length >= 3
      } else {
        this.hideUpload = false
      }
    },
    // 处理限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 移除前的确认
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`)
      }
    },
    // 上传成功，未调用
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess')
      // const base_url = process.env.BASE_API + '/static/'
      if (response.code === 200) {
        debugger
        this.fileList.push({ uid: file.uid, name: file.file.name, url: response.data })
        this.handleChange()
      } else {
        this.$message.warning(response.message)
      }
    }
  }
}
</script>

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

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