<template>
	<div class="complaints">
    <image mode="aspectFill" style="width:750rpx;height:280rpx;" src="https://eshangtech.com/ShopICO/jianyi_bg.png"></image>
    <div class="complaints-content" >
			<div class="adress-content ">
				<span class="content-title">服务区</span>
				<div class="content-input address-content borbottom" @click="pageMsg.isSelect=true">
					{{pageMsg.serverPartName}}
					<van-icon name="arrow" size="28rpx" custom-style="margin-left:12rpx;" color="#999"/>
				</div>
			</div>
			<div class="adress-content ">
				<span class="content-title">类型</span>
				<div class="content-input address-content borbottom" @click="pageMsg.isSelectType=true">
					{{pageMsg.typeName}}
					<van-icon name="arrow" size="28rpx" custom-style="margin-left:12rpx;" color="#999"/>
				</div>
			</div>
			<div class="adress-content ">
        <span class="content-title">您的姓名</span>
        <div class="content-input borbottom">
          <input type="text" maxlength="20" placeholder="请输入您的姓名" @input="bindKeyInput($event,'SuggestionName')" :value="saveMsg.SuggestionName"/>
        </div>
      </div>
			<div class="adress-content">
        <span class="content-title">联系方式</span>
        <div class="content-input">
          <input type="number" maxlength="11"  placeholder="请输入您的手机号" @input="bindKeyInput($event,'PhoneNumber')" :value="saveMsg.PhoneNumber"/>
        </div>
      </div>
		</div>
    <div class="evaluate-box">
      <div class="tag-list" v-for="(tags,i) in tagList" :key="i">
        <div class="tag-name">{{tags.FIELDENUM_NAME}}</div>
        <div class="tags-box">

          <div class="tag-unit" v-for="(tag,s) in tags.fieldenumList" :key="s" @tap="selectTag(tag)" :class="{'active':tag.ischecked}">{{tag.FIELDENUM_NAME}}</div>
        </div>
      </div>
    </div>
		<div class="evaluate-box">
      <div v-if="pageMsg.isSelect || pageMsg.isSelectType" class="div-textarea" :style="saveMsg.Info!=''?'color:#333;':'color:#999;'">{{saveMsg.Info?saveMsg.Info:'请详细描述您的问题，我们将及时跟进解决（添加图片将有助于我们解决您的问题）'}}</div>
			<textarea cols="30" rows="5" cursor-spacing="200" v-else placeholder="请详细描述您的问题，我们将及时跟进解决（添加图片将有助于我们解决您的问题）" v-model="saveMsg.Info"></textarea>
			<div class="photo-box">
				<div class="images" v-for="(item,i) in imgsList" :key="i">
					<image mode="aspectFit" :src='item' @click="seePhoto(item)"></image>
					<i @click="deleteImg(i)"></i>
				</div>
				<div class="add-photo" @click="choeseImg">
					<i></i>
					上传照片
				</div>
			</div>
		</div>

		<div class="post-btn" :class="{'active': noPost}" @click="checkFn">提交</div>
        <van-popup :show="pageMsg.isSelect"
            position="bottom"
            overlay="false"
            @close="onClose">
            <van-picker show-toolbar @cancel="pageMsg.isSelect=false" @confirm="chosePart" :columns="serverList" value-key="showName"/>
        </van-popup>
		<van-popup :show="pageMsg.isSelectType"
            position="bottom"
            overlay="false"
            @close="pageMsg.isSelectType=false">
            <van-picker show-toolbar @cancel="pageMsg.isSelectType=false" @confirm="changeType" :columns="msgType" value-key="name"/>
        </van-popup>
	</div>
</template>

<script>

import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      noPost: true,
      saveMsg: {
        action_type: 'Complaints',
        ProvinceCode: '',
        ServerPartID: '',
        Type: 2000,
        SuggestionName: '',
        Title: '',
        Info: '',
        PhoneNumber: '',
        WechatOpenId: '',

        imageArr: []
      },
      imgsList: [],
      pageMsg: {
        serverPartName: '',
        isSelect: false,
        typeName: '投诉',
        isSelectType: false
      },
      msgType: [{type: 2000, name: '投诉'}, {type: 4000, name: '咨询'}, {type: 1000, name: '建议'}],
      tagList: [], // 可选择的建议标签
      selectTags: [] // 已选中的建议标签
    }
  },
  computed: {
    ...mapGetters({ 'serverList': 'severList', 'user': 'user', 'serverPart': 'serverPart' })
  },
  methods: {
    chosePart (event) {
      let index = event.target.index
      this.saveMsg.ProvinceCode = this.serverList[index].ProvinceCode
      this.saveMsg.ServerPartID = this.serverList[index].ServerPart_Id
      this.pageMsg.serverPartName = this.serverList[index].ServerPart_Name
      this.onClose()
    },
    changeType (event) {
      let index = event.target.index
      this.saveMsg.Type = this.msgType[index].type
      this.pageMsg.typeName = this.msgType[index].name
      this.pageMsg.isSelectType = false
    },
    onClose () {
      this.pageMsg.isSelect = false
    },
    choeseImg () {
      let _this = this
      let num = 9 - _this.imgsList.length
      if (num === 0) {
        mpvue.showToast({title: '您最多可以上传9张图', icon: 'none'})
        return false
      }
      console.log('1')

      wx.chooseMedia({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (rs) {
          console.log('rs', rs)
          // tempFilePath可以作为img标签的src属性显示图片
          // console.log(rs.tempFiles[0].size)
          _this.noPost = false
          let quality = 100
          if (rs.tempFiles[0].size > 1024 * 200) {
            quality = 1024 * 200 / rs.tempFiles[0].size * 100
          }
          if (quality < 100 && rs.tempFiles[0].path.indexOf('.jpg') > -1) {
            mpvue.compressImage({
              src: rs.tempFilePaths[0], // 图片路径
              quality: quality, // 压缩质量
              success (res) {
                // console.log(rs)
                mpvue.showLoading({
                  title: '图片上传中...',
                  mask: true
                })
                mpvue.uploadFile({
                  url: 'https://mp.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=suggestion',
                  filePath: res.tempFilePath,
                  fileType: 'image',
                  name: 'data',
                  success (res) {
                    let _data = JSON.parse(res.data)
                    _this.imgsList.push(rs.tempFilePaths[0])
                    _this.saveMsg.imageArr.push(_data.Data.IMAGE_PATH)
                    mpvue.hideLoading()
                    _this.noPost = true
                  },
                  fail (res) {
                    console.log(res)
                    _this.noPost = true
                  }
                })
              },
              fail (error) {
                console.log(error)
                _this.noPost = true
              }
            })
          } else {
            mpvue.showLoading(
              {
                title: '图片上传中...',
                mask: true}
            )
            mpvue.uploadFile({
              url: 'https://mp.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=suggestion',
              filePath: rs.tempFilePaths[0],
              fileType: 'image',
              name: 'data',
              success (res) {
                let _data = JSON.parse(res.data)
                _this.imgsList.push(rs.tempFilePaths[0])
                _this.saveMsg.imageArr.push(_data.Data.IMAGE_PATH)
                mpvue.hideLoading()
                _this.noPost = true
              },
              fail (res) {
                console.log(res)
                _this.noPost = true
              }
            })
          }
        }
      })
    },
    seePhoto (item) {
      let _this = this
      mpvue.previewImage({
        current: item, // 当前显示图片的http链接
        urls: _this.imgsList // 需要预览的图片http链接列表
      })
    },
    deleteImg (index) {
      let _this = this
      _this.$api.postCoop({
        action_type: 'DelFile',
        filePath: _this.saveMsg.imageArr[index]
      }).then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.ResultCode == '100') {
          _this.imgsList.splice(index, 1)
          _this.saveMsg.imageArr.splice(index, 1)
        } else {
          mpvue.showToast({
            title: '删除失败请稍后重试。错误：' + res.ResultDesc,
            icon: 'none'
          })
        }
      })
    },
    bindKeyInput (event, name) {
      this.saveMsg[name] = event.mp.detail.value
    },
    checkFn () {
      let _this = this
      let flag = 0

      for (let element in this.saveMsg) {
        if (_this.saveMsg[element] === '') {
          let msg = ''
          switch (element) {
            case 'SuggestionName':
              msg = '您的姓名'
              break
            case 'PhoneNumber':
              msg = '联系电话'
              break
            case 'Info':
              msg = '反馈内容'
              break
          }
          if (msg !== '') {
            mpvue.showToast({
              title: '请输入' + msg,
              icon: 'none'
            })
            flag += 1
            return false
          }
        }
      }
      if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(_this.saveMsg.PhoneNumber)) {
        mpvue.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return false
      }
      if (flag === 0) {
        this.postIt()
      }
    },
    postIt () {
      let _this = this
      let data = _this.saveMsg

      data.imageArr = data.imageArr.toString()

      data.WechatOpenId = this.user.WECHATAPP_OPENID
      data._enumLabel = this.selectTags.toString()
      delete data.__newReference
      mpvue.showLoading({
        title: '正在提交...',
        mask: true
      })
      this.$api.postCoop(data).then(function (rs) {
        _this.$store.commit('refresh', true)
        mpvue.hideLoading()

        // eslint-disable-next-line eqeqeq
        if (rs.ResultCode == '100') {
          mpvue.showToast({
            title: '反馈成功！'
          })
          setTimeout(() => {
            // _this.noPost = true
            mpvue.navigateBack({
              delta: 1
            })
          }, 1000)
        }
      })
    },
    loadIndustry () { // 新增意见时，如果是内部会员则提供默认填写名字和电话
      if (this.user.MEMBERSHIP_MOBILEPHONE) {
        // this.saveMsg.SuggestionName = this.user.MEMBERSHIP_NAME
        this.saveMsg.PhoneNumber = this.user.MEMBERSHIP_MOBILEPHONE
      }
    },
    getTag () {
      let _this = this
      _this.$api.getCoop({
        action_type: 'GetEnumLable',
        fieldexplainField: 'BUSINESS_TARGET',
        fieldenumIndex: 4000
      }).then(res => {
        _this.tagList = res.Data.List
      })
    },
    selectTag (tag) {
      let index = this.selectTags.indexOf(tag.FIELDENUM_VALUE)
      if (index !== -1) {
        this.selectTags.splice(index, 1)
      } else {
        this.selectTags.push(tag.FIELDENUM_VALUE)
      }

      tag.ischecked = tag.ischecked !== undefined ? !tag.ischecked : true
      this.$forceUpdate()
    }
  },
  onUnload () {
    this.saveMsg = {
      action_type: 'Complaints',
      ProvinceCode: '',
      ServerPartID: '',
      Type: 2000,
      SuggestionName: '',
      Title: '',
      Info: '',
      PhoneNumber: '',
      WechatOpenId: '',

      imageArr: []
    }
    this.noPost = true
    this.imgsList = []
  },
  onLoad (option) {
    console.log('this.serverList', this.serverList)
    this.loadIndustry()
    this.pageMsg.serverPartName = this.serverPart.ServerPart_Name
    this.saveMsg.ProvinceCode = this.serverPart.ProvinceCode
    this.saveMsg.ServerPartID = this.serverPart.ServerPart_Id
    this.getTag()
    this.$utils.addUserBehaviorNew();
  }
}
</script>

<style lang="stylus" scoped>
.borbottom
  border-bottom 2rpx solid #eee
.complaints
	// background #fff
	padding-bottom 60rpx
	// height 100%
	font-size 28rpx
.complaints-content
  margin 24rpx
  padding 0 24rpx
  border-radius 12rpx
  background-color #fff
.evaluate-box
  margin 24rpx
  border-radius 12rpx
  background-color #fff
  padding 20rpx 0
	textarea,.div-textarea
		width 640rpx
		color #333
		height 98rpx
		padding 20rpx
		line-height 1.2
	.tip-text
		margin-top 16rpx
		color #646464
		text-align right
		padding-right 20rpx
		.tip-color
			color #ba9b6f
	.photo-box
		display flex
		align-items center
		flex-wrap wrap
		.images
			margin 16rpx 0 16rpx 13rpx
			position relative
			image
				height 140rpx
				width 140rpx
				border-radius 6rpx
				background #fff
			i
				background #ea4848
				height 30rpx
				width 30rpx
				border-radius 50%
				position absolute
				top -15rpx
				right -10rpx
				&:after
					content ' '
					height 4rpx
					width 18rpx
					display block
					background #fff
					margin-top 14rpx
					margin-left 6rpx
					border-radius 4rpx
		.add-photo
			height 138rpx
			width 138rpx
			border-radius 6rpx
			border 1rpx dashed #ba9b6f
			margin-left 12rpx
			text-align center
			color #ba9b6f
			display flex
			flex-direction column
			align-items center
			justify-content center
			i
				margin-bottom 12rpx
				width 42rpx
				height 36rpx
				background url(https://eshangtech.com/wanmeiyizhanImg/pic.png) no-repeat center
				background-size contain
.address-content
  display flex
  align-items center
  justify-content flex-end
.adress-content
  height 96rpx
  line-height 96rpx
  display flex
  align-items center
	.content-title
		width 168rpx
	.content-input
		flex 1
		input
			width 98%
			height 96rpx
			line-height 96rpx
.tag-list
  display flex
  font-size 24rpx
  color #606266
  padding 0 24rpx
.tag-list + .tag-list
  margin-top 8rpx

.tag-list .tag-name
  margin-right 16rpx
  font-size 24rpx
  line-height 2.4
  width 130rpx
.tag-list .tags-box
  width 540rpx


.tag-list .tags-box .tag-unit
  padding 8rpx 24rpx
  background #F4F4F4
  color #606266
  border-radius 24rpx
  margin 8rpx
  font-size 24rpx
  display inline-block
  vertical-align middle

.tag-list .tags-box .tag-unit.active
  color #ED7043
  background #FDF1EC

.post-btn
  background #e5e5e5
  width 690rpx
  height 82rpx
  line-height 82rpx
  border-radius 8rpx
  font-size 32rpx
  text-align center
  color #898989
  margin-left 32rpx
  margin-top 42rpx
  margin-bottom 32rpx
&.active
	background-color #333
	color #d2bc8d

</style>
