import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import dayjs from 'dayjs'
import { getDocumentVerify, commitDocumentVerify, getVerifyList } from '@services/user'
import { uploadFiles } from '@utils/request'

const profileBg = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/images/index/profile.png'
const add = require('@assets/add.png')
const closeImg = require('@assets/close.png')

export default class Profile extends Component {
  config = {
    navigationBarTitleText: '我的资料'
  }

  state = {

    documentVerifyId: '',
    imgList: [],
    documentTitle: '',
    verfyList: [], // 审核列表
    descVisible: false,


  }

  componentDidShow() {
    this.getProfile()
  }

  getProfile() {
    Taro.showLoading()
    getVerifyList().then(res => {
      this.setState({
        verfyList: res || []
      },
      //  () => {
      //   if (this.state.verfyList.length == 0) {
      //     this.setState({
      //       showWhich: true
      //     })
      //   } else {
      //     this.setState({
      //       showWhich: false
      //     })
      //   }

      // }
    )
      Taro.hideLoading()
    }).catch((err) => {
      Taro.hideLoading()
      setTimeout(() => {
        Taro.showToast({ icon: 'none', title: '获取信息失败' });
      }, 500)

    });
  }

  // 选择图片
  bindAlbumClick(e) {
    this.setState({
      descVisible: true,
      // showWhich: false
    })
    e.stopPropagation()
    this.setState({
      descVisible: true,
      // showWhich: false
    })
    Taro.showLoading({
      title: '上传中',
    })
    Taro.chooseImage({
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        uploadFiles(res.tempFilePaths).then(data => {
          let arr = []
          data.map((item, index) => {
            arr.push({ img: item, sort: index })
          })
          const imgList = this.state.imgList.concat(arr)
          this.setState({
            marginTop: 0,
            messageType: 'image',
            imgList: imgList || []
          })
        })
      },
      complete: res => {
        Taro.hideLoading()
      }
    })
  }
  // 删除图片
  deleteImg(inx) {

    const imgList = this.state.imgList;
    imgList.splice(inx, 1);
    this.setState({
      imgList: imgList || []
    })
  }
  toProfileDetail(item) {
    console.log(item, "item")
    Taro.navigateTo({
      url: '/pages/person/profile/detail/index?id=' + item.documentVerifyId
    })
  }
  // 查看大图
  onPreview = (item, e) => {
    let urls = []
    this.state.imgList.map((ele, index) => {
      urls.push(ele.img)
    })
    e.stopPropagation()
    e.preventDefault()
    Taro.previewImage({
      current: item.img,
      urls: urls
    })
  }
  // 提交资料审核
  commitBtn() {

    if (this.state.imgList.length == 0) {
      Taro.showToast({ icon: 'none', title: '请先上传图片' });
    } else if (this.state.documentTitle == "") {
      Taro.showToast({ icon: 'none', title: '资料说明不能为空' });
    }
    else {

      const payload = {
        documentTitle: this.state.documentTitle,
        imgList: this.state.imgList
      }

      commitDocumentVerify(payload).then(res => {
        this.setState({
          documentTitle: '',
          imgList: [],
          descVisible: false,
        })
        Taro.showToast({ icon: 'none', title: '提交成功' });
        this.getProfile()

      }).catch((err) => {
        Taro.showToast({ icon: 'none', title: err.errMsg || '提交失败' });
        console.error(err);
      });
    }
  }
  // 输入资料说明
  onInputText = e => {
    this.setState({
      documentTitle: e.detail.value
    })
  }
  // 上传资料模块
  renderUpImages() {
    return (
      <Block>
        <View className="up-btn" onClick={this.bindAlbumClick}>
          <Image className="add-img" src={add} />
          上传资料
        </View>
      </Block>
    )
  }
  // 资料审核列表模块
  // 审核状态 0未审核  1审核通过  2审核不通过 verifyStatus
  renderVerfyList() {
    const { verfyList } = this.state
    return (
      <View className="verfy-list">
        {
          verfyList.map((item, inx) => {
            return (
              <View className="verfy-item" key={`verfy-${inx}`} onClick={this.toProfileDetail.bind(this, (item))}>
                <View className="top">

                  <Text className="title">{item.documentTitle || ' '}</Text><Text className={item.verifyStatus == 0 ? 'status0' : item.verifyStatus == 1 ? 'status1' : 'status2'}>{item.verifyStatus == 0 ? '审核中' : item.verifyStatus == 1 ? '审核通过' : '未通过'}</Text>
                </View>
                <View className="bottom">
                  <Text className="time">{`${dayjs(item.createDate).format('YYYY年MM月DD日 HH:mm:ss')}`}</Text><Text className="handle">点击{item.verifyStatus == 2 ? '编辑' : '查看'}</Text>
                </View>
              </View>
            )

          })
        }

      </View>
    )
  }



  render() {
    const { imgList, documentTitle, verfyList, descVisible } = this.state

    return (
      <View className="profile-page" style={`background: url(${profileBg}) no-repeat top;background-size: 100% 100%;`}>
        <ScrollView scrollY scrollWithAnimation style="height: 100vh">

          {(!verfyList.length && !descVisible) &&
            <View className="up-images">
              {this.renderUpImages()}

              <View className="tip">
                建议上传相关购房资格等相关资料,审核
              </View>
              <View className="tip">
                通过后将获取更多积分、兑换好礼~
              </View>
            </View>
          }
          {(verfyList.length||descVisible) &&
            <View>

              {descVisible &&
                <View>
                  <View className="desc-box">
                    资料说明：
            <Input className='inputDesc' onInput={this.onInputText.bind(this)} type='text' placeholder='请填写资料说明' />
                  </View>
                  <View style="padding:10px 20px">
                    {this.renderUpImages()}
                  </View>
                  <View className="image-box">
                    {imgList.length &&
                      imgList.map((item, inx) => {
                        return (
                          <View className="image-con" key={`img-${inx}`}>
                            <Image className="close-btn" src={closeImg} onClick={this.deleteImg.bind(this, (inx))} />
                            <Image className="img" onClick={this.onPreview.bind(this, (item))} src={item.img} />
                          </View>
                        )
                      })
                    }

                  </View>
                </View>
              }
              {!descVisible &&
                <View>
                  <View style="padding:10px 20px">
                    {this.renderUpImages()}
                  </View>
                  {this.renderVerfyList()}
                </View>}

              {imgList.length && <View className="commit-btn" onClick={this.commitBtn}>提交审核</View>}

            </View>
          }

        </ScrollView>
      </View>
    )
  }
}
