import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtTextarea }  from 'taro-ui'
import LFormGroup from '@/c/lform/formGroup'
import LoginPopup from '@/c/login/Popup'
const HLKEY = '654mca0l38b489d9'
const CJ = require('crypto-js')
import './add.scss'

class Index extends Component {
  constructor (props) {
    super(props)
    this.state = {
      userInfo: '',
      token: '',
      isLoginPopupShow: false,
      question_cont: '',
      formObj: {
        is_anon: '2',
      },
      imgArr: [],
    }
  }
  config = {
    navigationBarTitleText: '我要提问',
  }

  componentWillMount () {
    this.getDtl()
  }
  getDtl () {
    this.setState({
      token: Taro.getStorageSync('APP_token') || ''
    })
  }

  commentChange (question_cont) {
    this.setState({
      question_cont
    })
  }

  saveHandle () {
    const { question_cont, formObj, imgArr } = this.state
    if (question_cont && formObj.question_tag) {
      Taro.api.news.apiquestionadd({
        question_tag: formObj.question_tag.join(','),
        question_cont: question_cont,
        is_anon: formObj.is_anon,
        question_img: imgArr.join(','),
      }).then(res => {
        Taro.$msgConfirm('提交成功~', () => {
          Taro.redirectTo({
            url: '/pagesQa/index'
          })
        }, () => {
          Taro.redirectTo({
            url: '/pagesQa/index'
          })
        })
      })
    } else {
      Taro.$msg('请输入提问的类型和内容')
    }
  }

  baseFormChange (key, val) {
    let { formObj } = this.state
    formObj[key] = val
    this.setState({
      formObj
    })
  }

  getUserProfile (e) {
    wx.getUserProfile({
      desc: '用于完善头像和昵称资料',
      success: (res) => {
        const dtlObj = res || {}
        this.setState({
          userInfo: dtlObj.userInfo
        })
        Taro.setStorageSync('APP_userInfo', dtlObj.userInfo)
      }
    })
  }
  openLoginPopup (obj) {
    this.setState({
      isLoginPopupShow: true
    })
  }
  closeLoginPopup (str) {
    this.setState({
      isLoginPopupShow: false
    })
    if (str && str === 'success') {
      this.getDtl()
    }
  }



  addImg () {
    let token = Taro.getStorageSync('APP_token')
    let { imgArr } = this.state
    const that = this
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths
        Taro.uploadFile({
          url: `https://api.honglouplus.com/api/upload/cloud`,
          filePath: tempFilePaths[0],
          name: 'upload',
          formData: {
            'token': token
          },
          success (res){
            const msg = res.data || ''
            const key = CJ.enc.Utf8.parse(HLKEY)
            const bytes = CJ.AES.decrypt(msg, key, {
              mode: CJ.mode.ECB,
              padding: CJ.pad.Pkcs7
            })
            const originalText = bytes.toString(CJ.enc.Utf8)
            const cData = JSON.parse(originalText)
            const curImg = cData.data.url || ''
            imgArr.push(curImg)
            that.setState({
              imgArr
            })
          }
        })
      }
    })
  }
  delImg (index) {
    let { imgArr } = this.state
    imgArr.splice(index, 1)
    this.setState({
      imgArr
    })
  }
  previewImageHandle (current, arr) {
    const { imgArr } = this.state
    Taro.previewImage({
      current,
      urls: imgArr
    })
  }

  renderUploadImg () {
    const { imgArr } = this.state
    const addIcon = require('@img/icon_upload_img.png')
    const closeIcon = require('@img/icon_g_close.png')
    const imgItems = imgArr.map((src, index) => {
      return (
        <View className="si-op" key={index}>
          <Image src={src} className="img" onClick={this.previewImageHandle.bind(this, src)} />
          <Image src={closeIcon} className="i" onClick={this.delImg.bind(this, index)}/>
        </View>
      )
    })
    return (
      <View className="comment-box">
        <View className="cb-title">图片描述
          <View className="s">（非必填，最多3张）</View>
        </View>
        <View className="cb-content">
          <View className="scoped-img">
            {imgItems}
            {
              imgArr.length < 3
              &&
              <View className="si-op" onClick={this.addImg.bind(this)}>
                <Image src={addIcon} className="img"/>
              </View>
            }
          </View>
        </View>
      </View>
    )
  }



  render () {
    const { question_cont, formObj } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const questionTagMoreOptions = {arr: dictData.question_tag}
    const yesnoMoreOptions = {arr: dictData. sys_yesno}
    const { userInfo, token } = this.state
    const uInfo = userInfo || Taro.getStorageSync('APP_userInfo')
    const { isLoginPopupShow } = this.state
    const bgTop = require('./img/bg_top.png')
    return (
      <View className="l-box">
        {
          uInfo
          ? token || isLoginPopupShow
          ? ''
          : <Button className="g-u-btn" onClick={this.openLoginPopup.bind(this)}></Button>
          : <Button className="g-u-btn" onClick={this.getUserProfile.bind(this)}></Button>
        }
        <LoginPopup show={isLoginPopupShow} close={this.closeLoginPopup.bind(this)} />
        <View className="l-floor-pos">
          <Navigator url={'/pagesQa/index'} openType="reLaunch" className="scoped-more">
            <Image className="img" src={bgTop} />
          </Navigator>
          <LFormGroup
            val={formObj.is_anon}
            valStr="is_anon"
            keyStr="选择匿名"
            typeStr="select"
            moreOptions={yesnoMoreOptions}
            bc={this.baseFormChange.bind(this)}
          />
          <LFormGroup
            val={formObj.question_tag}
            valStr="question_tag"
            keyStr="提问类型"
            typeStr="multiSelect"
            moreOptions={questionTagMoreOptions}
            bc={this.baseFormChange.bind(this)}
          />
        </View>
        <View className="comment-box">
          <View className="cb-title">提问内容</View>
          <View className="cb-content">
            <AtTextarea
              value={question_cont}
              onChange={this.commentChange.bind(this)}
              maxLength={300}
              height={300}
              placeholder='你想问的...'
            />
          </View>
        </View>
        {this.renderUploadImg()}
        {/* <Navigator url={'/pagesQa/index'} openType="reLaunch" className="scoped-more">先看看其它人说些啥{'>'}</Navigator> */}
        <View className="l-floor-footer t2">
          <View className="lff-flex">
            <View className="lff-btn full" onClick={this.saveHandle.bind(this)}>提交问题</View>
          </View>
        </View>
      </View>
    )
  }
}

export default Index
