<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="800px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model.trim="form.title"
          size="small"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-cascader
          v-model="form.category"
          :options="categoryData"
          :props="props"
          @change="handleChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="form.type"
          size="small"
          filterable
          placeholder="请选择类型"
        >
          <el-option
            v-for="item in typeData"
            :key="item.dataCode"
            :label="item.dataValue"
            :value="item.dataCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.type === '0'" label="简介" prop="introduction">
        <ckeditor
          v-model="form.introduction"
          size="small"
          :editor="editor"
          :config="editorConfig"
        ></ckeditor>
      </el-form-item>
      <el-form-item v-if="form.type === '0'" label="详情" prop="detail">
        <ckeditor
          v-model="form.detail"
          size="small"
          :editor="editor"
          :config="editorConfig"
        ></ckeditor>
      </el-form-item>
      <el-form-item v-if="form.type === '1'" label="文档附件" prop="file">
        <el-upload
          v-loading="loading"
          class="avatar-uploader"
          :action="action"
          :headers="headers"
          name="file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-change="fileChange"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-link
          v-if="filePath"
          type="primary"
          :href="filePath"
          target="_blank"
        >
          查看文档
        </el-link>
      </el-form-item>
      <el-form-item v-if="form.type === '2'" label="视频附件" prop="file">
        <el-upload
          v-loading="loading"
          class="avatar-uploader"
          :action="action"
          :headers="headers"
          name="file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-change="fileChange"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <video
          v-if="videoPath"
          width="300"
          height="200"
          :src="videoPath"
          class="avatar"
        />
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" size="small" @click="save">确 定</el-button>
      <el-button size="small" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  doAdd,
  doEdit,
  getTypeCategoryTree,
  getTypeDict,
  getTypeList,
} from '@/api/knowledge';
import ClassicEditor from '@/common/ckeditor/ckeditor';
import '@/common/ckeditor/zh';
import { knowledgeEditorConfig } from '@/common/ckeditor.config.js';
import { baseURL } from '@/config/net.config';
import store from '@/store';
import Video from '@/views/server/siteDetails/video.vue';

export default {
  components: { Video },
  data() {
    return {
      action: baseURL + '/file/upload',
      headers: { token: store.getters['user/token'] },
      filePath: '',
      videoPath: '',
      form: {
        id: '',
        title: '',
        introduction: '',
        detail: '',
        category: '',
      },
      rules: {
        title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
        category: [
          { required: true, trigger: 'change', message: '请选择分类' },
        ],
        type: [{ required: true, trigger: 'change', message: '请选择类型' }],
        introduction: [
          { required: true, trigger: 'blur', message: '请输入简介' },
        ],
        detail: [{ required: true, trigger: 'blur', message: '请输入详情' }],
      },
      dictData: [],
      roleData: [],
      clearable: true,
      roleId: '',
      parentData: [],
      title: '',
      dialogFormVisible: false,
      editor: ClassicEditor,
      editorConfig: knowledgeEditorConfig,
      typeData: [],
      typeList: [],
      categoryData: [],
      props: {
        value: 'id',
        label: 'label',
        children: 'children',
      },
      loading: false,
    };
  },
  created() {},
  methods: {
    showEdit(row) {
      this.getTypeDict();
      this.getTypeCategoryTree();
      this.getTypeList();
      if (!row) {
        this.title = '添加知识库';
      } else {
        this.title = '编辑知识库';
        const data = Object.assign({}, row);
        this.form.type = data.type.dataCode;
        this.form.category = data.category.categoryId;
        this.form.id = data.id;
        this.form.title = data.title;
        this.form.introduction = data.introduction;
        this.form.detail = data.detail;
        this.form.annex = data.annex;
        if (this.form.type === '1') {
          this.filePath = baseURL + '/static/img/' + data.annex;
        }
        if (this.form.type === '2') {
          this.videoPath = baseURL + '/static/img/' + data.annex;
        }
      }
      this.dialogFormVisible = true;
    },
    // 知识库类型
    async getTypeDict() {
      const { data } = await getTypeDict();
      this.typeData = data;
    },
    // 知识库分类
    async getTypeList() {
      const { data } = await getTypeList();
      this.typeList = data;
    },
    // 选择知识库分类
    handleChange(e) {
      this.form.category = e[e.length - 1];
    },
    // 上传文件成功
    handleAvatarSuccess(res, file) {
      if (res.code == 0) {
        this.form.annex = res.data;
        if (this.form.type === '1') {
          this.filePath = baseURL + '/static/img/' + res.data;
        } else {
          this.videoPath = baseURL + '/static/img/' + res.data;
        }
      } else {
        this.$message.error(res.msg);
      }
      console.log(111, res);
    },
    // 正在上传文件
    beforeAvatarUpload(file) {
      this.loading = true;
      if (this.form.type === '1') {
        const isLt10M = file.size / 1024 / 1024 < 200;
        if (!isLt10M) {
          this.$message.error('上传附件大小不能超过 200MB!');
        }
        return isLt10M;
      } else {
        const isLt10M = file.size / 1024 / 1024 < 500;
        if (!isLt10M) {
          this.$message.error('上传视频大小不能超过 500MB!');
        }
        return isLt10M;
      }
    },
    fileChange() {
      this.loading = false;
    },
    async getTypeCategoryTree() {
      const { data } = await getTypeCategoryTree();
      this.categoryData = data;
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (this.form.id) {
            const { msg } = await doEdit(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          } else {
            delete this.form.id;
            const { msg } = await doAdd(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          }
          this.$refs['form'].resetFields();
          this.$parent.getKnowledgeList();
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
