<template>
  <div class="poper-wrap wx_phone_preview_wrp jsPhoneView">
    <div class="mask"></div>
    <div class="wx_phone_preview">
      <span class="btn btn_default btn_phone_preview_closed jsPhoneViewClose" @click="hidePreviewPoper">关闭</span>
      <div class="wx_phone jsPhoneViewMain">
        <div class="wx_phone_hd" v-text="title"></div>
        <div  v-if="previewState === 'card'" class="wx_phone_bd wx_phone_preview_card_wrp">
          <div class="msg_card wx_phone_preview_multi_card has_first_cover">
            <div class="card_media">
              <div v-for="(article, index) in articles" class="jsPhoneViewCard" :class="{'sub_card_media': index > 0}" :key="index" :data-index="index">
                <div class="card_appmsg">
                  <div class="card_appmsg_inner">
                    <div class="weui-desktop-vm_primary card_appmsg_hd">
                      <strong class="card_appmsg_title" :title="article.title" v-text="article.title"></strong>
                    </div>
                    <div class="weui-desktop-vm_default card_appmsg_bd">
                      <div class="card_appmsg_thumb" :style="{'background-image':'url(' + prefix + article.logoFile + ')'}"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="previewState === 'moments'" class="wx_phone_bd">
            <div class="wx_phone_preview_moments" v-for="(article, index) in articles" :key="index">
                <img class="moments_user_avatar" src="@static/assets/images/socialmedia/zvinglogo.jpg" alt="泽元软件">
                <div class="moments_content_wrp">
                    <p class="moments_nickname">泽元软件</p>
                    <div class="moments_content jsPhoneViewCard" :data-index="index">
                        <img class="moments_appmsg_thumb" :src="prefix + article.logoFile">
                        <div class="moments_appmsg_title" :title="article.title" v-text="article.title"></div>
                    </div>
                </div>
            </div>
        </div>
        <div v-if="previewState === 'chat'" class="wx_phone_bd wx_phone_preview_chat_wrp">

            <div class="wx_phone_preview_chat" v-for="(article, index) in articles" :key="index">
                <img class="chat_user_avatar" src="@static/assets/images/socialmedia/zvinglogo.jpg">
                <div class="chat_content">
                    <div class="chat_appmsg_msg jsPhoneViewCard" data-index="0">
                        <div class="chat_appmsg_title" :title="article.title" v-text="article.title"></div>
                        <div class="chat_appmsg_content">
                            <img class="chat_appmsg_thumb" :src="prefix + article.logoFile">
                            <div class="chat_appmsg_desc" :title="article.summary" v-text="article.summary"></div>
                        </div>
                        <span class="chat_arrow_wrp">
                            <i class="chat_arrow arrow_out"></i>
                            <i class="chat_arrow arrow_in"></i>
                        </span>
                    </div>
                </div>
            </div>
        </div>
      </div>

      <div class="wx_view_container jsPhoneViewPlugin">
        <div>
          <ul class="wx_view_list">
            <li class="wx_view_item jsPhoneViewLink" @click="changePreviewState('card')" :class="{'selected': previewState === 'card'}" data-id="card">会话消息</li>
            <li class="wx_view_item jsPhoneViewLink" @click="changePreviewState('moments')" :class="{'selected': previewState === 'moments'}" data-id="moments">分享到朋友圈</li>
            <li class="wx_view_item jsPhoneViewLink" @click="changePreviewState('chat')" :class="{'selected': previewState === 'chat'}" data-id="chat">发送给朋友</li>
          </ul>
          <div class="btn_wx_phone_preview_wrp">
            <a class="btn btn_default btn_wx_phone_preview jsPhoneViewPub" @click="toggleSendDialogVisible">发送到手机预览</a>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="发送预览" :visible.sync="sendDialogVisible" :append-to-body="true" width="726px">
      <div class="send_preview">
      <div class="preview_form_box">
        <label class="frm_label">关注公众号后才能接收图文消息预览，多个微信号用逗号分开</label>
        <el-input placeholder="请输入微信账号" v-model="tousers" ></el-input>
        <p class="frm_tips">预览功能仅用于公众号查看文章效果，不适用于公众传播，预览链接会在短期内失效。预览接口每天最多调用100次，请勿滥用。</p>
        <div class="frm_msg_wrp frm_msg">
            <div class="fail" v-if="sendResult.errorMessage !== null" v-text="sendResult.errorMessage"></div>
            <p v-if="sendResult.sameResultData !== null" c :class="{'fail':sendResult.sameResultData.errcode !== 0, 'success': sendResult.sameResultData.errcode === 0}" v-text="sendResult.sameResultData.message"></p>
            <div v-if="sendResult.multiResultData.length > 0">
              <div class="send-result-item" v-for="(result,index) in sendResult.multiResultData" :key="index">
                <p :class="{'fail':result.errcode !== 0, 'success': result.errcode === 0}"><span class="send-result-wxname" v-text="result.wxname"></span>: <span v-text="result.message"></span></p>
              </div>
            </div>
        </div>
      </div>
      <div class="user_list jsAccountList" v-if="accountList.length > 0">
          <div class="user jsAccount" v-for="(user,index) in accountList" @click="addToCurrent(index)" :key="index" :data-value="user">
              {{user}}<a href="javascript:;" class="opt jsAccountDel" @click.stop.prevent="delAccount(index)" :data-index="index">x</a>
          </div>
      </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="toggleSendDialogVisible">取 消</el-button>
        <el-button type="primary" @click="doSendPreview" :disabled="tousers.length < 6" :loading="sendLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import './wxpreview.css'
import {union, dropRight, filter, map, uniq} from 'lodash'
let titleObj = {
  card: '泽元软件',
  moments: '朋友圈',
  chat: '泽元软件'
}
let storageKey = 'WX_PREVIEW_USERS'
let storageAccountLength = 10
export default {
  data() {
    return {
      previewState: 'card', // card || moments || chat
      sendDialogVisible: false,
      tousers: '',
      sendResult: {
        sameResultData: null,
        errorMessage: null,
        multiResultData: []
      },
      accountList: [],
      sendLoading: false
    }
  },
  props: {
    // mediaid用于手机预览时同步素材到微信服务器，然后发送到指定的微信用户
    mediaid: [String, Number],
    prefix: String,
    articles: Array,
    weixinid: [String, Number],
    weixinname: {
      type: String,
      default: '泽元软件'
    }
  },
  created() {
    titleObj.card = this.weixinname
    this.loadSendedAccounts()
  },
  computed: {
    title() {
      return titleObj[this.previewState]
    }
  },
  methods: {
    changePreviewState(state) {
      this.previewState = state
    },
    hidePreviewPoper() {
      this.$emit('hide')
    },
    toggleSendDialogVisible() {
      this.sendDialogVisible = !this.sendDialogVisible
    },
    // 加载发送成功的用户信息
    loadSendedAccounts() {
      let savedUsers = localStorage[storageKey + '_' + this.weixinid] || []
      if (typeof savedUsers === 'string' && savedUsers.startsWith('[')) {
        savedUsers = JSON.parse(savedUsers)
      }
      this.accountList = savedUsers
    },
    // 保存发送成功的微信用户信息到localStorage
    saveSendedAccounts() {
      let resData = this.sendResult.multiResultData
      if (resData !== null) {
        let successAccounts = filter(resData, function(item) {
          return String(item.errcode) === '0'
        })
        let wxnames = map(successAccounts, 'wxname')
        this.updateSavedAccounts(wxnames)
      } else if (this.sendResult.sameResultData !== null) {
        let res = this.sendResult.sameResultData
        if (String(res.errcode) === '0') {
          let usersArr = this.tousers.replace(/，/g, ',').split(',')
          let existUsers = localStorage[storageKey + '_' + this.weixinid] || []
          let users = union(usersArr, existUsers)
          this.updateSavedAccounts(users)
        }
      }
    },
    updateSavedAccounts(accounts) {
      accounts = accounts || this.accountList
      this.accountList = accounts.length > storageAccountLength ? dropRight(accounts, accounts.length - storageAccountLength) : accounts
      localStorage[storageKey + '_' + this.weixinid] = JSON.stringify(this.accountList)
    },
    addToCurrent(index) {
      let curUser = this.accountList[index]
      let usersStr = this.tousers === '' ? curUser : this.tousers + ',' + curUser
      this.tousers = uniq(usersStr.split(',')).join(',')
    },
    delAccount(index) {
      this.accountList.splice(index, 1)
      this.updateSavedAccounts()
    },
    async doSendPreview() {
      let toUsers = this.tousers.replace(/，/g, ',')
      this.sendResult.sameResultData = null
      this.sendResult.errorMessage = null
      this.sendResult.multiResultData = []
      this.sendLoading = true
      let res = await axios.put(`/ui/wechat/medias/${this.mediaid}/sendpreview`, { weiXinID: this.$route.params.weiXinID, tousers: toUsers })
      this.sendLoading = false
      let resData = res.data.message
      try {
        if (resData.startsWith('[{')) {
          // 多条记录发送结果不一致
          this.sendResult.multiResultData = JSON.parse(resData)
        } else if (resData.startsWith('{')) {
          // 发送结果相同
          this.sendResult.sameResultData = JSON.parse(resData)
        } else {
          // 发送失败
          this.sendResult.errorMessage = resData
        }
        this.saveSendedAccounts()
      } catch (e) {
        this.sendResult.errorMessage = '发生未知错误'
      }
    }
  }
}
</script>
<style scoped>
.send_preview {
  padding: 66px 45px 108px;
}
.preview_form_box,
.user_list {
  width: 405px;
  margin: 0 auto;
}
.send_preview .user {
  float: left;
  margin-right: 10px;
  border: 1px solid #e7e7eb;
  cursor: pointer;
  padding: 0 0.5em;
  background-color: #e5e7ec;
}
.send_preview .user .opt {
  font-size: 0;
  text-indent: -999em;
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAWElEQVR42mNgGLogNzdXBB8fKygpKRErLS3dW1pQYATig2gQHyROUHNxcTFYcVlxcQyIBvGJdi5QQ1xZSclZEE28JqjzQJqQnU2UH2HOI8mP6IqICtVhCgAXuzGKMKHRXgAAAABJRU5ErkJggg==);
  width: 14px;
  height: 14px;
  vertical-align: middle;
  display: inline-block;
}
.send_preview .user .opt:hover {
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAtElEQVR42mNgQAKrVq1SWb16dcrqlSs7gXgqmAbyQeIM2EBDQwPTmpUrI9asWjUTJwbKAw1gYkCzKQavJigGqYNrWrFihRKy5LatWxfi44PUgzWC/AAT3L59++L3798/PXz48FoQH0SD+CBxmBqQepjGbmQTYYqvXL68H9kQuEZggIE1YvMLSNPnz59fg2h0OVBoU2Yj2X4ERS6yiciKsIUqSmIgGPlIiQA9AZCXcshOq+QAALVsiODjKVsCAAAAAElFTkSuQmCC);
}
.frm_label {
  display: block;
  padding-bottom: 0.5em;
}
.frm_tips {
  color: #8d8d8d;
  padding-top: 4px;
}
.frm_msg .fail {
  padding-top: 6px;
  color: #e15f63;
}
.frm_msg .success {
  padding-top: 6px;
  color: #67C23A;
}
.frm_msg .send-result-wxname {
  font-weight:bold
}
</style>
