import Taro, { Component } from '@tarojs/taro';
import { TaroCanvasDrawer } from '@components/taro-plugin-canvas';
import dayjs from 'dayjs'
import './poster.scss'
/**
 * 文档参考
 * http://taro-ext.jd.com/plugin/view/5d23051670a0f46a87c9785b
 */
export default class Index extends Component {
  static options = {
    addGlobalClass: true,
  }
  static defaultProps = {
    data: {}
  }
  state = {
    // 绘制的图片
    shareImage: null,
    canvasStatus: false,
    config: null,
    visible: false,
    basicConfig: {
      width: 640,
      height: 1136,
      backgroundColor: '#ffffff',
      debug: false
    }
  }
  componentWillMount() {
    this.initConfig()
    Taro.showLoading({
      title: '生成中...',
      icon: 'none'
    })
  }
  initConfig() {
    const { data } = this.props
    const { basicConfig } = this.state
    const texts = [
      {
        x: 170,
        y: 720,
        text: data.nickname + ' 邀您参与' || '',
        fontSize: 28,
        color: '#666',
        baseLine: 'middle',
        lineHeight: 48,
        // textAlign: 'left',
        width: 260,
        zIndex: 999
      },
      {
        x: 480,
        y: 720,
        text: dayjs(data.createDate).format('YYYY-MM-DD') || '',
        fontSize: 25,
        color: '#666',
        baseLine: 'middle',
        lineHeight: 48,
        width: 200,
        zIndex: 999
      },
      {
        x: 30,
        y: 820,
        text: data.title,
        fontSize: 30,
        color: 'black',
        baseLine: 'middle',
        lineNum: 2,
        lineHeight: 48,
        // textAlign: 'center',
        width: 560,
        zIndex: 999
      },
      {
        x: 30,
        y: 890,
        text: data.posterDescription||'活动描述',
        fontSize: 28,
        color: '#999',
        baseLine: 'middle',
        lineNum: 2,
        lineHeight: 48,
        width: 560,
        zIndex: 999
      },
      {
        x: 30,
        y: 1010,
        text: '长按识别小程序码',
        fontSize: 26,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 200,
        zIndex: 11
      },
      {
        x: 30,
        y: 1065,
        text: '进入',
        fontSize: 26,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 50,
        zIndex: 11
      },
      {
        x: 100,
        y: 1065,
        text: '橙蕉',
        fontSize: 34,
        color: 'red',
        baseLine: 'middle',
        lineHeight: 48,
        width: 120,
        zIndex: 11
      },
      {
        x: 190,
        y: 1065,
        text: '热门活动',
        fontSize: 26,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 150,
        zIndex: 11
      },
    ]
    const images = [
      {
        url: data.poster,
        width: 640,
        height: 670,
        y: 0,
        x: 0
      },
      {
        url: data.qrcode,
        width: 160,
        height: 160,
        y: 950,
        x: 450,
        zIndex: 999
      },
      {
        url: data.avatarurl || require('@assets/default-avatar.png'),
        width: 130,
        height: 130,
        y: 630,
        x: 20,
        borderRadius: 130,
        zIndex: 999
      }
    ]

    const blocks = [
      {
        x: 0,
        y: 936,
        width: 640,
        height: 200,
        backgroundColor: 'rgba(248,248,248,1)',
        zIndex: 1
      }
    ]
    const config = Object.assign(basicConfig, { images, blocks, texts })
    this.setState({
      config,
      canvasStatus: true
    })
  }

  onCreateSuccess = (result) => {
    const { tempFilePath, errMsg } = result;
    Taro.hideLoading();
    if (errMsg === 'canvasToTempFilePath:ok') {
      this.setState({
        shareImage: tempFilePath,
        canvasStatus: false,
        config: null,
        visible: true
      });
    } else {
      this.setState({
        canvasStatus: false,
        config: null
      });
      Taro.showToast({ icon: 'none', title: errMsg || '出现错误' });
      console.log(errMsg);
      this.hidePoster()
    }
  }

  onPreview(e) {
    e.stopPropagation()
    e.preventDefault()
    Taro.previewImage({
      current: this.state.shareImage,
      urls: [this.state.shareImage]
    })
  }

  onCreateFail = (error) => {
    console.log(error);
  }

  hidePoster(e) {
    Taro.hideLoading();
    this.props.toggle(false)
  }

  // 保存图片至本地
  saveToAlbum = (e) => {
    e.stopPropagation()
    e.preventDefault()

    Taro.authorize({ scope: "scope.writePhotosAlbum" }).then(res => {
      console.log('auth:', res)
      Taro.saveImageToPhotosAlbum({
        filePath: this.state.shareImage,
      }).then(res => {
        Taro.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 2000,
        });
      })
    }).catch(err => {
      console.log('err:', err)
      Taro.showToast({
        title: '未开启相册权限',
        icon: 'none'
      })
    })
  }

  render() {
    return (
      <Block>
        {
          this.state.canvasStatus && (
            <TaroCanvasDrawer
              config={this.state.config}
              onCreateSuccess={this.onCreateSuccess}
              onCreateFail={this.onCreateFail}
            />
          )
        }
        {
          this.state.visible && (
            <View className="poster">
              <View className="con">
                <View className="con-head">
                  <Text>保存后分享图片</Text>
                  <Text className="iconfont icon-buoumaotubiao20" onClick={this.hidePoster}></Text>
                </View>
                <View className="con-body">
                  <Image className="result-img" mode="aspectFit" lazy-load src={this.state.shareImage} onClick={this.onPreview}></Image>
                </View>
                <Button className="save-btn" onClick={this.saveToAlbum}>保存海报</Button>
              </View>
            </View>
          )
        }
      </Block>
    )
  }
}