import { Component } from 'react'
import { View, Text, Button, Image, Swiper, SwiperItem, scrollView, Input, Textarea } from '@tarojs/components'
import * as api from '../../../service/index'
import tool from '../../../common/tool'
import TaroCanvasDrawer from '../../../component/taro-plugin-canvas';
import Taro, { getCurrentInstance } from '@tarojs/taro'
import './index.less'

export default class collection extends Component {
  $instance = getCurrentInstance()
  state = {
    // consultImg: 'https://video-h5.fyshark.com/1680752646217.png',
    value: '牛渚江头夜色寒，渡口月华如钩弯。孤帆远影千里外，独钓寂寥万重山。',//绘画描述
    changeValue: '',//转义文本
    imageList: [

    ],//作品列表
    tmplIds: [],//订阅列表
    qrCodeImg: '',
    img_size: '1:1',
    // 绘图配置文件
    config: null,
    interval: null,//画画轮训
    intervalText: null,//诗词转义轮训
    // 绘制的图片
    shareImage: null,
    // TaroCanvasDrawer 组件状态
    canvasStatus: false,
    isFill: false,//是否画海报
    current: 0,//当前选择的作品
    draw_status: 2,//2:已完成
    lastTime: 0,
    jumpurl: '',//广告id
    que_cnt: 0,
    task_id: 0,
    repeat: 0,//广告次数
  }

  componentWillMount () {
    setTimeout(() => {
      this.getWxCodeImg()
    }, 1000)

  }
  componentDidShow () {
    this.getWxTemplate()
    this.getCoinTaskAd()
  }
  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
        })
      }
    })
  }
  getWxCodeImg () {
    api.getWxCodeImg({ code_from: 'bill' }).then(res => {
      this.dataURLtoFile(res.data)
    })
  }
  //base64转本地路径
  dataURLtoFile (dataurl) {
    let that = this
    /// 获取到base64Data
    var base64Data = dataurl;
    /// 通过微信小程序自带方法将base64转为二进制去除特殊符号，再转回base64
    base64Data = Taro.arrayBufferToBase64(Taro.base64ToArrayBuffer(base64Data));
    /// 拼接请求头，data格式可以为image/png或者image/jpeg等，看需求
    const base64ImgUrl = "data:image/png;base64," + base64Data;

    const base64ImgData = base64ImgUrl.replace(/^data:image\/\w+;base64,/, '');
    const buffer = new ArrayBuffer(base64ImgData.length);
    const view = new Uint8Array(buffer);
    for (let i = 0; i < base64ImgData.length; i++) {
      view[i] = base64ImgData.charCodeAt(i);
    }
    const fileStream = Taro.base64ToArrayBuffer(base64ImgData);
    const filePath = Taro.env.USER_DATA_PATH + '/test.png';
    Taro.getFileSystemManager().writeFile({
      filePath: filePath,
      data: fileStream,
      encoding: 'binary',
      success: function (res) {
        console.log('writeFile success:', res, filePath);
        that.setState({
          qrCodeImg: filePath
        }, () => {
        })
      },
      fail: function (res) {
        console.log('保存失败')
      }
    })
    /// 刷新数据
    return base64ImgUrl;
  }

  playVideoAll () {
    // let lastTime = this.state.lastTime;
    // let now = new Date().getTime();
    // if (now - lastTime < 2000) return
    // this.setState({
    //   lastTime: now
    // })
    let params = {
      jumpurl: this.state.jumpurl,
      id: this.state.task_id
    }
    if (process.env.TARO_ENV == 'tt') {
      this.playVideoTT(params)
    } else {
      this.playVideo(params)
    }
  }
  //抖音激励广告
  playVideoTT (item) {
    const videoAd = tt.createRewardedVideoAd({ adUnitId: item.jumpurl });
    Taro.showLoading({
      title: '加载中...',
    })
    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) {
        api.finishTask({ task_id: item.id }).then(res => {
          if (res.code == 200) {
            that.getUserInfo()
            that.getCoinTaskList()
            Taro.showToast({
              title: '领取点券成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        Taro.showToast({
          title: '领取点券失败',
          icon: 'none',
          duration: 2000
        })
      }
    }
    // 监听视频播放完成
    videoAd.onClose(videoAd.closeHandler);
  }
  //微信激励广告
  playVideo (item) {

    // 在页面中定义激励视频广告
    let adUnitId = item.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) {
          // 正常播放结束，可以下发游戏奖励
          api.finishTask({ task_id: item.id }).then(res => {
            if (res.code == 200) {
              that.getUserInfo()
              that.getCoinTaskList()
              Taro.showToast({
                title: '领取点券成功',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } 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('激励视频 广告显示失败')
          })
      })
    }

  }
  download () {
    Taro.showLoading({
      title: '加载中...'
    })
    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.hideLoading();
    Taro.downloadFile({
      url: this.state.imageList[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.hideLoading();
    Taro.showModal({
      content: '检测到您没有打开小程序相册权限，是否取设置打开？',
      showCancel: true,
      success: res => {
        if (res.confirm) {
          // 打开权限
          Taro.openSetting({
            success: res => {
              this.doSaveImg()
            }
          })
        }
      }
    })
  }
  // 调用绘画 => canvasStatus 置为true、同时设置config
  canvasDrawFunc () {
    let sizeList = this.state.img_size.split(":")
    console.log(sizeList, 375 * sizeList[1] / sizeList[0]);
    let rssConfig = {
      width: 345,
      height: 314 * sizeList[1] / sizeList[0] + 69 + 112,
      backgroundColor: 'rgba(255,255,255,0.1)',
      debug: false,
      pixelRatio: 3,
      blocks: [
        {
          x: 0,
          y: 0,
          width: 345,
          height: 314 * sizeList[1] / sizeList[0] + 69 + 112,
          paddingLeft: 0,
          paddingRight: 0,
          borderWidth: 0,
          // borderColor: '#ccc',
          backgroundColor: '#FFFFFF',
          borderRadius: 0,
          zIndex: 1,
        },
      ],

      images: [
        {
          url: 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1679561342726.png',
          width: 154,
          height: 21,
          x: 16,
          y: 19,
          borderRadius: 12,
          zIndex: 8,
        },
        {
          url: 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1679561346368.png',
          width: 65,
          height: 4,
          x: 261,
          y: 28,
          borderRadius: 12,
          zIndex: 8,
        },
        {
          url: this.state.imageList[this.state.current].img,
          width: 314,
          height: 314 * sizeList[1] / sizeList[0],
          x: 16,
          y: 69,
          borderRadius: 12,
          zIndex: 11,
        },
        {
          url: this.state.qrCodeImg,
          width: 72,
          height: 72,
          x: 258,
          y: 314 * sizeList[1] / sizeList[0] + 69 + 20,
          borderRadius: 12,
          zIndex: 12,
        },
      ],
      texts: [
        {
          x: 20,
          y: 314 * sizeList[1] / sizeList[0] + 69 + 35,
          text: this.state.value,
          fontSize: 14,
          color: '#000',
          opacity: 1,
          fontFamily: 'PingFang SC',
          baseLine: 'middle',
          lineHeight: 22,
          lineNum: 3,
          textAlign: 'left',
          width: 200,
          zIndex: 999,
        },
      ]
    }
    console.log('回执');
    this.setState({
      config: rssConfig,
    }, () => {
      this.setState({
        isFill: true
      })
    })
    Taro.showLoading({
      title: '加载中...'
    })
  }

  // 绘制成功回调函数 （必须实现）=> 接收绘制结果、重置 TaroCanvasDrawer 状态
  onCreateSuccess = (result) => {
    console.log('成功', result);
    const { tempFilePath, errMsg } = result;
    Taro.hideLoading();

    if (errMsg === 'canvasToTempFilePath:ok') {
      this.setState({
        shareImage: tempFilePath,
        // 重置 TaroCanvasDrawer 状态，方便下一次调用
        isFill: false,
        config: {}
      }, () => {
        Taro.showShareImageMenu({
          path: tempFilePath
        })
      })
      //画图成功之后打开分享
      //  Taro.downloadFile({
      //   url: tempFilePath,
      //   success: (res) => {
      //     console.log('打开分享');
      //     Taro.showShareImageMenu({
      //       path: res.tempFilePath
      //     })
      //   }
      // })
    } else {
      // 重置 TaroCanvasDrawer 状态，方便下一次调用
      this.setState({
        isFill: false,
        config: {}
      })
      Taro.showToast({ icon: 'none', title: errMsg || '出现错误' });
      console.log(errMsg);
    }
    // 预览
    // Taro.previewImage({
    //   current: tempFilePath,
    //   urls: [tempFilePath]
    // })
  }

  // 绘制失败回调函数 （必须实现）=> 接收绘制错误信息、重置 TaroCanvasDrawer 状态
  onCreateFail = (error) => {
    console.log('失败');
    Taro.hideLoading();
    // 重置 TaroCanvasDrawer 状态，方便下一次调用
    this.setState({
      isFill: false,
      config: {}
    })
    console.log(error);
  }
  openFill () {
    this.canvasDrawFunc()
  }

  getRadomPrompt () {
    api.getRadomPoetry().then(res => {
      if (res.code == 200) {
        this.setState({
          value: res.data.prompt,
        })
        document.getElementById('textarea-num').innerHTML = res.data.prompt.length + "/1000";
      }
    })
  }
  deleteDrawText () {
    setTimeout(() => {
      this.setState({
        value: ''
      })
      document.getElementById('textarea-num').innerHTML = 0 + "/1000";
    }, 200)
  }
  onInput (e) {
    var num = e.detail.cursor;
    document.getElementById('textarea-num').innerHTML = num + "/1000";
  }
  onChangeInput (e) {
    // var num = e.detail.cursor;
    // document.getElementById('textarea-change-num').innerHTML = num + "/1000";
  }
  onBlur (e) {
    console.log('onBlur');
    this.setState({
      value: e.detail.value
    })
  }
  onChangeBlur (e) {
    this.setState({
      changeValue: e.detail.value
    })
  }
  selectModel (item, index) {
    this.setState({
      current: index
    })
  }
  getWxTemplate () {
    api.getWxTemplate().then(res => {
      let tmplIds = []
      res.data.forEach(item => {
        tmplIds.push(item.template_id)
      })
      this.setState({
        tmplIds: tmplIds
      })
    })
  }
  //订阅
  subscribe (task_id) {
    let that = this
    console.log('订阅', this.state.tmplIds);
    Taro.requestSubscribeMessage({
      tmplIds: this.state.tmplIds,
      success: function (item) {
        console.log('订阅成功');
        if (item.errMsg === 'requestSubscribeMessage:ok') {
          let keys = Object.keys(item);
          let tempids = [];

          keys.forEach(element => {
            if (item[element] == "accept") {
              tempids.push(element)
            }
          });
          console.log(tempids, 'tempidstempids');
          let pramas = {
            task_id: task_id,
            template_ids: tempids
          }
          api.subscribeTemplate(pramas)
        }
        Taro.showToast({
          title: '已订阅',
          icon: 'none',
          duration: 2000
        })
      },

      complete: function (res) {
      },

      fail: function (res) {
      }

    })
  }
  aiPoetryDraw () {
    console.log('画画');
    Taro.showLoading({
      title: '加载中...'
    })

    if (this.state.draw_status != 2) {
      Taro.hideLoading()
      Taro.showToast({
        title: `正在绘画中请稍后...`,
        icon: 'none',
      });
      return
    }
    let that = this
    setTimeout(() => {
      console.log('画画2');
      this.setState({
        draw_status: 0
      }, () => {
        api.aiPoetryDraw({ prompt: this.state.value }).then(res => {
          if (res.code == 200) {
            if (process.env.TARO_ENV == 'weapp') {
              this.subscribe(res.data.task_id)
            }
            this.getDrawTaskStatus(res.data.task_id)
            this.getDrawPromptText(res.data.task_id)
          } else {
            Taro.hideLoading()
            if (res.code == 4001) {
              that.setState({
                draw_status: 2
              })
              Taro.showModal({
                title: '您的余额不足',
                content: '是否前往获取点券？',
                success: function (res) {
                  if (res.confirm) {
                    Taro.navigateTo({
                      url: `/moduleA/pages/earnPoints/index`
                    })
                  } else if (res.cancel) {

                    console.log('用户点击取消')
                  }
                },
              })
            } if (res.code == 4002) {
              that.setState({
                draw_status: 2
              })
              Taro.showModal({
                title: '提示',
                content: res.msg,
                success: function (item) {
                  if (item.confirm) {
                    if (process.env.TARO_ENV != 'weapp') {
                      that.playVideoTT(res.data)
                    } else {
                      that.playVideo(res.data)
                    }
                  } else if (item.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })

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

        })
      })

    }, 1000)
  }
  getDrawPromptText (task_id) {
    console.log('1111');
    api.getDrawPromptText({ task_id: task_id }).then(res => {
      if (res.code == 200) {
        if (res.data.status == 3) {
          this.state.intervalText = setInterval(() => {
            clearInterval(this.state.intervalText)
            this.getDrawPromptText(task_id)
          }, 500 * 1)
          this.setState({
            changeValue: res.data.prompt,
          })
          // document.getElementById('textarea-change-num').innerHTML = res.data.prompt.length + "/1000";
        } else {
          this.setState({
            changeValue: res.data.prompt,
          })
          // document.getElementById('textarea-change-num').innerHTML = res.data.prompt.length + "/1000";
          clearInterval(this.state.intervalText)
        }
      }
    })
  }
  getDrawTaskStatus (task_id) {
    api.getDrawTaskStatus({ task_id: task_id }).then(res => {
      Taro.hideLoading();
      //定时器不要轻易改，避免造成服务器攻击
      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)
        }
        if (res.data.draw_status != 2 && res.data.que_cnt > 1) {
          this.state.interval = setInterval(() => {
            clearInterval(this.state.interval)
            this.getDrawTaskStatus(task_id)
          }, 1000 * 30)
        } 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({
          imageList: draw_infos,
          draw_status: res.data.draw_status,
          que_cnt: res.data.que_cnt,
          img_size: res.data.draw_data.img_size
        })

      }
    })
  }
  onShareAppMessage = (res) => {
    let path = `/pages/index/index?c=${Taro.getStorageSync('user_id')}&s=rightTap`
    if (process.env.TARO_ENV == 'tt') {
      path = `/pages/index/index?c=channel_name&s=douyinguazai`
    }
    let shareData = {
      title: tool.shareTitle,
      path: path,
      imageUrl: tool.shareImg
    }
    return shareData;
  }
  changeCurrent (e) {
    this.setState({
      current: e.detail.current
    })
    console.log(e, 'eeee');
  }
  selectModel (item, index) {
    this.setState({
      current: index
    })
  }

  componentWillUnmount () {
    //避免服务器攻击
    clearInterval(this.state.interval)
    clearInterval(this.state.intervalText)
  }
  render () {
    return (
      <View className='mine'>
        <View className='draw-content'>
          <View className='draw-title'>绘画描述</View>
          <View className='draw-text'>
            <View className='draw-content-func'>
              <View className='recommend'>
                <View className='recommend-text' onClick={e => (this.getRadomPrompt())}>使用推荐诗词</View>
                <Image className='recommend-img' src='http://video-img.fyshark.com/1681193671211redo%402x.png'></Image>
              </View>
              <View className='delete-draw-text' onClick={e => (this.deleteDrawText())}>清空</View>
            </View>
            <Textarea
              value={this.state.value}
              className='draw-taxtarea'
              placeholder='| 请输入相关描述，也可以输入关键词～'
              showCount
              onInput={e => (this.onInput(e))}
              onBlur={e => (this.onBlur(e))}
              maxlength='1000' />
            <View className='textarea-num' id='textarea-num'>{this.state.value.length}/1000</View>
            <View className='generate'>
              <View className='generate-button' onClick={e => (this.aiPoetryDraw())}>生成图片（消耗8点券）</View>
            </View>
          </View>
          {
            this.state.imageList.length > 0 &&
            <View>
              <View className='draw-title'>作品展示</View>
              <View className='result-content'>
                <View className='draw-text'>
                  <Textarea
                    value={this.state.changeValue}
                    className='draw-taxtarea'
                    placeholder='诗词解读中...'
                    showCount
                    disabled
                    onInput={e => (this.onChangeInput(e))}
                    onBlur={e => (this.onChangeBlur(e))}
                    maxlength='1000' />
                  {/* <View className='textarea-change-num' id='textarea-change-num'>{this.state.changeValue.length}/1000</View> */}
                </View>
                <View className='banner-content'>
                  <Swiper
                    className='banner'
                    indicatorColor='#121D34'
                    indicatorActiveColor='#0F84EC'
                    circular
                    current={this.state.current}
                    adjustHeight='first'
                    onChange={e => (this.changeCurrent(e))}
                  >
                    {
                      this.state.imageList.map((item, index) => (
                        <SwiperItem key={index}>
                          <View className='banner-info'>
                            <Image className='banner-image' mode='aspectFit' src={item.img} onClick={e => (this.previewImage(item, index))}></Image>
                          </View>
                          {
                            this.state.draw_status != 2 && item.id == -1 &&
                            <View className='banner-tips'>
                              <View className='tips-left'>
                                预计等待{Math.ceil((this.state.que_cnt - 1) * 0.2 + 1)}分钟...
                              </View>
                              {
                                this.state.repeat <= 10 && this.state.jumpurl.length > 0 &&
                                <View className='tips-right' onClick={e => (tool.throttle(this.playVideoAll(), 2000))}>
                                  点击观看广告领取积分
                                </View>
                              }
                            </View>
                          }
                        </SwiperItem>
                      ))
                    }
                  </Swiper>
                  <View className='banner-indicatorDots'>
                    {
                      this.state.imageList.map((item, index) => (
                        <View className='indicatorDots-info'
                          key={index}
                          style={this.state.current == index ? ' border: 2px solid #0F84EC;' : 'border: 2px solid rgba(2, 2, 2, 0.75);'}
                          onClick={e => (this.selectModel(item, index))}
                        >
                          <Image className='indicatorDots-img' src={item.img}></Image>
                        </View>
                      ))
                    }
                  </View>
                </View>
                {
                  this.state.draw_status == 2 &&
                  < View className='func'>
                    <View className='func-list'>
                      {
                        this.state.qrCodeImg.length > 0 && process.env.TARO_ENV != 'tt' &&
                        <View className='func-info' onClick={e => (this.openFill())}>
                          <Image className='func-image' src='https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1678952396973.png'></Image>
                          <View>分享</View>
                        </View>
                      }
                      <View className='func-info' onClick={e => (this.download())}>
                        <Image className='func-image' src='https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1678952411029.png'></Image>
                        <View>下载</View>
                      </View>
                    </View>
                  </View>
                }
              </View>
            </View>
          }
        </View>
        {
          this.state.isFill &&
          <TaroCanvasDrawer
            config={this.state.config} // 绘制配置
            onCreateSuccess={e => (this.onCreateSuccess(e))} // 绘制成功回调
            onCreateFail={e => (this.onCreateFail(e))} // 绘制失败回调
          />
        }
      </View >
    )
  }
}
