import { Component } from 'react'
import { View, Text, Button, Image, ScrollView, Input } from '@tarojs/components'
import * as api from '../../../service/index'
import tool from '../../../common/tool'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import './index.less'

export default class collection extends Component {
  $instance = getCurrentInstance()
  state = {
    jumpurl: '',//广告id
    task_id: 0,//任务id
    repeat: 0,//广告次数
    current: 0,
    interval: null,
    draw_status: 0,
    draw_infos: [],
    que_cnt: 0,
    default_img: '',
    wallet_balance: 0,//用户当前余额
  }

  componentWillMount () {

  }
  componentDidShow () {
    let routers = this.$instance.router.params
    this.getCoinTaskAd()
    api.unlockGcImg({ task_id: routers.task_id }).then(res => {
      console.log('解锁');
      if (res.code == 200) {
        this.getDrawTaskStatus(routers.task_id)
      }
    })
  }
  //页面销毁之前调用
  componentWillUnmount () {
    //避免服务器攻击
    clearInterval(this.state.interval)
  }
  getCoinTaskAd () {
    api.getCoinTaskAd().then(res => {
      if (res.code == 200) {
        this.setState({
          jumpurl: res.data[0].jumpurl,//广告id
          task_id: res.data[0].id,//任务id
          repeat: res.data[0].repeat
        })
      }
    })
  }
  //解锁成功
  unlockGcImg (item, index) {
    console.log('解锁002');
    api.unlockGcImg({ task_id: item.task_id }).then(res => {
      if (res.code == 200) {
        this.setState({
          current: index
        })
        this.getDrawTaskStatus(item.task_id)
      }
    })
  }

  selectedLabel (item, index) {
    let that = this
    console.log(item, 'itemitem');
    if (item.unlock_status == 0) {
      Taro.showModal({
        title: '提示',
        content: '是否观看广告解锁？',
        success: function (res) {
          if (res.confirm) {
            if (item.status == 4) {
              that.generatePictures(item, index)
            }
            that.playVideo(item, index)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      this.setState({
        current: index
      })
    }

  }
  //观看广告
  playVideo (item, index) {
    if (process.env.TARO_ENV == 'tt') {
      this.playVideoTT(item, index)
    } else {
      this.playVideoWeapp(item, index)
    }
  }
  //抖音激励广告
  playVideoTT (item, index) {
    let that = this
    Taro.showLoading({
      title: '加载中...',
    })
    const videoAd = tt.createRewardedVideoAd({ adUnitId: this.state.jumpurl });
    videoAd.show()
    videoAd.onError((err) => {
      Taro.hideLoading()
      switch (err.errCode) {
        case 1004:
          // 无合适的广告
          break;
        default:
        // 更多请参考错误码文档
      }
    });
    try {
      if (videoAd.closeHandler) {
        videoAd.offClose(videoAd.closeHandler);
        console.log("videoAd.offClose卸载成功");
      }
    } catch (e) {
      console.log("videoAd.offClose 卸载失败");
      console.error(e);
    }
    videoAd.closeHandler = function (data) {
      Taro.hideLoading()
      if (data.isEnded) {
        Taro.showToast({
          title: '解锁成功',
          icon: 'none',
          duration: 2000
        })
        that.unlockGcImg(item, index)
      } else {
        that.getDrawTaskStatus(item.task_id)
        Taro.showToast({
          title: '解锁失败',
          icon: 'none',
          duration: 2000
        })
      }
    }
    // 监听视频播放完成
    videoAd.onClose(videoAd.closeHandler);
  }
  //激励广告
  playVideoWeapp (item, index) {
    console.log(item, 'guanggao');
    // 在页面中定义激励视频广告
    let adUnitId = this.state.jumpurl
    // 在页面中定义激励视频广告
    let videoAd = null
    let that = this
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: adUnitId
      })
      videoAd.onLoad(() => {
      })
      videoAd.onError((err) => { })
      try {
        if (videoAd.closeHandler) {
          videoAd.offClose(videoAd.closeHandler);
          console.log("videoAd.offClose卸载成功");
        }
      } catch (e) {
        console.log("videoAd.offClose 卸载失败");
        console.error(e);
      }
      videoAd.closeHandler = function (res) {
        Taro.hideLoading()
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded || res === undefined) {
          // 正常播放结束，可以下发游戏奖励
          Taro.showToast({
            title: '解锁成功',
            icon: 'none',
            duration: 2000
          })
          console.log(item, '关闭');
          that.unlockGcImg(item, index)
        } else {
          console.log(item, '关闭1');
          //提前关闭小程序
          that.getDrawTaskStatus(item.task_id)
          Taro.showToast({
            title: '解锁失败',
            icon: 'none',
            duration: 2000
          })
        }
      };
      videoAd.onClose(videoAd.closeHandler);

    }

    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            Taro.showToast({
              title: '暂无广告',
              icon: 'none',
              duration: 2000
            })
            console.log('激励视频 广告显示失败')
          })
      })
    }

  }
  //画画
  generatePictures (item, index) {
    console.log(item, '画画');
    api.drawGcImgTask({ task_id: item.task_id }).then(res => {
      if (res.code == 200) {
        this.getDrawTaskStatus(item.task_id)
      }
    })
  }
  getDrawTaskStatus (task_id) {
    api.getDrawTaskStatusGc({ task_id: task_id }).then(res => {
      //定时器不要轻易改，避免造成服务器攻击
      if (res.code == 200) {
        let draw_infos = res.data.draw_infos
        // if (res.data.draw_status != 2) {
        //   let params = {}
        //   params['img'] = res.data.default_img
        //   params['id'] = -1
        //   draw_infos.push(params)
        // }
        console.log(draw_infos, 'draw_infos');
        if (res.data.draw_status != 2 && res.data.que_cnt > 1) {
          this.state.interval = setInterval(() => {
            clearInterval(this.state.interval)
            this.getDrawTaskStatus(task_id)
          }, 1000 * 10)
        } else if (res.data.draw_status != 2 && res.data.que_cnt <= 1) {
          clearInterval(this.state.interval)
          this.state.interval = setInterval(() => {
            this.getDrawTaskStatus(task_id)
          }, 1000 * 5)
        } else {
          clearInterval(this.state.interval)
        }
        this.setState({
          draw_status: res.data.draw_status,
          que_cnt: res.data.que_cnt,
          draw_infos: draw_infos,
          wallet_balance: res.data.wallet_balance
        })
      }
    })
  }

  download () {
    this.downImg()
  }
  // 鉴权操作 判断是否有保存到相册的权限
  // 有就直接下载 没有就弹窗提示给权限
  downImg () {
    Taro.getSetting({
      success: res => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          Taro.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.doSaveImg()
            },
            fail: () => {
              this.openConfirm()
            }
          })
        } else {
          this.doSaveImg()
        }
      }
    })
  }
  // 生成临时路径 保存图片到手机
  doSaveImg () {
    Taro.downloadFile({
      url: this.state.draw_infos[this.state.current].img,
      success: res => {
        Taro.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            Taro.showToast({ title: '已保存到相册', icon: 'success' })
          },
          fail: () => {
            Taro.showToast({ title: '保存失败', icon: 'none' })
          }
        })
      }
    })
  }
  // 权限弹窗
  openConfirm () {
    Taro.showModal({
      content: '检测到您没有打开小程序相册权限，是否取设置打开？',
      showCancel: true,
      success: res => {
        if (res.confirm) {
          // 打开权限
          Taro.openSetting({
            success: res => {
              this.doSaveImg()
            }
          })
        }
      }
    })
  }
  toIndex () {
    Taro.reLaunch({
      url: `/pages/index/index`
    })
  }
  previewImage () {
    Taro.previewImage({
      current: this.state.draw_infos[this.state.current].img, // 当前显示图片的http链接  
      urls: [`${this.state.draw_infos[this.state.current].img}`] // 需要预览的图片http链接列表  
    })
  }


  render () {
    return (
      <View className='mine'>
        {
          this.state.draw_infos.length > 0 &&
          <View className='banner'>
            <View className='banner-content'>
              <Image className='content-img'
                mode='aspectFit'
                onClick={e => (this.previewImage())}
                src={this.state.draw_infos[this.state.current].img}
              ></Image>
              {/* {
                this.state.draw_infos[this.state.current].status == 0 &&
                this.state.draw_infos[this.state.current].status == 1 &&
                <View className='content-wait'>
                  <View className='wait-date'>预计等待{Math.ceil((this.state.que_cnt - 1) * 0.2 + 1)}分钟...</View>
                  <View className='wait-middle'>{this.state.draw_status == 0 ? '等待中' : this.state.draw_status == 1 ? '正在绘画...' : '已完成'}</View>
                  <View className='wait-bottom'>
                    <View className='wait-num'>当前点券余额：{this.state.wallet_balance}</View>
                    <View className='wait-get-num' onClick={e => (tool.throttle(this.playVideo()), 2000)}>点击观看广告领取更多点券</View>
                  </View>
                </View>
              } */}

            </View>
          </View>
        }
        <ScrollView
          className='recharge'
          scrollX
        >
          {
            this.state.draw_infos.map((item, index) => (
              <View className='recharge-info'
                key={index}
                onClick={e => (this.selectedLabel(item, index))}>
                <Image className='recharge-image' mode='aspectFit' src={item.img}></Image>
                {
                  item.unlock_status == 0 &&
                  <View className='lock'>
                    <View className='lock-content'>
                      <Image className='lock-img' src='http://video-img.fyshark.com/1681733630830%E8%A7%A3%E9%94%81%402x.png'></Image>
                      <View className='lock-title'>解锁</View>
                    </View>
                  </View>
                }
              </View>
            ))
          }
        </ScrollView>
        <View className='control'>
          <View className='download' onClick={e => (this.download())}>保存图片</View>
          <View className='toIndex' onClick={e => (this.toIndex())}>前往探索更多玩法</View>
        </View>
      </View>
    )
  }
}
