<template>
  <!-- 表单渲染 -->
  <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelView" :visible="visible" :title="title" width="1080px">
    <el-form ref="formViewRef" :model="formData" :rules="rules" :status-icon="true" label-width="240px">
      <el-form-item label="资讯分类：" class="form-cell" style="margin: 0">
        <div class="cell-box" style="display: flex">
          <el-form-item prop="type">
            <el-select v-model="formData.type" placeholder="请选择">
              <el-option v-for="item in dict.information_type" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item label="标题：" class="form-cell" prop="title">
        <div class="cell-box">
          <el-input v-model="formData.title" placeholder="单行输入" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item v-show="formData.type>=4" label="链接：" class="form-cell" prop="url">
        <div class="cell-box">
          <el-input v-model="formData.url" placeholder="单行输入" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item v-show="formData.type" label="照片：" class="form-cell" prop="productPic">
        <div class="cell-box">
          <ul class="el-upload-list el-upload-list--picture-card" style="float: left">
            <li v-for="(item, index) in imgList" :key="index" tabindex="0" class="el-upload-list__item is-success">
              <img :src="imgSrcStart+item" class="el-upload-list__item-thumbnail">
              <label class="el-upload-list__item-status-label"><i class="el-icon-upload-success el-icon-check" /></label>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="dialogImgUrl=item;dialogImgVisible=true"><i class="el-icon-zoom-in" /></span>
                <span class="el-upload-list__item-delete" @click="handleRemoveImg(item)"><i class="el-icon-delete" /></span>
              </span>
            </li>
          </ul>
          <el-dialog append-to-body :visible.sync="dialogImgVisible">
            <img width="100%" :src="imgSrcStart+dialogImgUrl">
          </el-dialog>
          <el-upload
            ref="uploadCom"
            action="/api/bsw/common/uploadPicture"
            name="multipartFile"
            :data="{mark:'news'}"
            list-type="picture-card"
            :headers="uploadHeaders"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleImported"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <div slot="trigger" @click="handlePushClick($event)">
              <i class="el-icon-plus" />
            </div>
          </el-upload>
          <el-dialog append-to-body :visible.sync="dialogImageVisible">
            <img width="100%" :src="dialogImageUrl">
          </el-dialog>
        </div>
        <div style="display: none;clear: both">{{ formData.picture }}</div>
      </el-form-item>
      <el-form-item v-show="formData.type<4" label="来源：" class="form-cell" prop="source">
        <div class="cell-box">
          <el-input v-model="formData.source" placeholder="单行输入" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item v-show="formData.type<4" label="内容：" class="form-cell" prop="content">
        <div class="cell-box">
          <div ref="editor" class="editor" />
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button @click="cancelView">关闭</el-button>
      <!--      <el-button type="danger" @click="submitForm()">预览</el-button>-->
      <el-button type="primary" @click="submitForm()">保存</el-button>
      <el-button v-if="formData.newsPageId" type="success" @click="submitForm(true)">发布</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from '@/utils/auth'
import { HttpReq } from '@/api/common'
import { mapGetters } from 'vuex'
import { upload } from '@/utils/upload'
import E from 'wangeditor'

export default {
  dicts: ['information_type'],
  data() {
    return {
      uploadHeaders: { 'Authorization': getToken() },
      imgSrcStart: process.env.VUE_APP_BASE_API,
      editor: false, // 富文本对象
      dialogImageUrl: '',
      dialogImageVisible: false,
      imgList: [],
      dialogImgUrl: '',
      dialogImgVisible: false,
      visible: false,
      title: '资讯信息内容设置',
      formData: {
        newsPageId: null,
        title: '', // 标题
        type: '', // 类型
        source: '', // 来源
        content: '', // 内容
        picture: '', // 图片
        url: '' // 链接
      },
      rules: {}
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  mounted() {
  },
  methods: {
    handleExceed() {
      this.$message({
        message: '超出最大上传数量限制',
        type: 'info'
      })
    },
    handlePushClick(event) {
      if (this.formData.picture !== '') {
        event.stopPropagation()
        this.$message({
          message: '超出最大上传数量限制',
          type: 'info'
        })
      }
    },
    handleRemoveImg(item) {
      this.imgList.splice(this.imgList.indexOf(item), 1)
      const arr = this.formData.picture.split(';')
      arr.splice(arr.indexOf(item), 1)
      this.formData.picture = arr.join(';')
    },
    handleRemove(file, fileList) {
      HttpReq.backstageApi.deletePicture({
        multipartFile: file.response.pictures
      }).then((res) => {
        this.$notify({
          title: res.msg,
          type: 'success',
          duration: 2500
        })
        const arr = []
        fileList.forEach(item => {
          arr.push(item.response.pictures)
        })
        this.formData.picture = arr.join(';')
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleImported(response, file, fileList) {
      this.$nextTick(() => {
        const arr = this.formData.picture ? this.formData.picture.split(';') : []
        arr.push(response.pictures)
        this.formData.picture = arr.join(';')
        this.$notify({
          title: '上传成功！',
          type: 'success',
          duration: 2500
        })
      })
    },
    showView() {
      this.visible = true
    },
    hideView() {
      if (this.$refs.uploadCom) {
        this.$refs.uploadCom.clearFiles()
      }
      if (this.editor) {
        this.editor.txt.clear()
      }
      this.$refs.formViewRef.resetFields()
      this.visible = false
      this.imgList = []
      this.formData = {
        newsPageId: null,
        title: '', // 标题
        type: '', // 类型
        source: '', // 来源
        content: '', // 内容
        picture: '', // 图片
        url: '' // 链接
      }
    },
    cancelView() {
      this.hideView()
    },
    release() {
      HttpReq.backstageApi.releaseNewsPage({ ids: [this.formData.newsPageId] }).then((res) => {
        this.$notify({
          title: res.msg,
          type: res.code === 200 ? 'success' : 'error',
          duration: 2500
        })
        if (res.code === 200) {
          this.cancelView()
          this.$parent.loadData()
        }
      })
    },
    submitForm(isRelease) {
      this.$refs.formViewRef.validate((valid, obj) => {
        if (valid) {
          if (this.formData.newsPageId) {
            HttpReq.backstageApi.updateNewsPage(this.formData).then((res) => {
              this.$notify({
                title: res.msg,
                type: res.code === 200 ? 'success' : 'error'
              })
              if (res.code === 200) {
                if (isRelease) {
                  this.release()
                } else {
                  this.cancelView()
                  this.$parent.loadData()
                }
              }
            })
          } else {
            HttpReq.backstageApi.addNewsPage(this.formData).then((res) => {
              this.$notify({
                title: res.msg,
                type: res.code === 200 ? 'success' : 'error'
              })
              if (res.code === 200) {
                if (isRelease) {
                  this.release()
                } else {
                  this.cancelView()
                  this.$parent.loadData()
                }
              }
            })
          }
        } else {
          this.$message({
            message: '表单信息有误，请核对无误后提交！',
            type: 'error'
          })
        }
      })
    },
    loadData(newsPageId) {
      this.showView()
      this.$nextTick(() => {
        if (!this.editor) {
          const _this = this
          const editor = new E(this.$refs.editor)
          editor.config.zIndex = 5
          editor.config.customUploadImg = function(files, insert) {
            files.forEach(image => {
              upload(_this.imagesUploadApi, image).then(res => {
                const data = res.data
                const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
                insert(url)
              })
            })
          }
          editor.config.onchange = (html) => {
            this.formData.content = html
          }
          editor.create()
          this.editor = editor
        }
        if (newsPageId) {
          HttpReq.backstageApi.queryNewsPageById({ newsPageId }).then((res) => {
            if (res.code === 200) {
              this.formData = Object.assign(this.formData, res.data)
              if (this.formData.picture) {
                this.imgList = this.formData.picture.split(';')
              }
              this.editor.txt.html(this.formData.content)
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.grid-content {
  border: 1px solid rgba(100, 100, 100, 0.3);
  padding: 0;
}
.grid-label {
  background: #dedede;
  padding: 0 10px;
}
.editor{
  text-align:left;
  width: 680px;
}
::v-deep .w-e-text-container {
  height: 560px !important;
}
.cell-box {
  min-width: 120px;
  .cell-input {
    width: 420px;
  }
  .cell-select {
    width: 220px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 28px;
    line-height: 24px;
    padding: 0 8px;
  }
  .input-new-tag {
    width: 140px;
    height: 28px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  >>>.el-input__inner {
    border: 1px solid rgba(100, 100, 100, 0.1);
    border-bottom: 1px solid rgba(100, 100, 100, 0.2);
    border-radius: 5px;
  }
  >>>.el-input.is-disabled .el-input__inner {
    border-radius: 0;
    border: 0;
    border-bottom: 1px solid rgba(100, 100, 100, 0.4);
    background: white;
    cursor: text;
  }
  >>>.el-input.is-disabled .el-input__icon {
    cursor: text;
  }
  >>>.el-icon-circle-check {
    color: #13ce66;
  }
  //>>>.el-icon-arrow-up:before {
  //  content: '';
  //}
}
</style>
