<template>
  <div class="app-container">
    <base-form ref="ruleForm" class="lib-edit" :data="formData" :is-inline="false" label-width="60px" :insertSlotArr="[1]">
      <div class="scoped-textarea"  slot="OI1">
        <div class="st-text">洪楼科技</div>
        <textarea v-model="content" id="cTiny" style="height: 500px;width:100%;"></textarea>
      </div>
    </base-form>
    <div class="xl-form scoped-bottom">
      <el-button class="xl-form-btn t2" @click="close">关 闭</el-button>
      <el-button class="xl-form-btn t1" @click="close('confirm')">确定</el-button>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  name: 'edit',
  mixins,
  data() {
    const token = window.sessionStorage.getItem('fp_token')
    let domainUrl = process.env.VUE_APP_BASE_API
    return {
      domainUrl,
      token,
      formData: [],
      loading: true,
      cObj: {},
      content: '',
    }
  },
  created () {
    const query = this.$route.query
    if (query.id) {
      this.$api.house.adminformationdetail({id: query.id}).then(res => {
        let curData = res || {}
        this.cObj = curData || {}
        this.content = curData.content || ''
        this.getDef()
      })
    } else {
      this.content = '<p>这里开始</p>\n<p>&nbsp;</p>\n<p style=\"margin: 10px 16px; padding: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; clear: both; min-height: 1em; color: #333333; font-family: -apple-system, BlinkMacSystemFont, Arial, sans-serif; font-size: 17px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: 0.544px; text-transform: none; white-space: normal; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; line-height: 2em; text-indent: 2em; text-align: center;\"><span style=\"margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; font-size: 16px;\"><span style=\"margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; letter-spacing: 2px;\">-END-</span></span></p>\n<p><span style=\"margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; color: #333333; font-family: -apple-system, BlinkMacSystemFont, Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; orphans: 2; text-align: justify; text-indent: 34px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; letter-spacing: 2px;\"><img class=\"wscnph\" src=\"https://img2.honglounews.com/20210603040359-8175.gif\" /></span></p>'
      this.getDef()
    }
  },
  methods: {
    deactivated() {
      this.destroyTinymce()
    },
    destroyed() {
      this.destroyTinymce()
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get('cTiny')
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    },
    initTextarea () {
      const that = this
      tinymce.init({
        selector: '#cTiny',
        language: 'zh_CN', // 需要在官网自己下载一个全局的langs包。同时我提供的powerpaste本身自带一个langs包里面含中文，所以可以100%支持中文。
        plugins: [
          // plugins中，用powerpaste替换原来的paste
          'powerpaste advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak 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'],
        powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: 'propmt',// propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_data_images: true,
        images_upload_url: `${that.domainUrl}/adm/upload/cloudpub`,
        automatic_uploads: true,
        images_upload_handler: function (blobInfo, success, failure) {
          // 这个函数主要处理word中的图片，并自动完成上传；
          // ajaxUpload是自己定义的一个函数；在回调中，记得调用success函数，传入上传好的图片地址；
          // blobInfo.blob() 得到图片的file对象；
          // ajaxUpload(blobInfo.blob()).then((data) => {
          //   // 上传成功后，调用success函数传入图片地址
          //   success(data.uploadedImageUrl)
          // })
          const formData = new FormData();
          formData.append('upload', blobInfo.blob())
          formData.append('token', that.token)
          formData.append('logic_type', 'textcontent')
          console.log(formData)
          axios.post(`${that.domainUrl}/adm/upload/cloudpub`, formData)
          .then(function (res) {
              if (res.data.errno == 0) {
                let file = res.data.data
                success(file.url)
                return
              }
              failure('上传失败')
          })
          .catch(function (error) {
            failure('上传出错')
          })
        },
        // tinymce的其他配置参数
      })
    },
    getDef() {
      const params = { ...this.cObj }
      const disabled = false
      const remoteOptionsIds = []
      if (params.estate_list) {
        params.estate_id_list = params.estate_list.map(item => {
          remoteOptionsIds.push({ keyRO: item.estate_name, valRO: item.id })
          return item.id
        })
      } else {
        params.estate_id_list = []
      }
      // if (params.id) disabled = true
      this.formData = [
        { label: '标题', key: 'title' },
        { label: '分类', key: 'information_category', type: 'select', class: 'c-2', options: this.$dictData.information_category, changeHandle: this.cateChange },
        { label: '作者', key: 'author', class: 'c-2' },
        { label: '主图', key: 'pri_image', type: 'cuImg',
          options: {
            w: 375,
            h: 262,
          }, class: 'c-2' },
        { label: '状态', key: 'hide_status', type: 'select', class: 'c-2', options: this.$dictData.hide_status },
        { label: '时间', key: 'create_at', type: 'datePicker', type2: 'date'},
        { label: '楼盘', key: 'estate_id_list', type: 'selectRemote', multiple: true, changeHandle: this.deviceChange,
          remoteParams: { skey: 'estate_name', api: `house.admestatelist?search_EQ_status=1`, opKey: 'estate_name', opVal: 'id' },
          remoteOptions: remoteOptionsIds
        },
      ]
      this.setDefaultValue(params)
      window.setTimeout(() => {
        this.initTextarea()
      }, 10)
    },
    cateChange (val) {
      let params = {...this.$refs.ruleForm.baseForm}
      let imgURL= ''
      if (val === 'hlzt') imgURL= 'http://icon.honglounews.com/news_hlzt.jpg'
      if (val === 'hljy' || val === 'xqsc') imgURL= 'http://icon.honglounews.com/news_hljy.jpg'
      if (val === 'bkfx') imgURL= 'http://icon.honglounews.com/news_bkfx.jpg'
      if (val === 'lppc') imgURL= 'http://icon.honglounews.com/news_lppc.jpg'
      if (val === 'lpwd') imgURL= 'http://icon.honglounews.com/news_lpwd.jpg'

      if (val === 'hlpd') imgURL= 'http://icon.honglounews.com/news_hlpd.jpg'
      if (val === 'lszt') imgURL= 'http://icon.honglounews.com/news_lszt.jpg'
      if (val === 'zcjd') imgURL= 'http://icon.honglounews.com/news_zcjd.jpg'
      if (val === 'esf') imgURL= 'http://icon.honglounews.com/news_esf.jpg'
      if (val === 'lsdt') imgURL= 'http://icon.honglounews.com/news_lsdt.jpg'
      if (val === 'scfx') imgURL= 'http://icon.honglounews.com/news_scfx.jpg'
      params.pri_image = imgURL
      this.setDefaultValue(params)
    },
    close(str) {
      if (str === 'confirm') {
        this.$refs['ruleForm'].$refs['baseForm'].validate((valid) => {
          if (valid) {
            const oldform = this.$refs.ruleForm.baseForm
            const newForm = { ...oldform }
            if (this.cObj.id) newForm.id = this.cObj.id
            if (newForm.estate_id_list && newForm.estate_id_list.length > 0) {
              newForm.estate_id_list = newForm.estate_id_list.join(',')
            } else {
              newForm.estate_id_list = ''
            }
            let apiStr = 'adminformationadd'
            if (newForm.id) apiStr = 'adminformationedit'
            if (this.content) {
              newForm.content = this.content
            } else {
              this.$msg('请输入资讯文章内容')
              return
            }
            newForm.news_type = 'adminadd'
            this.$api.house[apiStr](newForm).then(data => {
              this.$msgs(newForm.id ? '编辑成功' : '新增成功')
              this.$router.push('/news/index')
            })
          }
        })
      } else {
        this.$router.push('/news/index')
        this.setDefaultValue()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../styles/libEdit.scss';
.lib-edit {
  width: 900px;
  padding-top: 0;
  padding-left: 0;
  padding-bottom: 40px;
  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
  ::v-deep .el-date-editor.el-input {
    width: 100%;
  }
}

.scoped-textarea {
  width: 100%;
  position: relative;
  margin-bottom: 20px;
  .st-text {
    position: absolute;
    bottom: 1px;
    right: 14px;
    background: #fff;
    font-size: 12px;
    z-index: 9;
    height: 16px;
    line-height: 16px;
    padding-left: 10px;
    padding-right: 10px;
    color: #595959;
    user-select: none;
  }
}

.scoped-bottom {
  position: fixed;
  bottom: 0;
  right: 0;
  background: #fff;
  width: 960px;
  box-sizing: border-box;
  padding-left: 380px;
  padding-bottom: 20px;
  padding-top: 20px;
  border-top: 1px solid #dcdcdc;
  z-index: 10;
}

::v-deep .el-drawer__body {
  padding-bottom: 30px;
}
</style>
