<script src="../../utils/validate.js"></script>
<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>智库编辑</h3>
      <el-form ref="faq" :rules="rules" :model="faq" label-width="150px">
        <el-form-item label="FAQ标题" prop="name">
          <el-input v-model="faq.name" />
        </el-form-item>

        <el-form-item label="是否置顶" prop="isTop">
          <el-radio-group v-model="faq.isTop" style="margin-top:10px">
            <el-radio :label="false">不置顶</el-radio>
            <el-radio :label="true">置顶</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标签">
          <el-select v-model="faq.label" clearable>
            <el-option v-for="item in labelList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>

          <el-button class="button-new-keyword" type="primary" @click="showInput">+ 增加</el-button>
        </el-form-item>

        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader v-model="faq.categoryId" :options="categoryList" expand-trigger="hover" clearable @change="handleCategoryChange" />
        </el-form-item>

        <el-form-item label="详细内容">
          <editor v-model="faq.content" :init="editorInit" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleCreate">保存</el-button>
    </div>
  </div>
</template>

<style>
 .info {
    font-size: 9px;
    color: #20a0ff;
    margin-left: 15px;
 }

.el-card {
  margin-bottom: 10px;
}
.op-container {
  display: flex;
  justify-content: center;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.el-form-item__content{
  display: flex;
}

.avatar {
  width: 145px;
  height: 145px;
}
</style>

<script>
import { create, listCatAndLabel } from "@/api/faq";
import { createStorage, uploadPath } from "@/api/storage";
import Editor from "@tinymce/tinymce-vue";
import { MessageBox } from "element-ui";
import { getToken } from "@/utils/auth";

export default {
  name: "faqCreate",
  components: { Editor },
  filters: {
    disTypeFilter(type)
    {
      return typeMap[type]
    }
  },

  data() {
    return {
      uploadPath,
      categoryList: [],
      labelList:[],
      faq: {
        label: [],
        isTop: false,
      },
      submiting:false,//商品提交中 防止多次提交
      multipleSpec: false,
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        categoryId: [{ type: 'number', required: true, message: "请选择分类", trigger: "change" }],
      },
      editorInit: {
        language: "zh_CN",
        height: 500,
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount"
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen"
        ],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then(res => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure("上传失败，请重新上传");
            });
        }
      }
    };
  },
  computed: {
    headers() {
      return {
        "X-JZ-Admin-Token": getToken()
      };
    }
  },
  created() {
    this.init();
  },

  methods: {
    init: function() {
      listCatAndLabel().then(response => {
        this.categoryList = response.data.data.categoryList;
        this.labelList = response.data.data.brandList;
      });
    },
    isNumber(rule, value, callback) {
      if (value === '') {
        return callback();
      }  //这是用来判断如果不是必须输入的，则直接跳出
      const r = /^\+?[1-9][0-9]*$/; // 正整数
      // 如果判断不符合正则，则不是正整数不能提交
      if (!r.test(value)) {
        return callback(new Error('数量必须为正整数'));
      } else {
        return callback();
      }
    },
    isInputValid(rule,value,callback){
      if(value==null||value.trim()=="")
         return callback(new Error('请输入参数或值'));
      else return callback();

    },
    handleCategoryChange(value) {
      this.faq.categoryId = value[value.length - 1];
    },
    handleCancel: function() {
      this.$router.push({ path: "/faq/goods" });
    },
    handleCreate: function() {
       if(this.submiting) return;
       this.submiting=true;
       console.info(this.faq);
       create(this.faq)
              .then(response => {
                this.$notify.success({
                  title: "成功",
                  message: "创建成功"
                });
                this.$router.push({ path: "/faq/list" });
              })
              .catch(response => {
                MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
                  confirmButtonText: "确定",
                  type: "error"
                });
        });
        this.submiting=false;
     },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1);
      this.faq.keywords = this.keywords.toString();
    },
    showInput() {
      this.newKeywordVisible = true;
      this.$nextTick(_ => {
        this.$refs.newKeywordInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword;
      if (newKeyword) {
        this.keywords.push(newKeyword);
        this.faq.keywords = this.keywords.toString();
      }
      this.newKeywordVisible = false;
      this.newKeyword = "";
    }
  }
};
</script>
