<template>
  <div
    class="home"
    @mousedown="onMouseDown"
    @mousemove="onMouseMove"
    @mouseup="onMouseUp"
    @mouseleave="onMouseLeave"
    @wheel.passive="onWheel"
    @dragstart.prevent
  >
    <div
      ref="landscape-wrap"
      class="landscape-wrap"
      :style="{
        left: landscapePositionleft,
      }"
    >
      <img
        v-for="index in 3"
        :key="index"
        class="landscape"
        src="@/assets/landscape.png"
        alt=""
        @dragstart.prevent
      >
    </div>
    <div
      class="people-far-wrap"
      :style="{
        right: peopleFarPositionRight,
      }"
    >
      <img
        class="people-far"
        :class="peopleFarColorStatus"
        src="@/assets/people-far-serial-frame-400-600-60.png"
        alt=""
        @dragstart.prevent
      >
      <HotSpot
        class="hot-spot"
        @click="onClickPeopleFarHotSpot"
      />
    </div>
    <div
      class="people-near-wrap"
      :style="{
        left: peopleNearPositionLeft,
        zIndex: [0, 2].includes(tourState) ? 2 : 0,
      }"
    >
      <img
        class="people-near"
        src="@/assets/people-near.png"
        alt=""
        @dragstart.prevent
      >
      <img
        v-if="[0, 2].includes(tourState)"
        ref="treasure"
        class="treasure"
        :style="{
          opacity: tourState === 0 ?
            treasureFadeInProgress / treasureFadeInProgressRightBorder :
            1 - treasureFadeOutProgress / treasureFadeOutProgressRightBorder,
        }"
        src="@/assets/treasure.png"
        alt=""
        @dragstart.prevent
      >
    </div>
    <img
      class="introduce"
      :style="{
        left: introducePositionLeft,
      }"
      src="@/assets/introduce.png"
      alt=""
      @dragstart.prevent
    >

    <div
      v-if="[0, 1, 2].includes(tourState)"
      class="fade-mask"
      :style="{
        opacity: tourState === 0 ?
          treasureFadeInProgress / treasureFadeInProgressRightBorder :
          1 - treasureFadeOutProgress / treasureFadeOutProgressRightBorder
      }"
    />

    <div
      v-if="[1].includes(tourState)"
      class="treasure-frames-wrap"
    >
      <img
        v-for="index of treasureFrameTotalNum"
        v-show="treasureFrameCurNum === index - 1 ||
          treasureFrameCurNum - 1 === index - 1
        "
        :key="index"
        class="treasure-frame"
        :src="require(`@/assets/treasure-frames/文物序列帧-${(index-1).toString().padStart(7, '0')}.png`)"
        alt=""
        @load="onTreasureFrameLoad(index - 1)"
        @error="onTreasureFrameError(index - 1)"
      >
    </div>
  </div>
</template>

<script>
const initialPeopleNearPositionLeft = '25%'
const initPeopleFarPositionRight = '10%'
const landscapeSpeedRate = 0.01
const peopleFarSpeedRate = 0.2
const peopleNearSpeedRate = 0.8
const introduceSpeedRate = 1
const treasureFadeInProgressRightBorder = 2000
const treasureDisplayProgressRightBorder = 3000
const treasureFadeOutProgressRightBorder = 2000
const treasureFrameTotalNum = 100

export default {
  name: 'HomeView',
  components: {
  },
  data() {
    return {
      // 鼠标拖拽相关
      isMouseDown: false,
      lastMoveEventTimeStamp: 0,
      moveSpeed: 0,

      // 动画帧相关
      lastAnimationTimeStamp: 0,
      animationFrameId: null,

      tourState: 0, // 0:文物淡入过渡阶段；1:文物三维展示阶段；2：文物渐出过渡阶段；3：镜头平移阶段

      // 镜头平移相关
      translateLength: 0,
      landscapePositionleft: '18.491%',
      peopleFarPositionRight: initPeopleFarPositionRight,
      peopleNearPositionLeft: initialPeopleNearPositionLeft,
      introducePositionLeft: '3.347%',

      // 文物淡入相关
      treasureFadeInProgress: 0,
      treasureFadeInProgressRightBorder,
      treatureFadeInInitialLeft: 0,
      treatureFadeInInitialTop: 0,
      treatureFadeInFinalLeft: 0,
      treatureFadeInFinalTop: 0,

      // 文物展示相关
      treasureDisplayProgress: 0,
      treasureFrameTotalNum,
      treasureFrameCurNum: 0,
      treasureFrameStateList: new Array(treasureFrameTotalNum),

      // 文物淡出相关
      treasureFadeOutProgress: 0,
      treasureFadeOutProgressRightBorder,

      // 远处人物变色相关
      peopleFarColorStatus: 'no-color', // 'no-color', 'color'
      isPeopleFarColorChanging: false,
    }
  },
  watch: {
    treasureFadeInProgress: {
      handler(vNew, vOld) {
        if (vOld < this.treasureFadeInProgressRightBorder && vNew >= this.treasureFadeInProgressRightBorder && this.tourState === 0) {
          this.tourState = 1
        }

        this.$refs.treasure.style.left = this.treatureFadeInInitialLeft + this.treasureFadeInProgress / treasureFadeInProgressRightBorder * (this.treatureFadeInFinalLeft - this.treatureFadeInInitialLeft) + 'px'
        this.$refs.treasure.style.top = this.treatureFadeInInitialTop + this.treasureFadeInProgress / treasureFadeInProgressRightBorder * (this.treatureFadeInFinalTop - this.treatureFadeInInitialTop) + 'px'
        this.$refs.treasure.style.transform = `translate(-50%, -50%) scale(${1 + this.treasureFadeInProgress / treasureFadeInProgressRightBorder * (10 - 1)})`
      }
    },
    treasureDisplayProgress: {
      handler(vNew, vOld) {
        // 更新toureState
        if (vOld > 0 && vNew <= 0 && this.tourState === 1) {
          this.tourState = 0
        } else if (vOld < treasureDisplayProgressRightBorder && vNew >= treasureDisplayProgressRightBorder && this.tourState === 1) {
          this.tourState = 2
        }

        let idealCurNum = Math.round(this.treasureDisplayProgress / treasureDisplayProgressRightBorder * treasureFrameTotalNum)

        while (this.treasureFrameStateList[idealCurNum] === false) {
          idealCurNum--
        }
        this.treasureFrameCurNum = idealCurNum
      }
    },
    treasureFadeOutProgress: {
      handler(vNew, vOld) {
        if (vOld > 0 && vNew <= 0 && this.tourState === 2) {
          this.tourState = 1
        } else if (vOld < this.treasureFadeOutProgressRightBorder && vNew >= this.treasureFadeOutProgressRightBorder && this.tourState === 2) {
          this.tourState = 3
        }

        console.log('fadeOut阶段！', this.treasureFadeOutProgress)
      }
    },
    translateLength: {
      handler(vNew, vOld) {
        // const rightBorder = window.innerWidth * 2

        if (vOld < 0 && vNew >= 0 && this.tourState === 3) {
          this.tourState = 2
        }
        // if (vOld > -rightBorder && vNew <= -rightBorder && this.tourState === 3) {
        //   this.tourState = 1
        // }

        this.landscapePositionleft = `calc(18.491% + ${vNew * landscapeSpeedRate}px)`
        this.peopleFarPositionRight = `calc(${initPeopleFarPositionRight} - ${vNew * peopleFarSpeedRate}px)`
        this.peopleNearPositionLeft = `calc(${initialPeopleNearPositionLeft} + ${vNew * peopleNearSpeedRate}px)`
        this.introducePositionLeft = `calc(3.347% + ${vNew * introduceSpeedRate}px)`

        console.log('平移阶段！', this.translateLength)
      }
    },
  },
  mounted() {
    this.animationFrameId = requestAnimationFrame(this.inertanceEffect)
    this.treatureFadeInInitialLeft = this.$refs.treasure.offsetLeft
    this.treatureFadeInInitialTop = this.$refs.treasure.offsetTop
    this.treatureFadeInFinalLeft = window.innerWidth / 2 - this.$refs.treasure.offsetParent.offsetLeft
    this.treatureFadeInFinalTop = window.innerHeight / 2 - this.$refs.treasure.offsetParent.offsetTop
  },
  unmounted() {
    cancelAnimationFrame(this.animationFrameId)
  },
  methods: {
    onMouseDown(e) {
      this.isMouseDown = true
      this.moveSpeed = 0
      this.lastMoveEventTimeStamp = 0
      this.lastAnimationTimeStamp = Date.now()
    },
    onMouseUp(e) {
      this.isMouseDown = false
    },
    onMouseLeave() {
      this.isMouseDown = false
    },
    onMouseMove(e) {
      if (this.isMouseDown) {
        if (this.lastMoveEventTimeStamp) {
          // 更新speed
          const currentMoveSpeed = e.movementX / (e.timeStamp - this.lastMoveEventTimeStamp)
          this.moveSpeed = this.moveSpeed * 0.9 + currentMoveSpeed * 0.1
        }
        this.lastMoveEventTimeStamp = e.timeStamp
      }
    },
    onWheel(e) {
      if (this.tourState === 0) {
        this.treasureFadeInProgress += e.deltaY
        if (this.treasureFadeInProgress < 0) {
          this.treasureFadeInProgress = 0
          this.moveSpeed = 0
        } else if (this.treasureFadeInProgress > this.treasureFadeInProgressRightBorder) {
          this.treasureFadeInProgress = this.treasureFadeInProgressRightBorder
        }
      } else if (this.tourState === 1) {
        this.treasureDisplayProgress += e.deltaY
        if (this.treasureDisplayProgress < 0) {
          this.treasureDisplayProgress = 0
        } else if (this.treasureDisplayProgress > treasureDisplayProgressRightBorder) {
          this.treasureDisplayProgress = treasureDisplayProgressRightBorder
        }
      } else if (this.tourState === 2) {
        this.treasureFadeOutProgress += e.deltaY
        if (this.treasureFadeOutProgress < 0) {
          this.treasureFadeOutProgress = 0
        } else if (this.treasureFadeOutProgress > this.treasureFadeOutProgressRightBorder) {
          this.treasureFadeOutProgress = this.treasureFadeOutProgressRightBorder
        }
      } else if (this.tourState === 3) {
        this.translateLength -= e.deltaY
        if (this.translateLength > 0) {
          this.translateLength = 0
        }
      }
    },
    inertanceEffect() {
      const timeStamp = Date.now()
      const timeElapsed = timeStamp - this.lastAnimationTimeStamp

      // 速度减慢
      if (this.moveSpeed > 0) {
        this.moveSpeed -= 0.003 * timeElapsed
        if (this.moveSpeed < 0) {
          this.moveSpeed = 0
        }
      } else if (this.moveSpeed < 0) {
        this.moveSpeed += 0.003 * timeElapsed
        if (this.moveSpeed > 0) {
          this.moveSpeed = 0
        }
      }

      // 根据速度更新“距离”
      if (this.tourState === 0) {
        this.treasureFadeInProgress -= this.moveSpeed * timeElapsed
        if (this.treasureFadeInProgress < 0) {
          this.treasureFadeInProgress = 0
          this.moveSpeed = 0
        } else if (this.treasureFadeInProgress > this.treasureFadeInProgressRightBorder) {
          this.treasureFadeInProgress = this.treasureFadeInProgressRightBorder
        }
      } else if (this.tourState === 1) {
        this.treasureDisplayProgress -= this.moveSpeed * timeElapsed
        if (this.treasureDisplayProgress < 0) {
          this.treasureDisplayProgress = 0
        } else if (this.treasureDisplayProgress > treasureDisplayProgressRightBorder) {
          this.treasureDisplayProgress = treasureDisplayProgressRightBorder
        }
      } else if (this.tourState === 2) {
        this.treasureFadeOutProgress -= this.moveSpeed * timeElapsed
        if (this.treasureFadeOutProgress < 0) {
          this.treasureFadeOutProgress = 0
        } else if (this.treasureFadeOutProgress > this.treasureFadeOutProgressRightBorder) {
          this.treasureFadeOutProgress = this.treasureFadeOutProgressRightBorder
        }
      } else if (this.tourState === 3) {
        this.translateLength += this.moveSpeed * timeElapsed
        if (this.translateLength > 0) {
          this.translateLength = 0
        }
      }

      this.lastAnimationTimeStamp = timeStamp
      this.animationFrameId = requestAnimationFrame(this.inertanceEffect)
    },
    onClickPeopleFarHotSpot() {
      if (this.isPeopleFarColorChanging) {
        return
      } else {
        if (this.peopleFarColorStatus === 'no-color') {
          this.peopleFarColorStatus = 'color'
        } else {
          this.peopleFarColorStatus = 'no-color'
        }
        this.isPeopleFarColorChanging = true
        setTimeout(() => {
          this.isPeopleFarColorChanging = false
        }, 2500)
      }
    },
    onTreasureFrameLoad(idx) {
      this.treasureFrameStateList[idx] = true
    },
    onTreasureFrameError(idx) {
      this.treasureFrameStateList[idx] = false
    },
  }
}
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 100%;
  background-image: url(@/assets/background.jpg);
  background-repeat: repeat;
  background-size: contain;
  position: relative;
  overflow: hidden;
  .landscape-wrap {
    position: absolute;
    height: 30%;
    top: 0;
    display: flex;
    > .landscape {
      height: 100%;
    }
  }
  > .people-far-wrap {
    position: absolute;
    top: 25%;
    height: 55vh;
    width: calc(55vh * 400 / 600);
    overflow: hidden;
    > .people-far {
      position: absolute;
      height: 100%;
      transition-property: left;
      transition-duration: 2.5s;
      transition-timing-function: steps(59, jump-end);
      &.no-color {
        left: 0;
      }
      &.color {
        left: calc(-100% * 59)
      }
    }
    > .hot-spot {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: 10%;
    }
  }
  .people-near-wrap {
    position: absolute;
    bottom: -13%;
    height: 100vh;
    overflow: hidden;
    > .people-near {
      height: 100%;
    }
    > .treasure {
      position: absolute;
      left: 40%;
      top: 35%;
      width: 7%;
      height: 3.5%;
    }
  }
  .introduce {
    position: absolute;
    top: 5%;
    width: 13.727%;
  }
  .fade-mask {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #663e21;
    z-index: 1;
  }
  .treasure-frames-wrap {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 3;
    img {
      position: absolute;
    }
  }
}
</style>