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

export default class collection extends Component {
  state = {
    consultImg: '',
    sizeIndex: 0,
    mass: 0,
    modelIndex: 0,
    isImage: false,
    isOpen: false,
    jumpurl: '',//广告id
    task_id: 0,//任务id
    repeat: 0,//广告次数
    drawTaskId: 0,//任务id
    is_week: 0,//是否是周卡用户
    models: {},//活动数据
    isIos: false,
  }

  componentWillMount () {
    let that = this
    Taro.getSystemInfo({
      success: function (res) {
        if (res.platform != "android") {
          that.setState({
            isIos: true
          })
        }
      }
    })
    this.getCoinTaskAd()
    this.getDraw51ImgIndex()
    setTimeout(() => {
      this.getCoinTaskAd()
      this.getDraw51ImgIndex()
    }, 1000);
  }
  componentDidShow () {
    //接收裁剪图片
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    console.log(currentPage, 'currentPage');
    if (process.env.TARO_ENV == 'weapp') {
      if (currentPage.__data__.consultImg) { // 获取值
        this.setState({
          consultImg: currentPage.__data__.consultImg,
          sizeIndex: currentPage.__data__.sizeIndex,
          isImage: true
        })
        currentPage.__data__.consultImg = ''
      }
    } else if (process.env.TARO_ENV == 'tt') {
      if (currentPage.data.consultImg) { // 获取值
        this.setState({
          consultImg: currentPage.data.consultImg,
          sizeIndex: currentPage.data.sizeIndex,
          isImage: true
        })
        currentPage.data.consultImg = ''
      }
    }
  }
  getDraw51ImgIndex () {
    api.getDraw51ImgIndex().then(res => {
      if (res.code == 200) {
        this.setState({
          is_week: res.data.is_week,
          models: res.data,
          consultImg: res.data.img
        })
      }
    })
  }
  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
        })
      }
    })
  }
  changeOpen () {
    this.setState({
      isOpen: !this.state.isOpen
    })
  }
  //上传图片
  upLode () {
    let that = this
    Taro.chooseMedia({
      count: 1, // 默认
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res, 'res');
        const file = res.tempFiles[0].tempFilePath
        if (res.tempFiles[0].size > 2000000) {
          Taro.showToast({ title: '图片大小不能超过2M', icon: 'none' })
          return
        }
        let base64Img = Taro.getFileSystemManager().readFileSync(file, 'base64')
        Taro.showLoading({
          title: '图片检测中...',
        })
        api.imageDetection({ img_data: base64Img }).then(item => {
          if (item.code == 200) {
            Taro.hideLoading()
            Taro.navigateTo({
              url: `/moduleA/pages/upload/index?image=${file}`
            })
          } else {
            Taro.hideLoading()
            Taro.showToast({ title: item.msg, icon: 'none' })
          }
        })
      }
    })
  }
  //看广告画图
  playVideoGeneratePictures () {

    if (!this.state.isImage) {
      Taro.showToast({ title: '请先上传图片', icon: 'none' })
      return
    }
    api.drawGcImg({ img_url: this.state.consultImg, style_id: this.state.models.style_id }).then(res => {
      if (res.code == 200) {
        if (this.state.is_week == 1) {
          Taro.navigateTo({
            url: `/moduleB/pages/comicActivityDetail/index?task_id=${res.data.task_id}`
          })
        } else {
          this.setState({
            drawTaskId: res.data.task_id
          }, () => {
            this.playVideo()

          })
        }

      } else {
        Taro.hideLoading()
        Taro.showToast({ icon: 'none', title: res.msg })
      }
    })
  }

  //观看广告
  playVideo () {
    if (process.env.TARO_ENV == 'tt') {
      this.playVideoTT()
    } else {
      this.playVideoWeapp()
    }
  }
  //抖音激励广告
  playVideoTT () {
    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.navigateTo({
          url: `/moduleB/pages/comicActivityDetail/index?task_id=${that.state.drawTaskId}`
        })
      } else {

      }
    }
    // 监听视频播放完成
    videoAd.onClose(videoAd.closeHandler);
  }
  //激励广告
  playVideoWeapp () {
    // 在页面中定义激励视频广告
    let adUnitId = this.state.jumpurl
    // 在页面中定义激励视频广告
    let videoAd = null
    let that = this
    console.log(videoAd, 'videoAd');
    // 在页面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) {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded || res === undefined) {
          // 正常播放结束，可以下发游戏奖励
          Taro.navigateTo({
            url: `/moduleB/pages/comicActivityDetail/index?task_id=${that.state.drawTaskId}`
          })
        } else {
          //提前关闭小程序
        }
      };
      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('激励视频 广告显示失败')
          })
      })
    }

  }
  deleteImg () {
    this.setState({
      consultImg: this.state.models.img,
      isImage: false,
    })
  }
  onShareAppMessage = (res) => {
    let path = `/pages/index/index?c=${Taro.getStorageSync('user_id')}&s=rightTap`
    if (process.env.TARO_ENV == 'tt') {
      path = `/moduleB/pages/comic/index?c=channel_name&s=neibuguazai`
    }
    let shareData = {
      title: tool.shareTitle,
      path: path,
      imageUrl: tool.shareImg
    }
    return shareData;
  }
  changeMass (e) {
    this.setState({
      mass: e
    })
  }
  selectModel (item, index) {
    this.setState({
      modelIndex: index,
    })
  }
  //充值
  toOrder () {
    if (this.state.isIos) {
      Taro.showToast({
        title: 'ios暂不支持充值',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let that = this
    if (process.env.TARO_ENV === 'tt') {
      Taro.showLoading({
        title: '加载中...',
      })
      api.ttCreateOrder({ pay_info_id: this.state.models.shop_id }).then(res => {
        if (res.code == 200) {
          Taro.hideLoading()
          tt.pay({
            orderInfo: {
              order_id: res.data.order_id,
              order_token: res.data.order_token
            },
            service: 5,
            success (item) {
              if (item.code == 0) {
                Taro.showToast({
                  title: '购买成功',
                  icon: 'none',
                  duration: 2000
                })
                that.getDraw51ImgIndex()
                setTimeout(() => {
                  that.getDraw51ImgIndex()
                }, 2000);
                // 支付成功处理逻辑，只有res.code=0时，才表示支付成功
                // 但是最终状态要以商户后端结果为准
              }
            },
            fail (item) {
              // 调起收银台失败处理逻辑
            },
          });
        }
      })
    } else if (process.env.TARO_ENV === 'weapp') {
      Taro.getSystemInfo({
        success: function (res) {
          Taro.showLoading({
            title: '加载中...',
          })
          api.createOrder({ shop_id: that.state.models.shop_id }).then(res => {
            if (res.code == 200) {
              Taro.hideLoading()
              Taro.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success: function (res) {
                  // console.log(res);
                  //添加2s延迟在刷新数据
                  setTimeout(() => {
                    that.getDraw51ImgIndex()
                    Taro.showToast({
                      title: '购买成功',
                      icon: 'none',
                      duration: 2000
                    })
                  }, 2000);
                },
                fail: function (err) {
                  try {
                    const res = Taro.getSystemInfoSync()
                    console.log(res, 'iphone=====');
                  } catch (e) {
                  }
                }
              })
            }
          })
        }
      })
    }
  }
  toComic () {
    Taro.navigateTo({
      url: `/moduleB/pages/comic/index`
    })
  }

  render () {
    return (
      <View className='mine'>
        {
          !this.state.isImage ?
            <View className='before-painting'>
              <View className='title'>
                <Image className='title-img' src='http://video-img.fyshark.com/1682475695399title.png'></Image>
              </View>
              <View className='banner'>
                <View className='banner-content'>
                  <Image className='content-img'
                    mode='aspectFit'
                    src={this.state.consultImg}
                  ></Image>
                </View>
                <View className='step'>
                  <Image className='step-img' src='http://video-img.fyshark.com/1683196371096123.png'>
                  </Image>
                </View>
              </View>
              <View className='update' >
                <View className='update-button-more'
                  onClick={e => (this.toComic())}
                >
                  更多风格
                </View>
                <View className='update-button'
                  onClick={e => (this.upLode())}
                >
                  上传图片
                </View>
              </View>

            </View>
            :
            <View className='after-painting'>
              <View className='result-banner'>
                <View className='result-banner-content'>
                  <Image className='result-content-img'
                    mode='widthFix'
                    src={this.state.consultImg}
                  ></Image>
                  {
                    this.state.isImage &&
                    <Image className='delete' src='http://video-img.fyshark.com/1680147210173guanbi.png' onClick={e => (this.deleteImg())}></Image>
                  }
                </View>
              </View>
              <View className='after-tips'>照片已上传，还差最后一步</View>
              <View className='result-update' >
                {
                  this.state.is_week == 0 &&
                  <View className='result-recharge-button update-active'
                    onClick={e => (tool.throttle(this.toOrder()), 2000)}
                  >
                    <View className='result-recharge-button-content'>
                      <View className='result-recharge-button-top'>【限时抢购】无广告！</View>
                      <View className='result-recharge-button-bottom'>9.9元→{this.state.models.money_week / 100}元/周！
                      </View>
                    </View>
                  </View>
                }
                <View className='result-update-button'
                  onClick={e => (tool.throttle(this.playVideoGeneratePictures()), 2000)}
                >
                  {
                    this.state.is_week == 0 &&
                    <Image className='result-update-img' src='http://video-img.fyshark.com/1682414441783aghidjnl.png'></Image>
                  }
                  {
                    this.state.is_week == 1 ? '开始制作' : '看广告免费制作'
                  }

                </View>
              </View>
            </View>
        }
      </View>
    )
  }
}
