<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <div class="mod-news__news}">
      <el-form :inline="true"
               :model="dataForm"
               :rules="dataRule"
               ref="dataForm"
               :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
        <el-row>
          <el-form-item label="所属机构">
            <el-cascader v-model="dataForm.allDeptIdsShow"
                         :options="options"
                         :props="{ multiple: true }"
                         clearable
                         collapse-tags></el-cascader>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="类别"
                        prop="newsCateroryId">
            <el-select v-model="dataForm.newsCateroryId"
                       @change="changeCaterory"
                       placeholder="请选择类别">
              <el-option v-for="item in categorys"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="新闻标题"
                        prop="newsTitle">
            <el-input v-model="dataForm.newsTitle"
                      type="text"
                      maxlength="50"
                      show-word-limit
                      placeholder="请输入标题"
                      clearable
                      style="width:500px">
            </el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="newsContent"
                        label="正文编辑">
            <!-- 富文本编辑器, 容器 -->
            <div id="J_quillEditor" class="ql-editor"></div>
            <!-- 自定义上传图片功能 (使用element upload组件) -->
            <el-upload :action="uploadUrl"
                       :show-file-list="false"
                       :before-upload="uploadBeforeUploadHandle"
                       :on-success="uploadSuccessHandle"
                       style="display: none;">
              <el-button ref="uploadBtn"
                         type="primary"
                         size="small">{{ $t('upload.button') }}</el-button>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="newsImageUrl"
                        v-loading="loading"
                        label="新闻首图">
            <el-upload class="avatar-uploader"
                       :action="uploadUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :on-error="handelError"
                       :before-upload="beforeAvatarUpload">
              <img v-if="dataForm.newsImageUrl"
                   :src="dataForm.newsImageUrl"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip"
                   class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="newsReleaseStartTime"
                        label="有效时间">
            <el-date-picker @change='setRegistTime'
                            v-model="time"
                            value-format="yyyy-MM-dd"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label-width="500px">
            <el-button type="primary"
                       @click="dataFormSubmitHandle()">确认发布</el-button>
            <el-button type="primary"
                       @click="draftDataFormSubmitHandle()">存草稿箱</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </el-card>
</template>
<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
import AddOrUpdate from './news-add-or-update'
export default {
  data () {
    return {
      dataForm: {
        id: '',
        newsCateroryId: '',
        newsTitle: '',
        newsReleaseStartTime: '',
        newsReleaseEndTime: '',
        newsContent: '',
        newsImageUrl: '',
        newsProperty: '',
        sectionCode: 'home_page_news',
        allDeptIdsShow: []
      },
      time: [],
      options: [],
      categorys: [],
      loading: false,
      // 富文本
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block', 'image'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean']
      ],
      uploadUrl: '',
      // 富文本end
      fileList: []
    }
  },
  activated () {
    this.getListCategory()
  },
  watch: {
    'dataForm.allDeptIdsShow': function (val) {
    }
  },
  created () {
    this.$http
      .get(`/sys/user/deptOptions/getAllByLoginUser`)
      .then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      })
      .catch(() => { })
    this.getListCategory()
    this.visible = true
    this.$nextTick(() => {
      this.dataForm.communityId = this.dataForm.streetId = this.dataForm.gridId = null
      // 富文本
      this.hideUpload = false
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
      if (this.quillEditor) {
        this.quillEditor.deleteText(0, this.quillEditor.getLength())
      } else {
        this.quillEditorHandle()
      }
      // 富文本end
    })
  },
  computed: {
    dataRule () {
      return {
        streetId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsTitle: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsCateroryId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsImageUrl: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsReleaseStartTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsContent: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    changeCaterory () {
      // 给新闻类别变量赋值
      let choosenItem = this.categorys.filter(item => item.id === this.dataForm.newsCateroryId)[0]
      this.dataForm.newsProperty = choosenItem.name
    },
    getListCategory () {
      this.$http.get(`/news/newscategory/category/${this.dataForm.sectionCode}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.categorys = res.data
      }).catch(() => { })
    },
    // 富文本编辑器
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      this.quillEditor.container.style.height = `${300}px`
      // // 自定义上传图片功能 (使用element upload组件)
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.dataForm.newsContent = this.quillEditor.root.innerHTML
        // if ((this.dataForm.newsContent).length > 10000) {
        //   return this.$message.error('您输入的的内容已超过字数')
        // }
      })
    },
    // 上传图片之前 (富文本)
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
    },
    // 上传图片成功 (富文本)
    uploadSuccessHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.url)
    },
    setRegistTime () {
      this.dataForm.newsReleaseStartTime = this.time[0]
      this.dataForm.newsReleaseEndTime = this.time[1]
    },
    // 上传图片end
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      // if ((this.dataForm.newsContent).length > 10000) {
      //   return this.$message.error('您输入的的内容已超过字数不能提交')
      // }
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http['post']('/news/news/publish', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.dataForm.id = ''
              this.dataForm.streetId = ''
              this.dataForm.communityId = null
              this.dataForm.gridId = null
              this.dataForm.newsCateroryId = ''
              this.dataForm.newsTitle = ''
              this.dataForm.newsReleaseStartTime = ''
              this.dataForm.newsReleaseEndTime = ''
              this.dataForm.newsContent = ''
              this.dataForm.newsImageUrl = ''
              this.dataForm.street = ''
              this.dataForm.community = null
              this.dataForm.grid = null
              this.dataForm.newsProperty = ''
              this.visible = false
              this.time = []
              this.quillEditor.root.innerHTML = ''
              this.dataForm.communityId = this.dataForm.streetId = this.dataForm.gridId = null
              this.communityList = this.gridList = []
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 存草稿
    draftDataFormSubmitHandle: debounce(function () {
      // if ((this.dataForm.newsContent).length > 10000) {
      //   return this.$message.error('您输入的的内容已超过字数不能提交')
      // }
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http['post']('/news/news/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.dataForm.id = ''
              this.dataForm.streetId = ''
              this.dataForm.communityId = null
              this.dataForm.gridId = null
              this.dataForm.newsCateroryId = ''
              this.dataForm.newsTitle = ''
              this.dataForm.newsReleaseStartTime = ''
              this.dataForm.newsReleaseEndTime = ''
              this.dataForm.newsContent = ''
              this.dataForm.newsImageUrl = ''
              this.dataForm.street = ''
              this.dataForm.community = null
              this.dataForm.grid = null
              this.dataForm.newsProperty = ''
              this.visible = false
              this.time = []
              this.quillEditor.root.innerHTML = ''
              this.dataForm.communityId = this.dataForm.streetId = this.dataForm.gridId = null
              this.communityList = this.gridList = []
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    handleAvatarSuccess (res, file) {
      this.loading = false
      this.dataForm.newsImageUrl = res.data.url
    },
    beforeAvatarUpload (file) {
      this.loading = true
      var that = this
      return new Promise((resolve, reject) => {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt1M = file.size / 1024 / 1024 < 1
        let bool = false
        // 判断是否符合格式要求
        if (isJPG || isPNG) {
          bool = true
        } else {
          that.$message.error('上传文件必须是jpg、png格式!')
          return false
        }
        // 如果格式符合要求，但是size过大，对图片进行处理
        if (bool && !isLt1M) {
          let image = new Image()
          let resultBlob = ''
          image.src = URL.createObjectURL(file)
          image.onload = () => {
            resultBlob = that.compressUpload(image)
            resolve(resultBlob)
          }
        } else if (bool && isLt1M) {
          resolve(file)
        }
      })
    },
    compressUpload (image) {
      // 创建画布元素
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let { width } = image
      let { height } = image
      canvas.width = width
      canvas.height = height
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(image, 0, 0, width, height)
      // 等比压缩
      let compressData = canvas.toDataURL('image/jpeg', 0.8)
      // base64转Blob
      let blobImg = this.dataURItoBlob(compressData)
      return blobImg
    },
    dataURItoBlob (data) {
      let byteString
      if (data.split(',')[0].indexOf('base64') >= 0) {
        // 转二进制
        byteString = atob(data.split(',')[1])
      } else {
        byteString = unescape(data.split(',')[1])
      }
      let mimeString = data
        .split(',')[0]
        .split(':')[1]
        .split('')[0]
      let ia = new Uint8Array(byteString.length)
      for (let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], { type: mimeString })
    },
    handelError () {
      this.loading = false
    }
  },
  components: {
    AddOrUpdate
  }
}
</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>
