<style>
  .addimageText {
    width: 100%;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    background: rgba(0, 0, 0, 0.03);
  }

  .box_l {
    width: 400px;

  }

  .box_l_center {
    width: 370px;
    margin-left: 15px;
    border-radius: 5px;
  }

  .box_r {
    width: 800px;
    min-height: 100vh;
    background: #FFF;
    padding: 15px;
    position: relative;
    /* overflow: auto; */
  }

  .appmsg_account {
    background-color: #fff;
    padding: 10px 15px;
    display: flex;
    align-items: center;
    border-radius: 5px 5px 0 0;
  }

  .appmsg_one {
    width: 100%;
    height: 143px;
    position: relative;
    background: #999;
    color: #FFF;
  }

  .appmsg_two {
    width: 100%;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
  }
</style>
<template>
  <div class="addimageText">
    <div
      style="width: 100%;height: 40px;display: flex;align-items: center;position: fixed;top: 20px;left: 0;justify-content: center;">
      <div style="width: 800px;position: relative;">
        <div style="position: absolute;top: 5px;left: -160px;" v-if="addMsg.Type==1 || addMsg.Type==2">
          <q-btn-group push>
            <q-btn push label="图片" @click="getChoice(1),iscover=false" :disable="addMsg.Type==2?true:false" />
            <q-btn push label="小程序" @click="getapplet" />
          </q-btn-group>
        </div>
      </div>
    </div>
    <div class="box_r">
      <q-input clearable filled v-model="addMsg.Title" label="标题" maxlength="64" counter
        v-if="this.addMsg.Type != 2 && this.addMsg.Type != 5" style="margin-top: 20px;" />
      <q-input clearable filled v-model="addMsg.Author" label="作者" maxlength="8" counter v-if="addMsg.Type == 1"
        style="margin-top: 20px;" />
      <!-- 富文本 -->
      <div style="margin-top: 20px;" v-if="addMsg.Type != 4 && addMsg.Type != 5">
        <contributionUE :config="config" ref="UE_cb" @input="getcontnet" v-model="addMsg.Content">
        </contributionUE>
      </div>
      <span v-if='addMsg.Type==2' style="font-size: 11px;color: red;">*注:小程序和超链接会额外的占用字符</span>

      <div style="display: flex;align-items: flex-start;margin-top: 20px;" v-if="addMsg.Type == 1">
        <div v-if=" addMsg.CoverImageId==0"
          style="width:210px;height:90px;border:2px dashed #ebebeb;display: flex;align-items: center;justify-content: center;flex-direction: column;"
          @click="getChoice(0),iscover=true">
          <span style="font-size: 40px;">+</span>
          <span style="display: block; color: #7e8081;font-size: 14px;">选择封面</span>
        </div>
        <div v-if="addMsg.CoverImageId && addMsg.CoverImageId>0 && coverimg!='' " style="width:210px;height:90px"
          @click="getChoice(0),iscover=true">
          <el-image style="width: 100%; height: 100%" :src="coverimg" fit="cover"></el-image>
        </div>

        <q-input clearable filled v-model="addMsg.Description" label="描述/摘要" maxlength="120" counter type="textarea"
          bottom-slots style="margin-left: 20px;width: 500px;" />
      </div>
      <!-- 音频 -->
      <div v-if="addMsg.Type == 4">
        <q-input clearable filled v-model="addMsg.Description" label="可以输入140字以内的推荐语(选填)" maxlength="140" counter
          type="textarea" bottom-slots style="width: 100%;" />
        <div style="display: flex;align-items: center;">
          <audio :src="audiourl" controls="controls"></audio>
          <q-btn color="accent" class="q-mr-md" label="替换素材" @click="getChoice(2),iscover=true" size="sm"
            style="margin-left: 30px;" />
        </div>

      </div>
      <!-- 图片 -->
      <div v-if="addMsg.Type == 5">
        <q-input clearable filled v-model="addMsg.Description" label="可以输入140字以内的推荐语(选填)" maxlength="140" counter
          type="textarea" bottom-slots style="width: 100%;margin-top: 20px;" />
        <div style="display: flex;flex-wrap: wrap;width: 100%;">
          <draggable v-model="imgsList" style="display: flex;flex-wrap: wrap;width: 100%;">
            <div style="width: 178px;height: 178px;margin: 0 5px 10px;position: relative;cursor: grab"
              v-for="(x,y) in imgsList" :key='y'>
              <el-image style="width: 100%; height: 100%" :src="x.ImageUrl" fit="cover"></el-image>
              <q-icon style="position: absolute;right: 5px;top: 5px;color: #F56C6C;" name="iconfont icon-yiquxiao"
                size="24px" @click="ClearCarouse(y)"></q-icon>
            </div>
          </draggable>
          <div @click="getChoice(1)" class="cursor-pointer" v-if="imgsList.length<9"
            style="width: 178px;height: 178px;margin: 0 5px 10px;border: 1px dashed #d7d7d7;color: #9a9a9a;display: flex;flex-direction: column;align-items: center;justify-content: center;">
            <q-icon name="iconfont icon-add" size="24px"></q-icon>
            添加图片
          </div>
        </div>
        <!-- <div>封面预览</div>
                <div style="margin-top: 20px;display: flex;align-items: flex-start;">
                    <div style="width:210px;height:90px">
                        <el-image style="width: 100%; height: 100%" :src="coverimg" fit="cover"></el-image>
                    </div>
                    <q-btn color="accent" class="q-mr-md" label="上传封面图" @click="getChoice(0),iscover=true" size="sm"
                        style="margin-left: 30px;" />
                </div> -->

      </div>
      <!-- 不是管理端 -->
      <div style="margin-top: 20px;margin-bottom: 50px;" v-if="isManage==false">
        <q-btn color="accent" class="q-mr-md" label="暂存" @click="savemove(0)" style="width: 100px;"
          :loading="loading" />
        <q-btn color="accent" class="q-mr-md" label="提交并审核" @click="savemove(1)" style="width: 120px;"
          :loading="loading" />
        <q-btn class="q-mr-md" label="返回" @click="goblck()" style="width: 60px;" />
        <!-- <q-btn class="q-mr-md" label="推送" @click="tuisong()" style="width: 60px;" /> -->
      </div>
      <!-- 是管理端 -->
      <div v-if="isManage==true" style="margin-top: 20px;margin-bottom: 50px;border-top: 1px dashed #ebebeb;">
        <div style="display: flex;align-items: flex-end;">
          <q-input clearable standout="bg-primary text-white" v-model="SourceUrl" @input="$forceUpdate()"
            v-if="addMsg.Type==1" label="原文地址" style="margin-top: 20px;width: 500px;" />
          <span v-if="addMsg.Type==1" style="font-size: 11px;color: red;">*注:在图文消息页面点击“阅读原文”后的页面</span>
        </div>

        <div style="display: flex;align-items: center;margin: 10px 0 ;" v-if="addMsg.Type==1">
          封面图：
          <q-radio v-model="IsShowCover" val="1" label="显示" />
          <q-radio v-model="IsShowCover" val="0" label="不显示" />
          <span style="font-size: 11px;color: red;margin-left: 20px;">*注:封面图是否在正文中显示</span>
        </div>
        <div style="display: flex;align-items: center;margin: 10px 0 ;" v-if="addMsg.Type==1 || addMsg.Type==5 ">
          打开评论：
          <q-radio v-model="IsOpenComment" val="1" label="打开" />
          <q-radio v-model="IsOpenComment" val="0" label="不打开" />
        </div>
        <div style="display: flex;align-items: center;margin: 10px 0 ;"
          v-if="(addMsg.Type==1 || addMsg.Type==5) &&  IsOpenComment==1">
          粉丝才可评论：
          <q-radio v-model="IsFansCanComment" val="1" label="粉丝" />
          <q-radio v-model="IsFansCanComment" val="0" label="所有人" />
        </div>
        <div style="margin-top: 20px;">
          <q-btn color="accent" class="q-mr-md" label="保存" @click="savemoveManage(0)" style="width: 100px;"
            :loading="loading" />
          <q-btn color="accent" class="q-mr-md" label="预览" @click="savemoveManage(1)" style="width: 120px;"
            :loading="loading" />
          <q-btn color="accent" class="q-mr-md" label="保存并群发" @click="savemoveManage(2)" style="width: 120px;"
            :loading="loading" />
          <q-btn class="q-mr-md" label="返回" @click="goblck()" style="width: 60px;" />
          <!-- <q-btn class="q-mr-md" label="推送" @click="tuisong()" style="width: 60px;" /> -->
        </div>
      </div>
    </div>
    <!-- 选择文件 -->
    <q-dialog title="选择文件" v-model="getImgChoice" width="1200px">
      <ChooseImg @SelectId="SelectId" :type="type" @closeDia="getImgChoice=false"></ChooseImg>
    </q-dialog>
    <!-- 选择小程序 -->
    <q-dialog title="选择文件" v-model="getappletChoice" width="650px">
      <chooseApplet :type="addMsg.Type" @getresult='getresult' @closeDia="getappletChoice=false"></chooseApplet>
    </q-dialog>
    <q-dialog v-model="releasedialog" persistent transition-show="scale" transition-hide="scale">
      <q-card style="width: 600px;max-width:900px;">
        <q-card-section>
          <div class="text-h6">{{IsPreview==1?'预览发布':'保存群发'}}</div>
        </q-card-section>
        <q-card-section class="q-pt-none scroll" style="max-height: 70vh">
          <q-select filled stack-label option-value="Id" option-label="Name" v-model="PlatformId" ref="Id"
            :options="platTypeList" label="发布平台" :dense="false" emit-value map-options />
          <q-input v-if='IsPreview==1' clearable filled v-model="TagId" label="输入微信号" maxlength="30"
            style="margin-top: 20px;" />
          <q-select v-if='IsPreview==2' clearable filled stack-label option-value="id" option-label="name"
            v-model="TagId" style="margin-top: 20px;" :options="tagList" label="用户标签" :dense="false" emit-value
            map-options />
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white">
          <q-btn label="取消" flat color="grey-10" style="font-weight:400 !important" @click="closeCourseForm" />
          <q-btn label="立即提交" color="accent q-px-md" style="font-weight:400 !important" :loading="loading"
            @click="saveCourse" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>
<script>
  import contributionUE from './ue/contributionUE'
  import ChooseImg from '../components/ChooseImg'
  import chooseApplet from '../components/chooseApplet'
  import draggable from "vuedraggable"

  import {
    setContributeInfo,
    getContributeInfo,
    setContributeInfoPublish,
    setAdminContributeInfo,
    getGZHUserTagList
  } from '../../../api/teacher/contribution';
  import {
    GetContributePlatfrom, //获取平台
  } from '../../../api/system/wechat';
  export default {
    meta: {
      title: "新增/修改图文"
    },
    components: {
      contributionUE,
      ChooseImg,
      draggable,
      chooseApplet
    },

    data() {
      return {
        select: 1,
        releasedialog: false,
        Name: '',
        author: '',
        list: [],
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 500,
          zIndex: 99
        },
        importFileUrl2: this.domainManager().UploadFileUrl2,
        // this.domainManager().DomainUrl+'/api/upload/UploadImageTextFileToGZH',
        getImgChoice: false,
        getappletChoice: false,
        type: -1,
        ContributionType: 1, //进入的类型
        addMsg: {
          Id: 0,
          Type: 1,
          CoverImageId: 0,
          Title: '',
          Author: '',
          Description: '',
          VideoMediumId: 0,
          ImageList: [],
          Content: '',
          AuditState: 0,
          SendContent: '',
        },
        loading: false,
        iscover: false, //是否选择封面
        coverimg: '',
        audiourl: '', //音频地址
        imgsList: [], //图片消息的数据
        isManage: false, //是否是管理端
        IsPreview: 0, //1预览 2群发 0 只保存投稿 不发送
        TagId: '', //预览 =》 微信号（必传）； 群发 =》 标签ID
        PlatformId: 1, //发布的平台
        IsShowCover: '0', //是否显示封面，1为显示，0为不显示 （图文）
        SourceUrl: '', //	原文地址 （图文）
        IsOpenComment: '0', //是否打开评论，0不打开，1打开（图文 + 图片）	
        IsFansCanComment: '0', //是否粉丝才可评论，0所有人可评论，1粉丝才
        platTypeList: [], //平台列表
        tagList: [], //用户标签列表
      }
    },
    created() {
      if (this.$route.query && this.$route.query.type) {
        this.addMsg.Type = this.$route.query.type;
        if (this.addMsg.Type == 2 || this.addMsg.Type == 3) {
          this.config.initialFrameHeight = 200;
          this.config.toolbars = [
            ['undo', 'redo', 'link', 'unlink', ]
          ]
        }
        if (this.addMsg.Type == 2) {
          this.config.maximumWords = 300;
          this.config.wordCount = true;
        }
        // Todo 暂时不弄视频相关的东西
      }
      if (this.$route.query && this.$route.query.Id) { //编辑
        this.addMsg.Id = this.$route.query.Id;
        this.getdetails() //获取投稿详情
      } else { //没有id的话新增
        if (this.addMsg.Type == 4) {
          this.getImgChoice = true;
          this.iscover = true
          this.type = 2; //音频 这个自定义type 2为音频
        }
        if (this.addMsg.Type == 5) {
          this.getImgChoice = true;
          this.iscover = true
          this.type = 1; //音频 这个自定义type 1为图片
        }
      }
      if (this.$route.query && this.$route.query.isM) { //是否是管理端isM
        this.isManage = true;
        this.getPlatForm()
      }
    },
    mounted() {
      this.getGZHUserTagList() //获取公众号的用户标签
    },
    methods: {
      //获取已开放平台
      getPlatForm() {
        GetContributePlatfrom({}).then(res => {
          if (res.Code == 1) {
            this.platTypeList = res.Data;
          }
        })
      },
      getGZHUserTagList() {
        getGZHUserTagList({}).then(res => {
          if (res.Code == 1) {
            this.tagList = res.Data;
          }
        })
      },
      getdetails() {
        getContributeInfo({
          ContributeId: this.addMsg.Id
        }).then(res => {
          if (res.Code == 1) {
            this.addMsg = res.Data
            if (this.addMsg.Type == 1) {
              this.coverimg = res.Data.CoverImagePath
            } else if (this.addMsg.Type == 4) {
              this.audiourl = this.addMsg.VideoMediumPath
            } else if (this.addMsg.Type == 5) {
              this.imgsList = this.addMsg.ImageList
              this.coverimg = res.Data.CoverImagePath
            }
          }
        }).catch(() => {
        })
      },
      getChoice(type) {
        this.getImgChoice = true;
        this.type = type;
      },
      //选择图片
      SelectId(obj) {
        if (obj && obj.length > 0) {
          let data = []
          obj.forEach((x) => {
            let url = ''
            if (this.type == 1) {
              url = x.ImageUrl
            } else if (this.type == 2) {
              if (this.addMsg.Type == 1) {
                url = x.Path
              } else {
                url = x.Media_Id
              }

            } else if (this.type == 3) {
              url = x.VideoWXPath
            }
            let a = {
              fileName: x.MediaName,
              fileUrl: url
            }
            data.push(a)
          })
          if (this.type == 0) { //图片单选
            this.coverimg = obj[0].ImageUrl;
            this.addMsg.CoverImageId = obj[0].Id
          } else if (this.type == 1) { //图片多选
            if (this.addMsg.Type == 1) { //图文
              this.$refs.UE_cb.instertImage(data)
            } else { //图片消息
              if (this.imgsList.length == 0) {
                this.coverimg = obj[0].ImageUrl;
                this.addMsg.CoverImageId = obj[0].Id
              }
              this.imgsList = this.imgsList.concat(obj)
              if (this.imgsList.length > 9) {
                this.imgsList.slice(0, 9)
              }
            }
          }
          if (this.type == 2) {
            if (this.iscover == true) { //选择的音频
              this.audiourl = obj[0].Path;
              this.addMsg.VideoMediumId = obj[0].Id;
              this.addMsg.Title = obj[0].MediaName
            } else { //选择音频插入富文本
              this.$refs.UE_cb.insertaudio(data)
            }
          }
          if (this.type == 3) {
            this.$refs.UE_cb.insertVideo(data)
          }
          this.getImgChoice = false;
        }
      },
      ClearCarouse(index) { //删除图片
        this.imgsList.splice(index, 1);
      },
      successUpload(file) {
        if (file.Code == 1) {
          let data = [{
            fileName: file.Data.Name,
            fileUrl: this.domainManager().DomainUrl + '' + file.Data.HttpPath
          }]
          this.$refs.UE_cb.instertImage(data)
        }
      },
      savemove(type) { //普通的用户保存
        this.loading = true
        if (this.addMsg.Type == 5) {
          this.addMsg.ImageList = []
          this.imgsList.forEach(x => {
            let obj = {
              Id: x.Id,
              MediaName: x.MediaName
            }
            this.addMsg.ImageList.push(obj)
          })
        }
        this.addMsg.AuditState = type
        setContributeInfo(this.addMsg).then(res => {
          this.loading = false
          if (res.Code == 1) {
            this.$q.notify({
              icon: 'iconfont icon-chenggong',
              color: 'accent',
              timeout: 2000,
              message: res.Message,
              position: 'top'
            })
          }
        }).catch(() => {
          this.loading = false
        })
      },
      savemoveManage(type) { //管理的保存
        if (this.addMsg.Type == 5) {
          this.addMsg.ImageList = []
          this.imgsList.forEach(x => {
            let obj = {
              Id: x.Id,
              MediaName: x.MediaName
            }
            this.addMsg.ImageList.push(obj)
          })
        }
        if (type == 0) {
          let msg = JSON.parse(JSON.stringify(this.addMsg))
          msg.IsPreview = type;
          msg.TagId = '';
          msg.PlatformId = 0;
          if (this.addMsg.Type == 1) {
            msg.SourceUrl = this.SourceUrl
            msg.IsShowCover = this.IsShowCover
          }
          if (this.addMsg.Type == 1 || this.addMsg.Type == 5) {
            msg.IsOpenComment = this.IsOpenComment
            msg.IsFansCanComment = this.IsFansCanComment
          }
          this.loading = true
          setAdminContributeInfo(msg).then(res => {
            this.loading = false
            if (res.Code == 1) {
              this.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: res.Message,
                position: 'top'
              })
            }
          }).catch(() => {
            this.loading = false
          })
        } else { //预览 和 群发
          this.TagId = ''
          this.releasedialog = true
          this.IsPreview = type
        }
      },
      closeCourseForm() {
        this.releasedialog = false
      },
      saveCourse() {
        if (this.PlatformId == '') {
          this.$q.notify({
            type: 'negative',
            message: `请选择发布平台`,
            position: 'top'
          })
          return
        }
        if (this.IsPreview == 1 && this.TagId == '') {
          this.$q.notify({
            type: 'negative',
            message: `请输入预览的微信号`,
            position: 'top'
          })
          return
        }
        let msg = JSON.parse(JSON.stringify(this.addMsg))
        msg.IsPreview = this.IsPreview;
        msg.TagId = this.TagId;
        msg.PlatformId = this.PlatformId;
        if (this.addMsg.Type == 1) {
          msg.SourceUrl = this.SourceUrl
          msg.IsShowCover = this.IsShowCover
        }
        if (this.addMsg.Type == 1 || this.addMsg.Type == 5) {
          msg.IsOpenComment = this.IsOpenComment
          msg.IsFansCanComment = this.IsFansCanComment
        }
        this.loading = true
        setAdminContributeInfo(msg).then(res => {
          this.loading = false
          if (res.Code == 1) {
            this.$q.notify({
              icon: 'iconfont icon-chenggong',
              color: 'accent',
              timeout: 2000,
              message: res.Message,
              position: 'top'
            })
            this.releasedialog = false
          }
        }).catch(() => {
          this.loading = false
        })
      },
      goblck() { //返回上一个页面
        if (this.isManage == true) { //是管理端的时候返回投稿发布
          this.$router.push({
            path: '/teacher/contribution/contributemanage',
          });
        } else {
          this.$router.push({
            path: '/teacher/contribution/imageTextlist',
          });
        }
      },
      tuisong() {
        setContributeInfoPublish({
          ContributeId: 16,
          PlatformId: 1,
          IsPreview: 1,
          TagId: 'goodluck_cattle',
        }).then(res => {
        }).catch(() => {
          this.loading = false
        })
      },
      getapplet() { //小程序弹窗
        this.getappletChoice = true
      },
      getresult(data) { //选择小程序的结果
        this.getappletChoice = false
        this.$refs.UE_cb.applet(data)
      },
      getcontnet(data, length) {
        if (this.addMsg.Type == 2) {
          let obj = JSON.parse(JSON.stringify(data))
          let a = obj.replace(/<\/p>/g, '</p>\n') //处理换行的问题
          this.addMsg.Description = a.replace(/<\/?p[^>]*>/gi, '')
        } else {
          this.addMsg.Content = data
          this.addMsg.SendContent = JSON.parse(JSON.stringify(data))
          var reg = /data-time="(.*?)"/g;
          let _arr = []
          let deleteName = ''
          _arr = data.match(reg)
          if (_arr && _arr.length > 0) {
            var _res = []; //   
            _arr.sort();
            for (var i = 0; i < _arr.length;) {
              var count = 0;
              for (var j = i; j < _arr.length; j++) {
                if (_arr[i] == _arr[j]) {
                  count++;
                }
              }
              _res.push([_arr[i], count]);
              i += count;
            }
            //_res 二维数维中保存了 值和值的重复数  
            var _newArr = [];
            for (var i = 0; i < _res.length; i++) {
              _newArr.push({
                name: _res[i][0],
                num: _res[i][1]
              });
            }
            _newArr.forEach(x => {
              if (x.num == 2) {
                let a = new RegExp(
                  `<mp-miniprogram ${x.name}[^>]*>(.|\n)*<\/mp-miniprogram><span ${x.name}></span>`, 'g')
                this.addMsg.SendContent = this.addMsg.SendContent.replace(a, '')
              }
              // 清楚sengConent 里面不用的iframe
              let b = new RegExp(`<iframe[^>]*>(.|\n)*<\/iframe><span ${x.name}></span>`, 'g')
              this.addMsg.SendContent = this.addMsg.SendContent.replace(b, '')
            })
          }
        }
      },
    }
  }
</script>