<template>
  <div class="mainPage">
    <img
      src="../assets/images/icon1.jpg"
      class="centerLabel cover bg"
      :class="{'grey': bgGrey}"
      style="z-index: 1;"
      @load="imgLoad"
      alt
    >
    <img
      src="../assets/images/icon2.png"
      width="100%"
      class="bg"
      :class="{'grey': bgGrey}"
      style="z-index: 3;top:0;left:0"
      @load="imgLoad"
      alt
    >
    <img
      src="../assets/images/icon15.png"
      width="100%"
      class="bg"
      :class="{'grey': bgGrey}"
      style="display:block;position:absolute;z-index: 3;bottom:0;left:0"
      @load="imgLoad"
      alt
    >
    <div class="canvasBox" :class="{'grey': bgGrey}" id="canvasBox">
      <canvas id="canvas"></canvas>
    </div>
    <div class="animateBg centerLabel" :class="{'active': animationOff}" style="z-index: 10;">
      <img src="../assets/images/icon4.png" alt>
    </div>
    <div class="prizeList centerLabel" :class="{'hide': !projectStart}">
      <img src="../assets/images/icon14.png" alt>
      <ul>
        <li v-for="(item, index) in prizeList" :key="index">
          <img src="../assets/images/icon6.png" width="100%" alt>
          <div class="flex-v">
            <div class="title">
              <img src="../assets/images/icon7.png" v-if="item.PrizeType === '特等奖'" alt>
              <img src="../assets/images/icon8.png" v-if="item.PrizeType === '一等奖'" alt>
              <img src="../assets/images/icon9.png" v-if="item.PrizeType === '二等奖'" alt>
              <img src="../assets/images/icon10.png" v-if="item.PrizeType === '三等奖'" alt>
              <img src="../assets/images/icon11.png" v-if="item.PrizeType === '纪念奖'" alt>
              <img src="../assets/images/icon12.png" v-if="item.PrizeType === '附加奖'" alt>
            </div>
            <div class="flex-item" style="margin-top: -20px;">
              <div class="centerLabel" style="width: 100%;">
                <div class="listImg">
                  <a>
                    <img :src="item.Picture" class="centerLabel contain" style="width: 80%;" alt>
                  </a>
                </div>
                <span>{{item.PrizeName}}</span>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="prizeBox centerLabel" :class="{'hide': hidePrize}">
      <div>
        <div>
          <img src="../assets/images/icon6.png" class="prizeBg" alt>
          <div class="prizeFlex flex-v">
            <div class="prizeTitle">
              <img
                src="../assets/images/icon7.png"
                width="100%"
                v-if="currentPrize.type === '特等奖'"
                alt
              >
              <img
                src="../assets/images/icon8.png"
                width="100%"
                v-if="currentPrize.type === '一等奖'"
                alt
              >
              <img
                src="../assets/images/icon9.png"
                width="100%"
                v-if="currentPrize.type === '二等奖'"
                alt
              >
              <img
                src="../assets/images/icon10.png"
                width="100%"
                v-if="currentPrize.type === '三等奖'"
                alt
              >
              <img
                src="../assets/images/icon11.png"
                width="100%"
                v-if="currentPrize.type === '纪念奖'"
                alt
              >
              <img
                src="../assets/images/icon12.png"
                width="100%"
                v-if="currentPrize.type === '附加奖'"
                alt
              >
            </div>
            <div class="flex-item">
              <div>
                <div class="centerLabel" style="width:80%;">
                  <div class="prizeImg">
                    <a>
                      <img
                        :src="currentPrize.img"
                        class="centerLabel"
                        style="max-width: 80%;max-height:80%;"
                        alt
                      >
                    </a>
                  </div>
                  <span>{{currentPrize.name}} {{currentPrize.num}}人</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <img src="../assets/images/icon5.png" class="prizeBg" alt>
          <div class="prizeFlex flex-v">
            <div class="prizeNameListTitle"></div>
            <div class="prizeNameList flex-item">
              <div>
                <div class="centerLabel" style="width:80%;margin-top: -30px;">
                  <ul class="flex-h">
                    <li
                      class="flex-item endListLi"
                      v-for="(item, index) in drawUsersArr"
                      :key="index"
                      :style="{maxWidth: item.width + 'px', minWidth: item.width + 'px'}"
                    >{{item.orgName}}-{{item.UserName}}</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="userList centerLabel">
      <ul class="flex-h">
        <li
          v-for="(item, index) in users"
          v-show="!item.delete"
          class="flex-item"
          :key="index"
          :class="{'active': item.active, 'activeLi': item.active, 'hide': !item.show}"
        >
          <span>{{item.orgName}}-{{item.UserName}}</span>
        </li>
      </ul>
    </div>
    <div class="drawUserList centerLabel">
      <ul class="flex-h">
        <li
          v-for="(item, index) in drawUsersArr"
          class="flex-item targetLi"
          :key="index"
          :class="{'active': item.active}"
        >
          <span>{{item.orgName}}-{{item.UserName}}</span>
        </li>
      </ul>
    </div>
    <div class="drawEndList">
      <a
        v-for="(item, index) in drawUsersArr"
        :key="index"
        :style="{width: item.width + 'px', left: item.startX + 'px', top: item.startY + 'px'}"
      >
        <span>{{item.orgName}}-{{item.UserName}}</span>
      </a>
    </div>
    <!-- <div class="line"></div> -->
  </div>
</template>

<script>
/* eslint-disable */
import '../assets/reset.css'
import getApi from '../apis.js'
import request from '../utils/request.js'
export default {
  name: 'draw',
  data () {
    return {
      animationOff: false,
      currentPrize: {
        img: '',
        name: '',
        num: '',
        type: ''
      },
      projectStart: true,
      hidePrize: true,
      prizeList: [],
      hidePrize: true,
      bgGrey: false,
      time: 300,
      drawCount: 10,
      imgTotal: 3,
      curImgNum: 0,
      status: false,
      sureStatus: true,
      arrTimer: null,
      users: [],
      initUsers: [],
      drawUsersArr: [],
      randomArr: [],
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      drawWidth: Math.floor(window.innerWidth * .7)
    }
  },
  created () {
    this.getUserList()
    this.getPrizeList()
  },
  mounted () {
    this.$nextTick(() => {
      this.canvasInit()
    })
  },
  methods: {
    canvasInit () { // canvas初始化
      const Snow = (canvas, count, options) => {
        canvas.width = document.body.clientWidth
        canvas.height = document.body.clientHeight
        const ctx = canvas.getContext('2d')
        const snowflakes = []
        const add = item => snowflakes.push(item(canvas))
        const update = () => _.forEach(snowflakes, el => el.update())
        const resize = () => {
          ctx.canvas.width = canvas.offsetWidth
          ctx.canvas.height = canvas.offsetHeight
          _.forEach(snowflakes, el => el.resized())
        }
        const draw = () => {
          ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight)
          _.forEach(snowflakes, el => el.draw())
        }
        const events = () => {
          window.addEventListener('resize', resize)
        }
        const loop = () => {
          draw()
          update()
          animFrame(loop)
        }
        const init = () => {
          _.times(count, () => add(canvas => new SnowItem(canvas, null, options)))
          events()
          loop()
        }
        init(count)
        resize()
        return {
          add, resize
        }
      }
      const defaultOptions = {
        color: 'red',
        radius: [0.5, 4.0],
        speed: [1, 3],
        wind: [-0.5, 3.0]
      }
      const SnowItem = (canvas, drawFn = null, opts) => {
        const options = { ...defaultOptions, ...opts }
        const { radius, speed, wind, color } = options
        const params = {
          color,
          x: _.random(0, canvas.offsetWidth),
          y: _.random(-canvas.offsetHeight, 0),
          radius: _.random(...radius),
          speed: _.random(...speed),
          wind: _.random(...wind),
          isResized: false
        }
        const ctx = canvas.getContext('2d')
        const updateData = () => {
          params.x = _.random(0, canvas.offsetWidth)
          params.y = _.random(-canvas.offsetHeight, 0)
        }
        const resized = () => params.isResized = true
        const drawDefault = () => {
          ctx.beginPath()
          ctx.arc(params.x, params.y, params.radius, 0, 2 * Math.PI)
          ctx.fillStyle = params.color
          ctx.fill()
          ctx.closePath()
        }
        const draw = drawFn ? () => drawFn(ctx, params) : drawDefault
        const translate = () => {
          params.y += params.speed
          params.x += params.wind
        }
        const onDown = () => {
          if (params.y < canvas.offsetHeight) return
          if (params.isResized) {
            updateData()
            params.isResized = false
          } else {
            params.y = 0
            params.x = _.random(0, canvas.offsetWidth)
          }
        }
        const update = () => {
          translate()
          onDown()
        }
        return {
          update,
          resized,
          draw
        }
      }
      const el = document.querySelector('.container')
      const wrapper = document.querySelector('body')
      const canvas = document.getElementById('canvas')
      const animFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame
      Snow(canvas, 800, {
        color: 'yellow'
      })
    },
    getUserList () { // 获取用户数据
      const api = getApi('user.list')
      request(api).then((res) => {
        this.initUsers = res.users.map(x => ({ ...x, active: false, show: true, delete: false, orgName: x.UserOrg }))
      })
    },
    getPrizeList () { // 获取奖品数据
      const api = getApi('prize.list')
      request(api).then((res) => {
        this.prizeList = res.prizes || []
      })
    },
    imgLoad () {
      this.curImgNum += 1 // 图片加载完 + 1
      if (this.curImgNum >= this.imgTotal) { // 图片加载完毕之后执行抽奖初始化逻辑
        this.initDraw()
      }
    },
    initDraw () { // 初始化抽奖
      document.getElementsByTagName('html')[0].onkeydown = (e) => { // 页面添加键盘点击事件监听
        e = e || event
        if (e.ctrlKey && e.keyCode == 13) { // 启停抽奖组合键：Ctrl + Enter
          this.sureStatus = true
          if (!this.status) { // 重新抽奖
            const api = getApi('draw')
            request(api).then((res) => {
              this.currentPrize = {
                img: this.prizeList.filter((item) => { if (item.PrizeName === res.winner[0].PrizeName) return item.Picture })[0].Picture,
                name: res.winner[0].PrizeName || '未知奖品',
                num: res.winner.length || 0,
                type: this.prizeList.filter((item) => { if (item.PrizeName === res.winner[0].PrizeName) return item.PrizeType })[0].PrizeType
              }
              this.winner = res.winner || []
              this.drawCount = res.winner.length || 0
              this.bgGrey = true
              this.projectStart = false
              this.status = !this.status
              this.users = []
              this.drawUsersArr = [] // 置空中奖数据
              this.calcRandomArr(this.initUsers.length > 90 ? 90 : this.initUsers.length, this.initUsers, this.users, 'UserId', this.drawCount)
              this.arrTimer = window.setInterval(() => {
                this.users = []
                this.calcRandomArr(this.initUsers.length > 90 ? 90 : this.initUsers.length, this.initUsers, this.users, 'UserId', this.drawCount)
              }, this.time)
            })
          } else { // 抽奖变换动画暂定
            this.status = !this.status
            clearInterval(this.arrTimer)
            this.arrTimer = null
            var num = 0
            this.users.map((item) => { // 记录中奖数据，以便读取过渡动画结束位置坐标
              if (item.active) {
                item.UserName = this.winner[num].UserName
                item.orgName = this.winner[num].UserOrg
                item.isReset = true
                num += 1
                this.drawUsersArr.push({ ...item, width: 0, startX: '', startY: '', listX: '', listY: '' })
              }
            })
            this.$nextTick(() => {
              this.drawUsersArr.map((item, index) => { // 记录中奖名单结束位置坐标
                item.endX = document.getElementsByClassName('targetLi')[index].getBoundingClientRect().x
                item.endY = document.getElementsByClassName('targetLi')[index].getBoundingClientRect().y
              })
              window.setTimeout(() => {
                this.drawUsersArr.map((item, index) => { // 记录中奖名单结束位置坐标
                  item.listX = document.getElementsByClassName('endListLi')[index].getBoundingClientRect().x
                  item.listY = document.getElementsByClassName('endListLi')[index].getBoundingClientRect().y
                })
              }, 50)
              for (var n = 0; n < this.drawCount; n++) { // 记录中奖名单开始位置坐标
                this.drawUsersArr[n].startX = document.getElementsByClassName('activeLi')[n].getBoundingClientRect().x
                this.drawUsersArr[n].startY = document.getElementsByClassName('activeLi')[n].getBoundingClientRect().y
                this.drawUsersArr[n].width = document.getElementsByClassName('activeLi')[n].getBoundingClientRect().width
              }
              this.drawUsersArr.map((item, index) => {
                item.UserId = this.winner[index].UserId,
                  item.UserName = this.winner[index].UserName,
                  item.orgName = this.winner[index].UserOrg
              })
              window.setTimeout(() => {
                this.users.map((item) => { // 隐藏未抽中数据
                  item.show = false
                })
                this.drawUsersArr.map((item) => {
                  item.startX = item.endX
                  item.startY = item.endY
                })
                window.setTimeout(() => {
                  this.animationOff = true
                }, 1000)
                window.setTimeout(() => {
                  this.bgGrey = false
                  this.hidePrize = false
                  this.drawUsersArr.map((item) => {
                    item.startX = item.listX
                    item.startY = item.listY
                  })
                }, 2500)
              }, 1000)
            })
          }
        }
      }
    },
    calcRandomArr (num, pArr, aArr, key, activeNum) {
      var randomNum = Math.floor(Math.random() * pArr.length), bool = false
      if (pArr.length > num) {
        aArr.map((item) => {
          if (item[key] === pArr[randomNum][key]) {
            bool = true
          }
        })
        if (!bool) aArr.push({ ...pArr[randomNum], active: false })
        if (aArr.length === num) {
          return this.returnSubArr(aArr, activeNum, 'active', 0)
        } else {
          this.calcRandomArr(num, pArr, aArr, key, activeNum)
        }
      } else {
        aArr.push(...pArr.map((item, index) => ({ ...item, active: false })))
        return this.returnSubArr(aArr, activeNum, 'active', 0)
      }
    },
    returnSubArr (arr, subNum, key, count) {
      var randomNum = Math.floor(Math.random() * arr.length)
      if (!arr[randomNum][key]) {
        arr[randomNum][key] = true
        count += 1
      }
      if (count < subNum) {
        this.returnSubArr(arr, subNum, key, count)
      } else {
        return arr
      }
    }
  }
}
</script>

<style>
.line {
  width: 1px;
  height: 100%;
  position: absolute;
  left: 699.25px;
  top: 0;
  background: #fff;
  z-index: 10000;
}
.mainPage {
  overflow: hidden;
  background: #000;
}
.bg {
  -webkit-filter: brightness(100%);
  filter: brightness(100%);
  transition: filter 0.3s linear;
  -webkit-transition: filter 0.3s linear;
  display: block;
  position: absolute;
}
.bg.grey {
  -webkit-filter: brightness(20%);
  filter: brightness(20%);
}
.canvasBox {
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 2;
  -webkit-filter: brightness(100%);
  filter: brightness(100%);
}
.canvasBox.grey{
  -webkit-filter: brightness(20%);
  filter: brightness(20%);
}
.animateBg {
  z-index: 5;
  overflow: visible;
}
.animateBg img {
  display: block;
  transition: all 1s ease-in-out;
  -webkit-transition: all 1s ease-in-out;
  transform: scale(0, 0);
  -webkit-transform: scale(0, 0);
  opacity: 1;
}
.animateBg.active img {
  transform: scale(1.3, 1.3);
  -webkit-transform: scale(1.3, 1.3);
  opacity: 0;
}
.prizeList {
  width: 100%;
  opacity: 1;
  transition: opacity 0.2s linear;
  -webkit-transition: opacity 0.2s linear;
  z-index: 10000;
  overflow: visible;
}
.prizeList.hide {
  opacity: 0;
}
.prizeList > img:first-child {
  height: 17vh;
  display: block;
  margin: 0 auto;
}
.prizeList > ul {
  width: 100%;
  font-size: 0;
  white-space: nowrap;
  overflow: visible;
  text-align: center;
  margin: 40px auto 0;
}
.prizeList > ul > li {
  width: 7.4%;
  min-width: 300px;
  max-width: 400px;
  display: inline-block;
  margin-left: 20px;
  position: relative;
  overflow: hidden;
}
.prizeList > ul > li:first-child {
  margin-left: 0;
}
.prizeList > ul > li > img {
  display: block;
  position: relative;
  z-index: 10;
}
.prizeList > ul > li > div {
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 11;
}
.prizeList > ul > li .title {
  width: 100%;
  padding-bottom: 24.4%;
  position: relative;
  overflow: hidden;
}
.prizeList > ul > li .title img {
  width: 100%;
  display: block;
  position: absolute;
  left: 0;
  top: 0;
}
.listImg {
  width: 57.5%;
  position: relative;
  overflow: hidden;
  margin: 0 auto;
}
.listImg a {
  width: 100%;
  display: block;
  height: 0;
  padding-bottom: 100%;
  border-radius: 100%;
  position: relative;
  overflow: hidden;
  background: #fff;
}
.listImg + span {
  width: 100%;
  display: block;
  text-align: center;
  color: #fff;
  font-size: 20px;
  line-height: 30px;
  margin-top: 20px;
}
.prizeList.hide {
  opacity: 0;
}
.prizeBox {
  width: 42%;
  min-width: 1700px;
  max-width: 1900px;
  overflow: visible;
  z-index: 500;
  opacity: 1;
  transition: opacity 0.3s linear;
  -webkit-transition: opacity 0.3s linear;
}
.prizeBox.hide {
  opacity: 0;
}
.prizeBox > div {
  width: 100%;
  position: relative;
  overflow: hidden;
}
.prizeBox > div > div:first-child {
  width: 31.8%;
  position: relative;
  overflow: hidden;
  float: left;
}
.prizeBox > div > div:last-child {
  width: 65%;
  position: relative;
  overflow: hidden;
  float: right;
}
.prizeBox > div > div > img.prizeBg {
  width: 100%;
  position: relative;
  display: block;
  z-index: 100;
}
.prizeFlex {
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 101;
}
.prizeTitle {
  width: 100%;
  padding-bottom: 24.4%;
  position: relative;
  overflow: hidden;
  height: 0;
}
.prizeNameListTitle {
  width: 100%;
  padding-bottom: 15%;
  position: relative;
  overflow: hidden;
  height: 0;
}
.prizeTitle img {
  display: block;
  position: absolute;
  left: 0;
  top: 0;
}
.prizeFlex > .flex-item {
  margin-top: -20px;
}
.prizeFlex > .flex-item > div {
  padding: 0 9.5%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
.prizeFlex > .flex-item.prizeNameList > div {
  padding: 0 5.7%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
.prizeFlex > .flex-item.prizeNameList > div ul {
  justify-content: center;
  flex-wrap: wrap;
  -webkit-flex-wrap: wrap;
  opacity: 0;
}
.prizeFlex > .flex-item.prizeNameList > div ul li {
  text-align: center;
  color: #fff;
  font-size: 20px;
  line-height: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 10px;
}
.prizeImg {
  width: 70%;
  position: relative;
  overflow: hidden;
  margin: 0 auto;
}
.prizeImg a {
  width: 100%;
  display: block;
  padding-bottom: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 100%;
  background: #fff;
  height: 0;
}
.prizeImg + span {
  width: 100%;
  display: block;
  text-align: center;
  color: #fff;
  font-size: 30px;
  line-height: 40px;
  margin-top: 20px;
}
.drawEndList {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  z-index: 600;
}
.drawEndList > a {
  display: inline-block;
  box-sizing: border-box;
  border-radius: 60px;
  border: 2px solid #e7963b;
  position: absolute;
  box-shadow: 0 0 0.2rem 0.15rem rgba(231, 150, 59, 0.2);
  transition: none 0.5s ease-out;
  -webkit-transition: none 0.5s ease-out;
  transition-property: left, top;
  -webkit-transition-property: left, top;
}
.drawEndList > a > span {
  width: 100%;
  display: block;
  line-height: 60px;
  border-radius: 60px;
  color: #fff;
  text-align: center;
  font-size: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  box-shadow: 0 0 0.2rem 0.15rem rgba(231, 150, 59, 0.2) inset;
}
.userList,
.drawUserList {
  width: 22%;
  min-width: 1500px;
  overflow: visible;
  z-index: 100;
}
.drawUserList {
  width: 44%;
  min-width: 750px;
  opacity: 0;
}
.userList > ul,
.drawUserList > ul {
  width: 100%;
  position: relative;
  overflow: visible;
  flex-wrap: wrap;
  -webkit-flex-wrap: wrap;
  transition: all 0.2s linear;
  -webkit-transition: all 0.2s linear;
  justify-content: center;
}
.userList > ul > li,
.drawUserList > ul > li {
  min-width: 10%;
  max-width: 10%;
  margin: 10px 0.5%;
  box-sizing: border-box;
  border: 2px solid #79321c;
  border-radius: 60px;
  overflow: hidden;
  opacity: 1;
  transition: all 0.2s linear;
  -webkit-transition: all 0.2s linear;
}
.drawUserList > ul > li {
  min-width: 20%;
  max-width: 20%;
  margin: 10px 1%;
}
.userList > ul > li.hide {
  opacity: 0;
}
.userList > ul > li > span,
.drawUserList > ul > li > span {
  width: 100%;
  display: block;
  line-height: 60px;
  border-radius: 60px;
  color: #777;
  text-align: center;
  font-size: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.userList > ul > li.active {
  border-color: #e7963b;
  box-shadow: 0 0 0.2rem 0.15rem rgba(231, 150, 59, 0.2);
}
.userList > ul > li.active > span {
  border-color: #e7963b;
  box-shadow: 0 0 0.2rem 0.15rem rgba(231, 150, 59, 0.2) inset;
  color: #fff;
}
</style>

