import Taro, { Component } from '@tarojs/taro';
import { TaroCanvasDrawer } from '@components/taro-plugin-canvas';
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: '#2F3957',
      debug: false
    },
  }
  componentDidMount() {
    this.initConfig()
    Taro.showLoading({
      title: '海报生成中...'
    })
  }

  initConfig() {
    const { data } = this.props
    const { basicConfig } = this.state
    const texts = [
      {
        x: 70,
        y: 150,
        text: `${data.name}`,
        fontSize: 38,
        color: 'black',
        baseLine: 'middle',
        lineHeight: 48,
        width: 260,
        zIndex: 999
      },
      {
        x: 70,
        y: 210,
        text: `${data.company}`,
        fontSize: 30,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 260,
        zIndex: 999
      },
      {
        x: 110,
        y: 260,
        text: `${data.phone}`,
        fontSize: 28,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 260,
        zIndex: 999
      },
      {
        x: 120,
        y: 470,
        text: `金牌置业顾问`,
        fontSize: 32,
        color: '#000',
        baseLine: 'middle',
        lineHeight: 48,
        width: 260,
        zIndex: 999
      },
      {
        x: 70,
        y: 540,
        text: `好评经纪人，熟悉楼盘特色，很有耐心，非常专业有素养...`,
        fontSize: 30,
        color: '#666',
        baseLine: 'middle',
        lineNum: 2,
        lineHeight: 48,
        // textAlign: 'center',
        width: 500,
        zIndex: 999
      },
      {
        x: 100,
        y: 710,
        text: '长按识别小程序码',
        fontSize: 26,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 200,
        zIndex: 100
      },
      {
        x: 100,
        y: 755,
        text: '进入',
        fontSize: 26,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 50,
        zIndex: 100
      },
      {
        x: 170,
        y: 755,
        text: '橙蕉',
        fontSize: 34,
        color: 'red',
        baseLine: 'middle',
        lineHeight: 48,
        width: 120,
        zIndex: 100
      },
      {
        x: 260,
        y: 755,
        text: '查看主页',
        fontSize: 26,
        color: '#999',
        baseLine: 'middle',
        lineHeight: 48,
        width: 150,
        zIndex: 100
      },
      {
        x: 320,
        y: 1075,
        text: '橙蕉',
        fontSize: 32,
        color: '#b5b3b3',
        baseLine: 'middle',
        lineHeight: 48,
        width: 640,
        zIndex: 99,
        textAlign: 'center'
      },
    ]
    const blocks = [
      {
        width: 600,
        height: 930,
        x: 20,
        y: 80,
        backgroundColor: '#fff',
        borderRadius: 40,
      },
      {
        width: 520,
        height: 160,
        x: 60,
        y: 650,
        backgroundColor: '#F8F8F8',
        borderRadius: 10,
        zIndex: 99
      }
    ]
    const images = [
      {
        url: require('@assets/person/jinpai.png'),
        width: 42,
        height: 48,
        y: 440,
        x: 70,
        zIndex: 99
      },
      {
        url: require('@assets/person/tel2.png'),
        width: 30,
        height: 30,
        y: 240,
        x: 70,
        zIndex: 99
      },
      {
        url: require('@assets/person/bottom.png'),
        width: 600,
        height: 150,
        y: 870,
        x: 20,
        zIndex: 99,
        borderRadius: 40,
      },
      {
        url: data.picture,
        width: 210,
        height: 300,
        y: 40,
        x: 380,
        borderWidth: 15,
        borderColor: '#f1efef',
        borderRadius: 60,
        zIndex: 99
      },
      {
        url: data.qrcode,
        width: 120,
        height: 120,
        y: 670,
        x: 430,
        zIndex: 100
      },

    ]
    const config = Object.assign(basicConfig, { blocks, images, 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>
    )
  }
}