<style>
.van-dialog__message--has-title {
  color: #000 !important;
}
</style>

<template>
  <div v-if="showPage">
    <model1 v-if="model === 1" @run='run' :prizeData='prizeData' :prizeNum='prizeNum' :data='data' :bg='bg1' :activityStatus='activityStatus' :residue='residue'></model1>
    <model2 v-if="model === 2" @run='run' :prizeData='prizeData' :prizeNum='prizeNum' :data='data' :bg='bg2' :activityStatus='activityStatus' :residue='residue'></model2>
    <model3 v-if="model === 3" @run='run' :prizeData='prizeData' :prizeNum='prizeNum' :data='data' :bg='bg3' :activityStatus='activityStatus' :residue='residue'></model3>
  </div>
</template>

<script>
// import { getToLogin } from '@/util/util'
import bg1 from '@/assets/bg1.png'
import bg2 from '@/assets/bg2.jpg'
import bg3 from '@/assets/bg3.jpg'
import wxsdk from '@/util/share'
import model1 from '@/components/model1'
import model2 from '@/components/model2'
import model3 from '@/components/model3'
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: mapAppActions } = createNamespacedHelpers('app')
export default {
  data () {
    return {
      bg1,
      bg2,
      bg3,
      round: false,
      showDialog: false,
      data: {
        userInfo: {},
        prize: {},
        prizeList: [],
        list: [],
        hasTitle: true
      },
      prizeData: {},
      prizeNum: false,
      winning: '',
      showBtn: false,
      jump: '',
      model: 0,
      showPage: false,
      activityStatus: 1,
      residue: 1
    }
  },
  components: {
    model1,
    model2,
    model3
  },
  created () {
    this.LotteryId(this.$route.query.lotteryId)
    // this.showPage = true
    // this.model = 3 // 模板
    if (location.search && this.toolClass.UrlSearch(location.search).code) {
      this.code = this.toolClass.UrlSearch(location.search).code
    } else {
      this.code = null
    }
    this.getUserInfo({ code: this.code, luckdrawid: this.lotteryId }).then((res) => {
      if (typeof (res) === 'object') {
        if (res.appid && res.appid !== '') {
          this.toolClass.getCode(res.appid)
        } else {
          this.data.userInfo = this.userInfo
          this.residue = this.data.userInfo.set.SurplusNum
          this.getData()
        }
      }
    }).catch((err) => {
      console.log(err)
    })
  },
  computed: {
    ...mapState({
      userInfo: x => x.app.userInfo,
      prize: x => x.app.prize,
      list: x => x.app.record,
      lotteryId: x => x.app.lotteryId,
      isRun: x => x.app.runState
    })
  },
  methods: {
    ...mapAppActions(['getUserInfo', 'getPrize', 'setPrize', 'getRecord', 'setUser', 'setRunState', 'LotteryId']),
    getData () {
      this.getPrize({ id: this.lotteryId }).then((res) => {
        this.showPage = true
        this.data.prize = this.prize
        this.data.prizeList = this.data.prize.Prizes
        for (let i = 0; i < this.data.prizeList.length; i++) {
          this.data.prizeList[i].PrizeName = this.data.prizeList[i].PrizeName ? this.data.prizeList[i].PrizeName : '谢谢参与'
        }
        this.model = res.TplId ? Math.floor(res.TplId) : 3 // 模板
        if (this.model === 1) {
          this.bg1 = res.Imgs ? res.Imgs[0].ImgUrl : this.bg1
        } else if (this.model === 2) {
          this.bg2 = res.Imgs ? res.Imgs[0].ImgUrl : this.bg2
        } else if (this.model === 3) {
          this.bg3 = res.Imgs ? res.Imgs[0].ImgUrl : this.bg3
        }
        this.data.hasTitle = res.Imgs ? 0 : 1
        this.activityStatus = this.data.prize.Status
        let now = new Date().getTime()
        let start = new Date(this.data.prize.BeginDate).getTime()
        let end = new Date(this.data.prize.EndDate).getTime()
        if (this.activityStatus === 1) {
          if (now < start) {
            this.activityStatus = 0
          } else if (now > start && now < end) {
            this.activityStatus = this.data.prize.Status
          } else if (now > end) {
            this.activityStatus = 9
          }
        } else if (this.activityStatus === -1) {

        } else {
          this.activityStatus = 9
        }
        wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]) }, { // 随模板变动
          title: res.ActivityTitle || res.Name,
          desc: res.ShareContent || '精美礼品免费抽取，机会有限，速来参与',
          link: `${window.location.origin}${window.location.pathname}#/from/${this.data.userInfo.user.CustomerId}?lotteryId=${this.lotteryId}`,
          thu_image: res.ShareImg || `https://spaceofcheng.oss-cn-beijing.aliyuncs.com/indexlogo.jpg?x-oss-process=style/wxicon`
        })
      })
      this.getRecord({ id: this.lotteryId }).then((res) => {
        this.data.list = this.list
      })
    },
    start () {
      return new Promise((resolve, reject) => {
        if (this.isRun) {
        } else {
          this.setRunState(1)
          this.setPrize({ id: this.lotteryId }).then((res) => {
            for (let i = 0; i < this.data.prizeList.length; i++) {
              if (this.data.prizeList[i].Id === res.prize.Id) {
                this.prizeData = res // 中奖数据
                this.prizeNum = i // 奖品位于奖品列表的第几条
              }
            }
            resolve(res)
          }).catch((err) => {
            console.log(err)
            reject(err)
            this.setRunState(0)
          })
        }
      })
    },
    run () {
      if (this.data.userInfo.user.Phone === '') {
        this.$dialog.confirm({
          title: '提示',
          message: '您不是城的空间会员，前往注册免费获取抽奖机会',
          confirmButtonText: '立即前往',
          cancelButtonText: '放弃机会',
          overlay: true,
          lockScroll: true
        }).then(() => {
          const luckshare = this.$route.params.id ? `&luckshare=${this.$route.params.id}` : ''
          window.location.href = `${window.location.origin}/wechat/user.html#/bindMobile?isLottery=1${luckshare}&lotteryId=${this.lotteryId}`
        }).catch(() => {
          return false
        })
      } else {
        if (this.activityStatus === -1) {
          this.$toast('当前活动已不存在')
          return
        }
        this.start().then((res) => {
          if (this.$route.params.id) {
            if (this.$route.query.isnew) {
              this.setUser({ toId: this.lotteryId, fromId: this.$route.params.id, isnew: this.$route.query.isnew })
            } else {
              this.setUser({ toId: this.lotteryId, fromId: this.$route.params.id })
            }
          } else {
            if (this.$route.query.isnew) {
              this.setUser({ toId: this.lotteryId, isnew: this.$route.query.isnew })
            }
          }
          this.getUserInfo({ code: this.code, luckdrawid: this.lotteryId }).then((res) => {
            if (typeof (res) === 'object') {
              if (res.appid && res.appid !== '') {
                this.toolClass.getCode(res.appid)
              } else {
                this.data.userInfo = this.userInfo
                this.residue = this.data.userInfo.set.SurplusNum
              }
            }
          }).catch((err) => {
            console.log(err)
          })
        }).catch(() => {
          this.setRunState(0)
        })
      }
    }
  },
  watch: {
    isRun: {
      handler (cur, old) {
        if (cur === 2) {
          this.setRunState(0)
          this.getRecord({ id: this.lotteryId }).then((res) => {
            this.data.list = this.list
          })
        }
      },
      immediate: false,
      deep: false
    }
  }
}
</script>
