<template>
  <view class="answerdetail-page flex-column">
    <view class="question-wrap">
      <view class="question-item">
        <view class="question-info">
          <view style="flex: 1" class="question-title">
            <text class="item-label">{{
              questionItem.chart_permission_name
            }}</text>
            {{ questionItem.question_content }}
          </view>
          <view class="item-answer" v-if="questionItem.reply_status === 3">
            <view class="answer" @click.stop="handleAudio(questionItem)">
              <template v-if="!questionItem.loading">
                <image
                  class="music-img"
                  :src="questionItem.answer.isplay ? playImgSrc : pauseImgSrc"
                  mode="widthFix"
                />
                <template
                  v-if="
                    questionItem.answer.isplay || questionItem.answer.ispause
                  "
                >
                  <text>{{
                    questionItem.answer.audioTime -
                      currentAudioMsg.audioCurrentTime >
                    0
                      ? moment(
                          questionItem.answer.audioTime -
                            currentAudioMsg.audioCurrentTime
                        ).format("mm:ss")
                      : "00:00"
                  }}</text>
                </template>
                <template v-else>
                  <text>{{
                    moment(questionItem.answer.audioTime).format("mm:ss")
                  }}</text>
                </template>
              </template>
              <template v-else>
                <image
                  class="load-img"
                  src="../static/loading.png"
                  mode="aspectFill"
                />
                <text>{{
                  moment(questionItem.answer.audioTime).format("mm:ss")
                }}</text>
              </template>
            </view>
          </view>
        </view>
        <text class="item-time">提问时间:{{ questionItem.create_time }}</text>
      </view>
    </view>
    <view
      class="record-wrap flex-column"
      v-if="questionItem.reply_status === 2"
    >
      <view class="record flex-column" v-if="questionItem.recordStatus !== 4">
        <view class="no-record" v-if="questionItem.recordStatus === 1">
          <image src="../static/question/record.png" mode="widthFix" />
          <view>无录音（录音时长超过三分钟自动结束）</view>
        </view>
        <view class="record-time" v-else>{{ audioTime }}</view>
      </view>
      <view
        class="record-tool flex-column"
        v-if="questionItem.recordStatus !== 4"
      >
        <view class="hint" v-if="questionItem.recordStatus === 1"
          >点击开始录音</view
        >
        <view class="record-btn-wrap">
          <text @click="handleRecode('delete')">删除</text>
          <view class="switch" @click="changeRecodeStatus">
            <image
              v-if="questionItem.recordStatus >= 2"
              :src="questionItem.recordStatus === 2 ? playImgSrc : pauseImgSrc"
              :style="{
                'margin-left': questionItem.recordStatus !== 2 ? '7rpx' : 0,
              }"
              mode="widthFix"
            />
          </view>
          <text @click="handleRecode('finish')">完成</text>
        </view>
      </view>
      <view class="record-play" v-if="questionItem.recordStatus === 4">
        <view class="audio-wrap">
          <view v-if="pageLoading">音频生成中...</view>
          <view class="play" v-else>
            <van-icon
              :name="isplay ? 'pause' : 'play'"
              @click="handleAudioByReplay"
              color="#E6B77DFF"
              size="64rpx"
              style="align-items: flex-start; margin-left: -20rpx"
            />

            <!-- 进度条 -->
            <view class="slider-box">
              <slider
                :value="currentAudioMsg.audioCurrentTime"
                :max="currentAudioMsg.audioTime"
                @change="sliderChange($event)"
                activeColor="#E6B77DFF"
                backgroundColor="#EBEBEBFF"
                block-color="#E6B77DFF"
                block-size="12"
              />
              <view class="slider-time">
                <text>{{
                  moment(currentAudioMsg.audioCurrentTime * 1000).format(
                    "mm:ss"
                  )
                }}</text>
                <text>{{
                  moment(currentAudioMsg.audioTime * 1000).format("mm:ss")
                }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="audio-delete" @click="handleRecode('delete')">
          <image src="../static/question/delerecord.png" mode="heightFix" />
          <text>删除</text></view
        >
        <view class="audio-pub" @click="handleRecode('pub')">发布</view>
      </view>
    </view>
  </view>
</template>

<script>
import mixin from "../mixin/questionMixin";
import { apiReplayAsk } from "@/api/question";
import { uploadToServer, uploadAudioToServer } from "@/utils/upload";
export default {
  mixins: [mixin],
  data() {
    return {
      questionItem: {
        id: 1,
        chart_permission_id: 1,
        question_content: "疫情下全球苯乙烯市场有什么动荡和影响",
        create_time: "2022.5.23 14:40",
        answer: {
          source:
            "https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3",
          audioTime: 21 * 1000,
          isplay: false,
          ispause: false,
        },
        loading: false,
        reply_status: 2,
        chart_permission_name: "苯乙烯",
        recordStatus: 1, //1:未录音;2:正在录音;3:已暂停;4:完成录音
      },
      pauseImgSrc: "../static/question/recordplay.png",
      playImgSrc: "../static/question/recordpause.png",
      innerAudio: null, //该页面的音频
      audioCount: 0, //录音计时
      audioTime: "00:00", //录音时间
      timer: null,
      audioItem: {},
      pageLoading: false,
      isPlayed: false, //拖动进度条前音频是否为播放状态
      playIconKey: 0,
      isplay: false,
    };
  },
  onLoad(options) {
    this.initAudio();
    //this.getQuestionItem(options.id)
  },
  methods: {
    //初始化audio
    initAudio() {
      this.innerAudio = uni.createInnerAudioContext();
      this.handleAudioFun();
      this.handleRecorderFun();
    },
    //audio事件
    handleAudioFun() {
      this.innerAudio.onPlay(() => {
        this.isplay = true;
        console.log("播放录音了");
        this.questionItem.loading = false;
      });
      this.innerAudio.onTimeUpdate(() => {
        console.log("时间更新", this.innerAudio.currentTime);
        this.currentAudioMsg.audioCurrentTime = parseInt(
          this.innerAudio.currentTime
        );
      });
      this.innerAudio.onSeeked(() => {
        //取this.innerAudio.currentTime为0
        console.log("seek完成");
      });
      this.innerAudio.onPause(() => {
        this.isplay = false;
        console.log("暂停");
        console.log(this.innerAudio.paused);
      });
      this.innerAudio.onEnded(() => {
        console.log("音频播放完毕");
        this.questionItem.answer.isplay = false;
        this.questionItem.answer.ispause = false;
        this.changeCurrentAudio({
          id: "",
          answer: {
            source: "",
            audioTime: 0,
          },
        });
      });
    },
    //录音事件
    handleRecorderFun() {
      this.globalRecorder.onStart(() => {
        console.log("开始录音");
      });
      this.globalRecorder.onPause(() => {
        console.log("暂停录音");
        /* this.cleanTime(); */
      });
      this.globalRecorder.onStop((res) => {
        console.log("录音完成");
        console.log("res", JSON.stringify(res));
        //this.innerAudio.src = res.tempFilePath;
        this.cleanTime();
        //初始化音频播放
        this.innerAudio.src = res.tempFilePath;
        this.changeCurrentAudio({
          id: "",
          answer: {
            source: res.tempFilePath,
            audioTime: res.duration / 1000,
          },
        });
        this.pageLoading = false;
      });
      this.globalRecorder.onError((res) => {
        console.log("err", res);
      });
      /* this.globalRecorder.onFrameRecorded((res) => {
        console.log("?", res);
      }); */
    },
    changeRecodeStatus() {
      //根据questionItem.recordStatus
      if (this.questionItem.recordStatus === 1) {
        //开始录音
        this.globalRecorder.start({ duration: 180000, format: "mp3" });
        this.clockTime();
        this.questionItem.recordStatus = 2;
      } else if (this.questionItem.recordStatus === 2) {
        //暂停录音
        this.globalRecorder.pause();
        this.cleanTime();
        this.questionItem.recordStatus = 3;
      } else if (this.questionItem.recordStatus === 3) {
        //继续录音
        this.globalRecorder.resume();
        this.clockTime();
        this.questionItem.recordStatus = 2;
      } else {
        //结束录音
        this.globalRecorder.stop();
        this.cleanTime();
      }
    },
    //上传音频
    async uploadAudio() {
      const res = await uploadAudioToServer(this.innerAudio.src)
      if (res.code === 200) {
        this.audioItem = res.data;
      } else {
        //重新录
        this.questionItem.recordStatus = 1;
        this.audioCount = 0;
        this.audioTime = this.moment(this.audioCount * 1000).format("mm:ss");
      }
    },
    async handleRecode(type) {
      this.questionItem.recordStatus = 4;
      this.changeRecodeStatus();
      if (type === "finish") {
        //生成音频,更改页面布局
        this.pageLoading = true;
      } else if (type === "delete") {
        //重新录
        this.questionItem.recordStatus = 1;
        this.audioCount = 0;
        this.audioTime = this.moment(this.audioCount * 1000).format("mm:ss");
      } else {
        //发布
        await this.uploadAudio();
        //如果上传音频成功
        if (this.questionItem.recordStatus === 4) {
          //发布回答
          const res = await apiReplayAsk({
            question_id: 5,
            audio_list: [{...this.audioItem,sort:1}],
          });
          if (res.code === 200) {
            //关闭当前页面,跳转到我的回答
            uni.navigateBack({ delta: 1 });
          }
        }
      }
    },
    //(提问者)问题已被回答,点击回答音频
    handleAudio(item) {
      const { source, isplay, ispause } = item.answer;
      if (isplay) {
        //说明是播放->暂停
        this.innerAudio.pause();
        this.questionItem.answer.isplay = false;
        this.questionItem.answer.ispause = true;
      } else if (ispause) {
        //说明是暂停->播放
        this.innerAudio.play();
        this.questionItem.answer.isplay = true;
        this.questionItem.answer.ispause = false;
      } else {
        console.log("aaa", source, this.innerAudio.src);
        //说明是第一次播放
        this.changeCurrentAudio(item);
        this.innerAudio.stop();
        this.innerAudio.src = source;
        this.handleAudioPlay();
        this.questionItem.answer.isplay = true;
      }
    },
    //(回答者)问题被回答,点击回答音频
    handleAudioByReplay() {
      this.isplay = !this.isplay;
      if (this.innerAudio.paused) {
        this.innerAudio.play();
      } else {
        this.innerAudio.pause();
      }
      this.playIconKey++;
    },
    //拖动音频进度条
    sliderChange(e) {
      console.log("拖动完成?");
      //this.innerAudio.pause();
      const value = e.detail.value;
      this.innerAudio.seek(value);
      this.currentAudioMsg.audioCurrentTime = value;
    },
    //切换当前播放音频
    changeCurrentAudio(item) {
      const { id } = item;
      const { source, audioTime } = item.answer;
      this.currentAudioMsg = {
        id: id,
        audioCurrentTime: 0 * 1000,
        audioTime: audioTime,
        audioCurrentUrl: source,
      };
      if (id) {
        this.questionItem.loading = true;
      }
    },
    //录音计时
    clockTime() {
      console.log("开始计时");
      this.timer = setInterval(() => {
        if (this.timer) {
          this.audioCount++;
          this.audioTime = this.moment(this.audioCount * 1000).format("mm:ss");
        }
      }, 1000);
    },
    //清除录音计时
    cleanTime() {
      this.timer = null;
      this.audioTime = this.moment(this.audioCount * 1000).format("mm:ss");
    },
  },
};
</script>

<style scoped lang="scss">
.flex-column {
  display: flex;
  flex-direction: column;
}

.answerdetail-page {
  padding: 50rpx 30rpx 0 30rpx;
  height: calc(100vh - calc(50px + env(safe-area-inset-bottom)));
  box-sizing: border-box;
  .question-wrap {
    .question-item::after {
      height: 0;
    }
  }
  .record-wrap {
    margin: 0 -30rpx;
    flex: 1;
    .record {
      flex: 1;
      justify-content: center;
      align-items: center;
      .no-record {
        text-align: center;
        color: #999999ff;
        font-size: 28rpx;
        image {
          width: 94rpx;
        }
      }
      .record-time {
        justify-self: flex-end;
        font-size: 60rpx;
      }
    }
    .record-tool {
      justify-content: center;
      align-items: center;
      border-top: 1rpx solid #e6e6e6ff;
      height: 400rpx;
      position: relative;
      .hint {
        color: #ee3636ff;
        font-size: 28rpx;
        position: absolute;
        top: 50rpx;
      }
      .record-btn-wrap {
        margin-top: 38rpx;
        display: flex;
        width: 100%;
        justify-content: space-around;
        align-items: center;
        text {
          color: #999999ff;
          font-size: 32rpx;
          &.active {
            color: #ee3636ff;
          }
        }
        .switch {
          width: 118rpx;
          height: 118rpx;
          padding: 12rpx;
          box-sizing: border-box;
          border-radius: 50%;
          border: 1rpx solid #ee3636ff;
          /* background-color: rgb(68, 46, 46); */
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          image {
            position: absolute;
            width: 36rpx;
            z-index: 5;
          }
          &::after {
            content: "";
            display: inline-block;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: #ee3636ff;
          }
        }
      }
    }
    .record-play {
      margin: 20rpx 30rpx;
      .audio-wrap {
        background-color: #fdf8f2ff;
        padding: 30rpx;
        border-radius: 16rpx;
      }
      .play {
        display: flex;
        justify-content: space-between;
        .slider-box {
          margin-left: 15rpx;
          flex: 1;
          slider {
            margin: 15rpx 0 0 0;
          }
          .slider-time {
            display: flex;
            justify-content: space-between;
            text {
              color: #999999ff;
              font-size: 22rpx;
            }
          }
        }
      }
      .audio-delete {
        margin-top: 20rpx;
        width: 100%;
        height: 40rpx;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        image {
          height: 40rpx;
        }
        text {
          margin-left: 10rpx;
          color: #999999ff;
          font-size: 28rpx;
        }
      }
      .audio-pub {
        margin-top: 120rpx;
        background-color: #e6b77dff;
        color: #fff;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
        text-align: center;
        position: relative;
        width: 390rpx;
        left: 50%;
        margin-left: -170rpx;
      }
    }
  }
}
</style>
