<template>
  <view class="video-preview">
    <!-- 视频播放区域 -->
    <view class="video-container">
      <video
				v-if="videoUrl"
        :src="videoUrl"
        class="video-player"
        controls
      ></video>
			<u-empty v-else text="视频为空" src="play-circle"></u-empty>
    </view>
    
    <!-- 底部按钮区域 -->
    <view class="btn-box" :class="adjustCount == 0?'one':''" v-if="routeParams.name === '视频预览' && formState!= 'confirm'">
      <u-button 
				v-if="adjustCount !== 0"
        type="default"
        class="adjust-btn" 
        @click="showAdjustModal"
      >视频调整</u-button>
      <u-button 
        class="confirm-btn" 
        type="primary"
        @click="showConfirmModal"
      >确认视频</u-button>
    </view>
		
		<!-- 底部按钮区域 -->
		<!-- <view class="btn-box one" v-else-if="routeParams.name === '查看交付视频'">
		  <u-button 
		    class="confirm-btn" 
		    type="primary"
		    @click="downloadVideo"
		  >下载交付视频</u-button>
		</view> -->
    
    <!-- 调整建议弹窗 -->
    <u-popup
      v-model="showAdjust"
      @close="closeAdjustModal"
      mode="center"
      border-radius="10"
    >
      <view class="adjust-modal">
        <view class="modal-title">调整建议</view>
        <view class="adjust-count">剩余调整次数：{{ adjustCount }}</view>
        <u-input
          v-model="adjustForm.message"
          placeholder="请输入调整建议"
          auto-height
          type="textarea"
          border
        ></u-input>
        <view class="modal-buttons">
          <u-button 
            @click="cancelAdjustment"
          >取消</u-button>
          <u-button 
            type="primary"
            @click="submitAdjustment"
            :disabled="adjustCount <= 0"
          >提交</u-button>
        </view>
      </view>
    </u-popup>
    
    <!-- 确认弹窗 -->
    <u-modal
      v-model="showConfirm"
      title="确认提示"
      content="视频确认后将生成正式交付视频，并完成订单，是否要确认？"
      @confirm="submitAdjustment"
      @cancel="closeConfirmModal"
      show-cancel-button
    ></u-modal>
  </view>
</template>

<script>
export default {
  data() {
    return {
      videoUrl: '', // 视频URL
      adjustmentSuggestion: '', // 调整建议内容
      showAdjust: false, // 调整弹窗显示状态
      showConfirm: false, // 确认弹窗显示状态
      videoStatus: 'preview',
			routeParams:{
				productId:'',
				orderId:'',
				orderItemId:'',
				name:'',
			},
			adjustForm:{
				businessKey: undefined,
				state: 1,
				message: undefined
			},
			adjustCount:0,
			formState:'preview'
    }
  },
	onLoad(option) {
		if(option){
			this.routeParams = option;
		}
		this.getInfo();
	},
  methods: {
		async getInfo(){
			let res = await this.$api.orderApi.getOrderMaterialList({ orderItemId: this.routeParams.orderItemId })
			console.log("res",res)
			if(res.rows.length!=0){
				this.adjustForm.businessKey = res.rows[0].id;
				if (this.routeParams.name === '视频预览') {
					this.videoUrl = res.rows[0].resultPreview;
					this.formState = res.rows[0].formState;
					let count = res.rows[0].adjustCount || 0;
					this.adjustCount = 3 - count > 0 ? 3 - count : 0;
				} else {
					this.videoUrl = res.rows[0].resultOutput;
				}
			}else{
				
			}
		},
		downloadVideo(){
			if(!this.videoUrl){
				this.$u.toast('交付视频为空')
			}else{
				if(this.isWechat()){
					uni.showModal({
						title: '下载提示',
						content: '微信浏览器不允许下载，请复制视频链接在外部下载，或者右上角打开外部浏览器下载？',
						confirmText:'复制视频链接',
						success:(res)=>{
							if (res.confirm) {
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								uni.setClipboardData({
									data: this.videoUrl,
									success: function () {
										console.log('success');
									}
								});
							}
						}
					});
				}else{
					this.downloadFile(this.videoUrl, 'video.mp4');
				}
			}
		},
		isWechat(){
			return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
		},
		async downloadFile(videoUrl) {
      try {
        // 1. 获取视频文件的 Blob 对象
        const response = await fetch(videoUrl);
        const blob = await response.blob();

        // 2. 创建 Blob URL
        const blobUrl = window.URL.createObjectURL(blob);

        // 3. 创建 <a> 标签并触发下载
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = 'video.mp4'; // 设置下载的文件名
        document.body.appendChild(link);
        link.click();

        // 4. 清理 Blob URL
        window.URL.revokeObjectURL(blobUrl);
        document.body.removeChild(link);
      } catch (error) {
        console.error('下载失败：', error);
        uni.showToast({
          title: '下载失败',
          icon: 'none'
        });
      }
    },
    // 显示调整建议弹窗
    showAdjustModal() {
      this.adjustForm.state = 0;
      this.adjustForm.message = '';
      this.showAdjust = true;
    },
    
    // 关闭调整建议弹窗
    closeAdjustModal() {
      this.showAdjust = false
    },
    
    // 显示确认弹窗
    showConfirmModal() {
			this.adjustForm.state = 1;
			this.adjustForm.message = '';
      this.showConfirm = true;
    },
    
    // 取消调整
    cancelAdjustment() {
      this.adjustmentSuggestion = ''
      this.showAdjust = false
    },
    
    // 提交调整建议
    async submitAdjustment() {
      if (this.adjustCount <= 0 && this.adjustForm.state == 0) {
        this.$u.toast('已达到最大调整次数')
        return
      }
			let res = await this.$api.orderApi.materialAdjust(this.adjustForm)
			console.log("res",res)
			if(res.code == 200){
				this.$u.toast('提交成功')
				uni.navigateBack({
					delta: 1
				})
			}else{
				this.$u.toast(res.msg)
			}
    },
    
    // 确认视频
    confirmVideo() {
      // TODO: 调用确认视频接口
      this.$u.toast('视频已确认')
      this.showConfirm = false
    },
    
    // 关闭确认弹窗
    closeConfirmModal() {
      this.showConfirm = false
    }
  }
}
</script>
<style>
 page{
  height: 100%;
  background: #f5f5f5;
 }
</style>

<style lang="scss" >
.video-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: 120rpx;
  .video-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    
    
    .video-player {
      border-radius: 20rpx;
      width: 100%;
      max-height: 100%;
      // height: 400rpx;
    }
  }
  
  .btn-box {
    display: flex;
		justify-content: space-around;
		align-items: center;
		height: 120rpx;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: #fff;
		z-index: 999;
		button{
			width: 340rpx;
			height: 85rpx;
			border-radius: 10rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		&.one{
			button{
				width: 680rpx;
			}
		}
  }
  
  .adjust-modal {
    background-color: #fff;
    padding: 30rpx;
    width: 600rpx;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 20rpx;
    }
    
    .adjust-count {
      font-size: 28rpx;
      color: #ff0000;
      margin-bottom: 20rpx;
    }
    
    .modal-buttons {
      display: flex;
      margin-top: 30rpx;
      justify-content: space-around;
      align-items: center;
      button{
        width: 260rpx;
        height: 85rpx;
        border-radius: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style> 