import Taro, { Component } from '@tarojs/taro';
import { ScrollView, View, Block } from '@tarojs/components';
import { TaroCanvasDrawer } from '@components/taro-plugin-canvas';
import './style.scss';

export default class Poster extends Component {
  static options = {
    addGlobalClass: true
  }

  state = {
    images: [],
    done: false,
    current: undefined,
  }

  componentWillMount() {
    if (!Array.isArray(this.props.configs)) {
      throw new Error('未设置海报配置信息')
    }
  }

  onScroll = (e) => {
    const inx = e.detail.current
    this.setState({ current: this.state.images[inx] })
  }

  onPreview = (e) => {
    e.stopPropagation()
    e.preventDefault()
    Taro.previewImage({
      current: this.state.current,
      urls: this.state.images
    })
  }

  onCancel = () => {
    if (typeof this.props.onCancel === 'function') {
      this.props.onCancel()
    }
  }

  saveToAlbum = (e) => {
    e.stopPropagation()
    e.preventDefault()

    if (!this.state.current) {
      return
    }

    Taro.authorize({ scope: "scope.writePhotosAlbum" }).then(res => {
      Taro.saveImageToPhotosAlbum({
        filePath: this.state.current,
      }).then(res => {
        if (typeof this.props.onFinish === 'function') {
          this.props.onFinish()
        }

        Taro.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 2000,
        });
      })
    }).catch(err => {
      console.log('err:', err)
      Taro.showToast({
        title: '未开启相册权限',
        icon: 'none'
      })
    })
  }

  tmpImgs = []

  onCreateSuccess = (inx) => {
    return (result) => {
      const { tempFilePath, errMsg } = result;
      if (errMsg === 'canvasToTempFilePath:ok') {
        this.tmpImgs[inx] = tempFilePath
      } else {
        this.tmpImgs[inx] = undefined
        console.log(errMsg);
      }

      if (inx + 1 === this.props.configs.length) {
        this.setState({ done: true, images: [...this.tmpImgs], current: this.tmpImgs[0] });
        this.tmpImgs = [];
        Taro.hideLoading();
      }
    }
  }

  onCreateFail = (inx) => (err) => {
    this.tmpImgs[inx] = undefined
    if (inx + 1 === this.props.configs.length) {
      this.setState({ done: true, images: [...this.tmpImgs], current: this.tmpImgs[0] });
      this.tmpImgs = [];
      Taro.hideLoading();
    }
    console.err(err);
  }

  render() {
    const { images, done } = this.state
    const { configs } = this.props

    return (
      <View className="poster">
        <View className="con">
          <View className="con-head">
            <Text>保存后分享图片</Text>
            <Text className="iconfont icon-buoumaotubiao20" onClick={this.onCancel}></Text>
          </View>
          <View className="con-body">
            <Swiper className="preview-box" onChange={this.onScroll} >
            {
              done && images.map((img, inx) => {
                return (
                  <SwiperItem key={`img-${inx}`}>
                    <Image className="result-img" mode="aspectFit" lazy-load src={img} onClick={this.onPreview}></Image>
                  </SwiperItem>
                )
              })
            }
            </Swiper>
          </View>
          <Button className="save-btn" onClick={this.saveToAlbum}>保存海报</Button>
        </View>
        {
          !done && configs && configs.length &&
          (
            configs.map((conf, inx) => {
              return (
                <Block key={`cvs-${inx}`}>
                  {
                    !images[inx] && (
                      <TaroCanvasDrawer
                        config={conf}
                        onCreateSuccess={this.onCreateSuccess(inx)}
                        onCreateFail={this.onCreateFail(inx)}
                      />
                    )
                  }
                </Block>
              )
            })
          )
        }
      </View>
    );
  }
}
