import { Component } from 'react'
import { View, Text, Button, Image, Swiper, SwiperItem, ScrollView, Input, Textarea, Slider, Block } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import tool from '../../common/tool'
import { AtFloatLayout } from 'taro-ui'
import "taro-ui/dist/style/components/float-layout.scss";
import * as api from '../../service/index'

import './index.less'

export default class Mine extends Component {
  $instance = getCurrentInstance()
  state = {
    models: [],//模板
    imgSize: [],//图片尺寸
    sampling: [],//采样方式
    draw_infos: [
    ],//banner
    samplingIndex: 0,//当前选择的采样方式
    loraIndex: 0,//当前选择的风格
    sizeIndex: 0,//当前选择的尺寸
    isOpen: false,
    value: '杰作,顶级质量,女孩',//绘画描述
    negativeValue: '',//不要的元素
    modelIndex: 0,//当前选择的模型
    sliderNum: 7,//色彩丰富度
    drawNum: 1,//图片数量
    mass: 0,//图片质量
    tmplIds: [],//订阅列标
    tags: [],//标签列表
    tagsIndex: 0,//当前选择的主标签
    isTags: false,//是否打开标签弹窗
    consultImg: '',//参考图
    lastTime: 0
  }

  componentDidShow () {
    //接收裁剪图片
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    if (process.env.TARO_ENV == 'weapp') {
      if (currentPage.__data__.consultImg) { // 获取值
        this.setState({
          consultImg: currentPage.__data__.consultImg,
          sizeIndex: currentPage.__data__.sizeIndex
        })
        currentPage.__data__.consultImg = ''
      }
    } else if (process.env.TARO_ENV == 'tt') {
      if (currentPage.data.consultImg) { // 获取值
        this.setState({
          consultImg: currentPage.data.consultImg,
          sizeIndex: currentPage.data.sizeIndex
        })
        currentPage.data.consultImg = ''
      }
    }
    this.getDrawIndex()
    this.getWxTemplate()
    this.getTagsDev()
  }
  componentDidMount () {

  }

  getTagsDev () {
    api.getTagsDev().then(res => {
      if (res.code == 200) {
        let _tags = res.data
        _tags.forEach(item => {
          item.tags.forEach(e => {
            e['isSelect'] = false
          })
        })
        console.log(_tags, '_tags');
        this.setState({
          tags: _tags
        })
      }
    })
  }

  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;
  }

  getMyDraw () {
    api.getMyDraw({ page_size: 100 })
  }
  getDrawIndex () {
    api.getDrawIndex().then(res => {
      if (res.code == 200) {
        this.setState({
          models: res.data.models,
          imgSize: res.data.img_size,
          sampling: res.data.Sampler,
          draw_infos: res.data.banner_info
        }, () => {
          let routers = this.$instance.router.params
          console.log(routers, 'rou');
          if (routers.task_id) {
            Taro.showLoading({
              title: '加载中',
            })
            this.getDrawTaskStatus()
          }
        })
      }
    })
  }
  //获取同款信息
  getDrawTaskStatus () {
    let routers = this.$instance.router.params
    api.getImgDetail({ img_id: routers.task_id }).then(res => {
      Taro.hideLoading()
      if (res.code == 200) {
        let model_id_index = 0
        this.state.models.forEach((item, index) => {
          if (item.id == res.data.task_info.model_id) {
            model_id_index = index
          }
        });
        let style_id_index = 0
        this.state.models[model_id_index].lora_infos.forEach((item, index) => {
          if (item.id == res.data.task_info.style_id) {
            style_id_index = index
          }
        })
        let _sizeIndex = 0
        this.state.imgSize.forEach((item, index) => {
          if (res.data.task_info.img_size == item.name) {
            _sizeIndex = index
          }
        })
        let _samplingIndex = 0
        this.state.sampling.forEach((item, index) => {
          if (item == res.data.task_info.sampler) {
            _samplingIndex = index
          }
        })

        //定时器不要轻易改，避免造成服务器攻击
        if (res.code == 200) {
          this.setState({
            value: res.data.task_info.prompt,
            negativeValue: res.data.task_info.negative_prompt,
            modelIndex: model_id_index,
            loraIndex: style_id_index,
            sizeIndex: _sizeIndex,
            mass: res.data.task_info.img_type,
            samplingIndex: _samplingIndex
          })
        }
      }
    })
  }
  getRadomPrompt () {
    api.getRadomPrompt().then(res => {
      if (res.code == 200) {
        this.setState({
          value: res.data.prompt,
          negativeValue: res.data.negative_prompt
        })
        document.getElementById('textarea-num').innerHTML = res.data.prompt.length + "/1000";
        document.getElementById('negative_prompt').innerHTML = res.data.negative_prompt.length + "/1000";
      }
    })
  }
  deleteDrawText () {
    setTimeout(() => {
      this.setState({
        value: ''
      })
      document.getElementById('textarea-num').innerHTML = 0 + "/1000";
    }, 200)
  }
  deleteNegativeValue () {
    setTimeout(() => {
      this.setState({
        negativeValue: ''
      })
      document.getElementById('negative_prompt').innerHTML = 0 + "/1000";
    }, 200)
  }
  onInput (e) {
    var num = e.detail.cursor;
    document.getElementById('textarea-num').innerHTML = num + "/1000";
  }
  onBlur (e) {
    this.setState({
      value: e.detail.value
    })
  }
  onInputNegative (e) {
    var num = e.detail.cursor;
    document.getElementById('negative_prompt').innerHTML = num + "/1000";
  }
  onBlurNegative (e) {
    this.setState({
      negativeValue: e.detail.value
    })
  }
  changeOpen () {
    this.setState({
      isOpen: !this.state.isOpen
    })
  }
  selectModel (item, index) {
    this.setState({
      modelIndex: index,
      loraIndex: 0
    })
  }
  subNum () {
    if (this.state.drawNum <= 1) return
    this.setState({
      drawNum: this.state.drawNum - 1
    })
  }
  addNum () {
    if (this.state.drawNum >= 4) return
    this.setState({
      drawNum: this.state.drawNum + 1
    })
  }
  changeMeasurement (item, index) {
    if (this.state.consultImg.length > 0) {
      Taro.showToast({
        title: `您已选择图尺寸`,
        icon: 'error',
      });
      return
    }
    this.setState({
      sizeIndex: index
    })
  }
  changeSampling (item, index) {
    this.setState({
      samplingIndex: index
    })
  }
  changeLora (item, index) {
    this.setState({
      loraIndex: index
    })
  }
  changeMass (e) {
    this.setState({
      mass: e
    })
  }
  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) {
      }

    })
  }
  //生成图片
  generatePictures () {
    let that = this
    Taro.showLoading({
      title: '加载中',
    })

    console.log('生成图片');
    console.log();
    // setTimeout(() => {
    if (this.state.value.length == 0) {
      Taro.showToast({
        title: `请填写绘画描述`,
        icon: 'error',
      });
      return
    }
    let pramas = {
      // model_name: this.state.models[this.state.modelIndex].model_name,
      // file_name: this.state.models[this.state.modelIndex].lora_infos.length > 0 ? this.state.models[this.state.modelIndex].lora_infos[this.state.loraIndex].file_name : '',
      model_id: this.state.models[this.state.modelIndex].id,
      style_id: this.state.models[this.state.modelIndex].lora_infos.length > 0 ? this.state.models[this.state.modelIndex].lora_infos[this.state.loraIndex].id : 0,
      img_size: this.state.imgSize[this.state.sizeIndex].name,
      img_cnt: this.state.drawNum,
      cfg_scale: this.state.sliderNum,
      sampler: this.state.sampling[this.state.samplingIndex],
      prompt: this.state.value,
      negative_prompt: this.state.negativeValue,
      img_type: this.state.mass,
      img_url: this.state.consultImg
    }
    api.drawTxt2img(pramas).then(res => {
      if (res.code == 200) {
        Taro.hideLoading()
        if (process.env.TARO_ENV == 'weapp') {
          this.subscribe(res.data.task_id)
        }
        Taro.navigateTo({
          url: `/moduleA/pages/darwDetailIndex/index?task_id=${res.data.task_id}`
        })
      } else {
        console.log('11111111111');
        Taro.hideLoading()
        if (res.code == 4001) {
          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) {
          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)
  }
  //抖音激励广告
  playVideoTT (item) {
    let that = this
    let lastTime = this.state.lastTime;
    let now = new Date().getTime();
    if (now - lastTime < 2000) return
    console.log(item, 'itehndodjd');
    this.setState({
      lastTime: now
    })
    Taro.showLoading({
      title: '加载中...'
    })
    const videoAd = tt.createRewardedVideoAd({ adUnitId: item.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) {
        api.finishTask({ task_id: item.id }).then(res => {
          if (res.code == 200) {
            Taro.showToast({
              title: '领取点券成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        Taro.showToast({
          title: '领取点券失败',
          icon: 'none',
          duration: 2000
        })
      }
    }
    // 监听视频播放完成
    videoAd.onClose(videoAd.closeHandler);
  }
  //微信激励广告
  playVideo (item) {
    let lastTime = this.state.lastTime;
    let now = new Date().getTime();
    if (now - lastTime < 2000) return
    console.log(item, 'itehndodjd');
    this.setState({
      lastTime: now
    })
    // 在页面中定义激励视频广告
    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) {
              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('激励视频 广告显示失败')
          })
      })
    }

  }
  toChat (e) {
  }
  //选择标签
  selectedLabel (item, index) {
    this.setState({
      tagsIndex: index,
      isTags: true
    })
  }
  //选择子标签
  selectedSubtag (item, index) {
    let tags = this.state.tags
    tags[this.state.tagsIndex].tags[index].isSelect = !tags[this.state.tagsIndex].tags[index].isSelect
    this.setState({
      tags: tags
    })
  }
  //确定标签
  defineSubtag () {
    console.log('defineSubtag');
    let nowSelectTag = []
    let value = this.state.value
    let nowSelectTagObj = ''
    this.state.tags[this.state.tagsIndex].tags.forEach(item => {
      if (item.isSelect) {
        nowSelectTag.push(item.zh_name)
      }
    })
    nowSelectTagObj = nowSelectTag.toString()
    let _value = value.length > 0 ? `${value},${nowSelectTagObj}` : nowSelectTagObj
    this.setState({
      value: _value,
      isTags: !this.state.isTags
    }, () => {
      let _tags = this.state.tags
      _tags.forEach(item => {
        item.tags.forEach(e => {
          e['isSelect'] = false
        })
      })
      this.setState({
        tags: _tags
      })
    })
  }
  onClose (e) {
    console.log('onClose');
    this.setState({
      isTags: false
    })
  }
  //上传参考图
  upLode () {
    let that = this
    Taro.chooseMedia({
      count: 1, // 默认9
      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
        }
        Taro.hideLoading()
        Taro.navigateTo({
          url: `/moduleA/pages/upload/index?image=${file}`
        })
      }
    })
  }
  deleteImg () {
    this.setState({
      consultImg: ''
    })
  }
  toRealDetail (item, index) {
    Taro.navigateTo({
      url: item.jpath
    })
  }

  render () {
    return (
      <View className='mine'>
        {
          this.state.draw_infos.length > 0 &&
          <Swiper
            className='banner'
            indicatorColor='#121D34'
            indicatorActiveColor='#0F84EC'
            circular
            autoplay
            interval='3000'
            adjustHeight='first'
            indicatorDots
          >
            {
              this.state.draw_infos.map((item, index) => (
                <SwiperItem key={index}>
                  <View className='banner-info'>
                    <Image className='banner-image' src={item.img} onClick={e => (this.toRealDetail(item, index))}></Image>
                  </View>
                </SwiperItem>
              ))
            }
          </Swiper>
        }
        <View className='draw-content'>
          <View className='draw-title'>绘画描述</View>
          <View className='draw-text'>
            <View className='draw-content-func'>
              <View className='recommend'>
                <Image className='recommend-img' src='https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1678934357612.png'></Image>
                <View className='recommend-text' onClick={e => (this.getRadomPrompt())}>使用推荐词</View>
              </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>
          <View className='draw-title'>选择标签</View>
          <ScrollView
            className='recharge'
            scrollX
          >
            {
              this.state.tags.map((item, index) => (
                <View className='recharge-info'
                  key={index}
                  onClick={e => (this.selectedLabel(item, index))}>
                  {item.name}
                </View>
              ))
            }
          </ScrollView>
          <Block>
            {
              this.state.isTags &&
              <AtFloatLayout isOpened scrollX title={this.state.tags[this.state.tagsIndex].name} onClose={e => (this.onClose(e))}>
                <View className='layout-content'>
                  {
                    this.state.tags[this.state.tagsIndex].tags.map((item, index) => (
                      <View className='layout-block'
                        key={index}
                        style={item.isSelect ? ' border: 2px solid #0F84EC;background: #0F84EC;color: #FFFFFF;' : 'border: 2px solid rgba(2, 2, 2, 0.75); color: rgba(2, 2, 2, 0.75);background: #FFFFFF;'}
                        onClick={e => (this.selectedSubtag(item, index))}
                      >
                        {item.zh_name}
                      </View>
                    ))
                  }
                </View>

                <View className='selection'>
                  <View className='selection-botton' onClick={e => (this.defineSubtag())}>
                    确定标签
                  </View>
                </View>
              </AtFloatLayout>
            }
          </Block>
          <View className='draw-title'>选择模型</View>
          <View className='model-list'>
            {
              !this.state.isOpen ?
                this.state.models.slice(0, 6).map((item, index) => (
                  <View className='model-info'
                    style={this.state.modelIndex == index ? `border: 2px solid #0F84EC; background:url(${item.img});background-size: 100% 100%;` : `background:url(${item.img});background-size: 100% 100%;`}
                    key={index}
                    onClick={e => (this.selectModel(item, index))}>
                    <View className='model-info-bottom'>
                      {item.name}
                    </View>
                  </View>
                )) :
                this.state.models.map((item, index) => (
                  <View className='model-info'
                    style={this.state.modelIndex == index ? `border: 2px solid #0F84EC; background:url(${item.img});background-size: 100% 100%;` : `background:url(${item.img});background-size: 100% 100%;`}
                    key={index}
                    onClick={e => (this.selectModel(item, index))}>
                    <View className='model-info-bottom'>
                      {item.name}
                    </View>
                  </View>
                ))
            }
          </View>
          {
            this.state.models.length > 6 &&
            <View className='isOpen'>
              <View className='open-content' onClick={e => (this.changeOpen())}>
                <View className='open-title'>{!this.state.isOpen ? '展开' : '收起'}</View>
                <Image className='open-img' src={!this.state.isOpen ? 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1678935050487.png' : 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/total_picture/1678935114571.png'}></Image>
              </View>
            </View>
          }
          {
            this.state.models[this.state.modelIndex] &&
            this.state.models[this.state.modelIndex].lora_infos.length > 0 &&
            <View>
              <View className='draw-title'>风格</View>
              <View className='model-style-list'>
                {
                  this.state.models[this.state.modelIndex].lora_infos.map((item, index) => (
                    <View className='model-style-info' key={index} style={this.state.loraIndex == index ? `border: 2px solid #0F84EC;background:url(${item.img});background-size: 100% 100%;` : `background:url(${item.img});background-size: 100% 100%;`} onClick={e => (this.changeLora(item, index))}>
                      <View className='model-style-info-name'>{item.name}</View>
                    </View>
                  ))
                }

              </View>
            </View>
          }
          <View className='draw-title'>上传参考图</View>
          <View className='consult'>
            {
              this.state.consultImg.length == 0 ?
                <View className='consult-content' onClick={e => (this.upLode())}>
                  +
                </View>
                :
                <View className='consult-model'>
                  <Image className='consult-img' mode='aspectFit' onClick={e => (this.upLode())} src={this.state.consultImg}></Image>
                  <Image className='delete' src='http://video-img.fyshark.com/1680147210173guanbi.png' onClick={e => (this.deleteImg())}></Image>
                </View>
            }
          </View>
          <View className='draw-title'>色彩丰富度</View>
          <View className='components-page'>
            <Slider style={'margin: 10px 0;'} showValue step={1} max={15} min={1} activeColor='#0F84EC' value={this.state.sliderNum} />
          </View>
          <View className='draw-title'>图片尺寸</View>
          <View className='measurement-list'>
            {
              this.state.imgSize.map((item, index) => (
                <View className='measurement-info' style={this.state.sizeIndex == index ? 'border: 2px solid #0F84EC;' : ''} key={index} onClick={e => (this.changeMeasurement(item, index))}>
                  <Image className='measurement-img' src={item.img}></Image>
                  <View className='measurement-title'>{item.name}</View>
                </View>
              ))
            }
          </View>
          <View className='draw-title'>生成数量</View>
          <View className='draw-num'>
            <View className='subtract' onClick={e => (this.subNum())}>-</View>
            <View className='num'>{this.state.drawNum}</View>
            <View className='add' onClick={e => (this.addNum())}>+</View>
          </View>
          <View className='draw-title'>图片质量</View>
          <View className='draw-mass'>
            <View className='mass-same' style={this.state.mass == 0 ? 'border: 2px solid #0F84EC;' : ''} onClick={e => (this.changeMass(0))}>普通</View>
            <View className='mass-high' style={this.state.mass == 1 ? 'border: 2px solid #0F84EC;' : ''} onClick={e => (this.changeMass(1))}>高清</View>
          </View>
          <View className='draw-title'>采样方式</View>
          <View className='draw-sampling'>
            {
              this.state.sampling.map((item, index) => (
                <View className='sampling-same' style={this.state.samplingIndex == index ? 'border: 2px solid #0F84EC;' : ''} key={index} onClick={e => (this.changeSampling(item, index))}>{item}</View>
              ))
            }
          </View>
          <View className='draw-title'>绘画不要的元素</View>
          <View className='draw-text'>
            <View className='draw-content-func'>
              <View className='delete-draw-text' onClick={e => (this.deleteNegativeValue())}>清空</View>
            </View>
            <Textarea
              value={this.state.negativeValue}
              className='draw-taxtarea'
              placeholder='| 请输入相关描述，也可以输入关键词～'
              showCount
              onInput={e => (this.onInputNegative(e))}
              onBlur={e => (this.onBlurNegative(e))}
              maxlength='1000' />

            <View className='textarea-num' id='negative_prompt'>{this.state.negativeValue.length}/1000</View>
          </View>
        </View>
        <View className='generate-pictures' onClick={e => (this.generatePictures(e))} >
          生成图片（消耗{this.state.drawNum * 2 * (this.state.mass + 1)}点券）
        </View>
      </View>
    )
  }
}
