<template>
<div class='consult'>
<div class='search-bar'>
  <div>标题:</div>
  <input v-model='title' placeholder="请输入15字以内的标题" maxlength=15>
</div>
<div class='subtitle'>类别（最多选3个）</div>
<div class='select-grid'>
  <div @tap='selectTags(i)' class='grid-item' v-for='(item, i) in sort' :key='i' :style="styleTags[i]">
    <img :src="'/static/imgs/1/'+i+imgs[i]+'.png'" :class='classes[i]'>
    <div>{{item}}</div>
  </div>
</div>
<div class='subtitle'>正文</div>
<div class='textarea'>
  <textarea :placeholder="'请输入'+type+'的正文'" v-model='text' maxlength=200></textarea>
  <!-- <div>{{text.length}}/200</div> -->
</div>
<div class='subtitle'>添加图片</div>
<div class="img-box" style='background:white;'>
  <div v-for="(item,i) in imgfiles" :key="i" @tap='previewImg(i)'><img :src="item"><div @tap.stop='cancelImg(i)'><img src='/static/imgs/cancel.png'></div></div>
  <!-- <img v-for="(item,i) in imgfiles" :key="i" :src="item"> -->
  <img @tap="chooseImage" src='/static/imgs/upload.png'>
</div>

<div class='commit'><div @tap='commit'>提交</div></div>
</div>
</template>

<script>
export default {
  data() {
    return {
      sort: [
        '婚姻家庭',
        '交通事故',
        '刑事辩护',
        '劳动工伤',
        '房产纠纷',
        '债权债务',
        '合同事务',
        '医疗纠纷',
        '知识产权',
        '损害赔偿',
        '征地拆迁',
        '其它'
      ],
      selectedTags: [],
      styleTags: [],
      imgs: ['', '', '', '', '', '', '', '', '', '', '', ''],
      classes: [
        'p0',
        'p1',
        'p2',
        'p3',
        'p4',
        'p5',
        'p6',
        'p7',
        'p8',
        'p9',
        'p10',
        'p11'
      ],
      text: '',
      imgfiles: [],
      title: '',
      canIclear: false,
      type: ''
    }
  },
  methods: {
    cancelImg(i){
      wx.showModal({
        title:'',
        content: '放弃上传这张照片吗?',
        success:res=>{
          if(res.confirm){
            this.imgfiles.splice(i, 1)
          }
        }
      })
    },
    previewImg(i){
      wx.previewImage({
        urls: this.imgfiles,
        current: this.imgfiles[i]
      })
    },
    selectTags(i) {
      if (this.selectedTags.indexOf(i) > -1) {//我点击的类型已经被选择
        this.selectedTags.splice(this.selectedTags.indexOf(i), 1)//删除该类型的选择态(从已选择列表中移除)
        this.styleTags[i] = this.imgs[i] = ''//删除该类型的选择态(去除背景色样式，切换图片)
      } else if (this.selectedTags.length < 3) {//我点击的类型没有被选择且当前已选择数目小于3
        this.selectedTags.push(i) //激活该类型的选择态(添加到已选择列表)
        this.styleTags[i] = 'background:#AA001A;color:white;'//添加背景色样式
        this.imgs[i] = '_select'//切换图片
      }
    },
    commit() {
      const errTitle = '提交失败'
      if (this.title == '') {
        if (
          !wx.showModal({
            title: errTitle,
            content: '标题不能为空',
            showCancel: false,
            success: res => {
              if (res.confirm) return false
            }
          })
        )
          return
      }
      if (this.selectedTags.length == 0) {
        if (
          !wx.showModal({
            title: errTitle,
            content: '类别不能为空',
            showCancel: false,
            success: res => {
              if (res.confirm) return false
            }
          })
        )
          return
      }
      if (this.text == '') {
        if (
          !wx.showModal({
            title: errTitle,
            content: '正文不能为空',
            showCancel: false,
            success: res => {
              if (res.confirm) return false
            }
          })
        )
          return
      }
      wx.showLoading({ title: '正在上传文本' })
      wx.request({
        url: this.rootUrl + '/pub/addpub',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          Info_Title: this.title,
          Info_Content: this.text,
          Info_Tag: this.selectedTags.map(v => ++v).join('.'),
          Info_Type: this.type,
          sessionID: wx.getStorageSync('sessionID')
        },
        success: res => {
          if(res.statusCode=='500'){
            this.service.getUnionId(this.rootAvatar,this.rootUrl).then(res=>{
              console.log(res)
              this.commit()
            })
          }else{
            if(this.imgfiles.length>0){
              this.upLoadImgs(res.data)
            }else if(res.data==1){
              wx.hideLoading()
              wx.navigateBack({delta:1})
              this.canIclear = true
              console.log(res)
            }
          }
        },
        fail: res => {
          console.log(res)
        }
      })
    },
    upLoadImgs(CWXID) {
      wx.showLoading({ title: '正在上传图片' })
      const time = this.imgfiles.length
      let counter = time
      for(let i = 0; i< time; i++){
        wx.uploadFile({
          url: this.rootUrl + '/conwx/addpic',
          filePath: this.imgfiles[i],
          formData: {CWXID},
          name: 'file',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            console.log(res)
            if(res.data==='1'){
              wx.showLoading({ title: `图片${i+1}上传成功` })
            }else{
              wx.showLoading({ title: `图片${i+1}上传失败` })
            }
            if(--counter==0){
              wx.showToast({title:'问题上传成功'})
              const url = `../similar/main?title=${this.title}&text=${this.text}&tags=${this.selectedTags.join(',')}&imgs=${this.imgfiles.join(',')}`
              wx.navigateTo({url})
              this.canIclear = true
            }
          },
          fail: res => {
            console.log(res)
          }
        })
      }
    },
    clearData(){
      this.title = this.text = ''
      this.selectedTags = []
      this.styleTags = []
      this.imgfiles = []
      this.imgs = new Array(12).fill('')
      this.canIclear = false
    },
    chooseImage(e) {
      const count = 9 - this.imgfiles.length
      if(count==0){
        if(!wx.showModal({
          title: '上传限制',
          content: '图片数量上限为9张\n请删除部分图片后再上传新图片',
          showCancel: false,
          success: res=>{
            if(res.confirm){return false}
          }
        })){return}
      }
      wx.chooseImage({
        count,
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: res => {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          console.log('图片路径')
          console.log(res.tempFilePaths)
          this.imgfiles = this.imgfiles.concat(res.tempFilePaths)
        }
      })
    }
  },
  onLoad() {
    this.type = this.$root.$mp.query.type
  },
  onShow() {
    if(this.canIclear){
      this.clearData()
    }
  }
}
</script>
<style lang="stylus" scoped>
.consult
  Height_Width(100%)
  padding-top 20rpx
  Background()
.search-bar
  Flex(flex, , center)
  background white
  Font(30rpx, 60rpx)
  padding 30rpx
  div
    flex none
    margin-right 30rpx
  input
    flex auto
    height 60rpx
    padding 0 10rpx
    Background()
    border-radius 5rpx
.select-grid
  Flex(flex, space-between)
  flex-wrap wrap
  margin 0 1px
  BorderBox()
  width 100%
  .grid-item
    Flex(flex, space-between, center, column)
    flex none
    Height_Width(140rpx, calc(((100% - 3px) / 4)))
    padding 25rpx 0
    BorderBox()
    background white
    border-bottom 1rpx solid #EEE
    img
      Height_Width(50rpx)
    div
      Font(25rpx)
    .p1
      margin-top -5rpx
    .p3
      margin-top -3rpx
    .p1, .p3
      Height_Width(60rpx)
    .p4, .p5, .p6
      Height_Width(47rpx)
    .p7
      margin-top -3rpx
    .p8
      margin-top -2rpx
      Height_Width(55rpx)
    .p10
      Height_Width(60rpx)
      margin-top -5rpx
  .selected
    background blue
.textarea
  padding 30rpx 40rpx
  font-size 30rpx
  background white
  textarea
    Height_Width(400rpx, 100%)
    line-height 50rpx
    border-radius 10rpx
    border 1rpx solid #EEE
  div
    text-align right
    line-height 60rpx
.img-box>div
  position relative
  img
    Height_Width(100%)
  div
    position absolute
    top 0
    right 0
    opacity .5
    background black
    Height_Width(100% / 6)
    Flex(flex,center,center)
    border-radius 0 0 0 10rpx
    img
      Height_Width(60%)
</style>
