<template>
  <div class="AddMerchants">
    <image class="banner" mode="aspectFill" src="https://cdn.cunwuyun.cn/wxmp/tianfuxing/rz.jpg" />
    <div class="form">
      <div class="form-item">
        <h2>商家名称</h2>
        <div class="right">
          <input placeholder="请输入商家名称" v-model="merchantName" />
          <image class="right" src="https://cdn.cunwuyun.cn/wxmp/tianfuxing/ContentRightArrow@2x.png" />
        </div>
      </div>
      <div class="form-item">
        <h2>地理位置</h2>
        <div class="right" @click="chooseLocation" hover-class="text-hover">
          <span :style="{color: address ? '#333' : '#999'}">{{ address ? address : '请选择地理位置' }}</span>
          <image class="right" src="https://cdn.cunwuyun.cn/wxmp/tianfuxing/ContentRightArrow@2x.png" />
        </div>
      </div>
    </div>
    <div class="upload">
      <h2>门店照片</h2>
      <div class="upload-wrapper">
        <div class="imgs" v-for="(item, index) in logoFiles" :key="index">
          <image :src="item.url" mode="aspectFill" @click="prev(item.url)" />
          <image class="remove" @click.stop="remove(index)" src="https://cdn.cunwuyun.cn/wxmp/tianfuxing/close_release.png" />
        </div>
        <div class="add" @click="upLoad1" v-if="logoFiles.length < 9">
          <div></div>
          <span>添加照片</span>
        </div>
      </div>
    </div>
    <div class="btn-wrapper">
      <div class="btn" hover-class="text-hover" :style="{background: isAdd ? 'rgba(45, 125, 255, 0.5)' : '#2D7DFF'}" @click="save">{{ isAdd ? '审核中' : '提交申请' }}</div>
    </div>
  </div>
</template>

<script>
  import { mapActions, mapState } from 'vuex'
  export default {
    name: 'AddMerchants',
    appName: '商家入驻',

    data () {
      return {
        address: '',
        lat: '',
        lng: '',
        merchantName: '',
        logoFiles: [],
        hideStatus: false,
        isAdd: false
      }
    },

    computed: {
      ...mapState(['user', 'token'])
    },

    onLoad () {
      if (!this.token) {
        this.autoLogin()
      } else {
        this.getUserInfo().then(() => {
          if (this.user.merchantInfo) {
            if (this.user.merchantInfo.status === '0') {
              this.isAdd = true
            }
            this.address = this.user.merchantInfo.address
            this.lat = this.user.merchantInfo.lat
            this.lng = this.user.merchantInfo.lng
            this.merchantName = this.user.merchantInfo.merchantName
            this.logoFiles = this.user.merchantInfo.logoFiles || []
          }
        })
      }
    },

    methods: {
      ...mapActions(['autoLogin', 'getUserInfo']),

      chooseLocation () {
        uni.chooseLocation({
	        success: res => {
            this.address = res.name
            this.lat = res.latitude
            this.lng = res.longitude
          },
          fail: err => {
            console.log(err)
          }
        })
      },

      upLoad1 () {
        console.log(232)
        this.hideStatus = false
        if (this.logoFiles.length > 9) {
          return this.$toast(`图片不能超过9张`)
        }
        uni.chooseImage({
          count: (9 - this.logoFiles.length) > 0 ? 9 - this.logoFiles.length : 0,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            if (res.tempFilePaths.length > 9) {
              this.$toast(`图片不能超过9张`)

              return false
            }

            this.$loading('上传中')
            res.tempFilePaths.forEach((item, index) => {
              if (index === res.tempFilePaths.length - 1) {
                this.hideStatus = true
              }

              this.$nextTick(() => {
                this.uploadFile(item, res.tempFilePaths.length)
              })
            })
          }
        })
      },

      remove (index) {
        this.logoFiles.splice(index, 1)
      },

      uploadFile (img) {
        uni.uploadFile({
          url: this.$instance.defaults.baseURL + (process.env.NODE_ENV == 'production' ? '/api' : '') + '/file/add',
          filePath: img,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            Authorization: uni.getStorageSync('token'),
          },
          success: (res) => {
            const data = JSON.parse(res.data)

            if (data.code === 0 && this.logoFiles.length < 9) {
              this.logoFiles.push({
                url: data.data[0].split(';')[0],
                id: data.data[0].split(';')[1]
              })
            } else {
              this.$toast(data.msg)
            }
          },
          complete: () => {
            this.$nextTick(() => {
              if (this.hideStatus) {
                this.$hideLoading()
                this.hideStatus = false
              }
            })
          }
        })
      },

      prev (url) {
        wx.previewImage({
          current: url,
          urls: this.logoFiles.map(v => v.url)
        })
      },

      save () {
        if (!this.merchantName) {
          return this.$toast('请输入商家名称')
        }

        if (!this.address) {
          return this.$toast('请选择商家地址')
        }

        if (!this.logoFiles.length) {
          return this.$toast('请上传门店照片')
        }

        if (this.isAdd) {
          return false
        }

        this.$loading()
        this.$instance.post('/api/appmerchantinfo/addOrUpdate', {
          merchantName: this.merchantName,
          address: this.address,
          logoFiles: this.logoFiles,
          lat: this.lat,
          lng: this.lng,
          openId: this.user.openId,
          id: this.user.merchantInfo ? this.user.merchantInfo.id : ''
        }).then(res => {
          uni.hideLoading()
          if (res.code === 0) {
            this.$dialog.alert({
              title: '温馨提示',
              content: '提交申请成功，请等待后台审核！'
            }).then(() => {
              uni.navigateBack()
            }).catch(() => {})
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .AddMerchants {
    padding: 32px 32px 130px;

    .banner {
      width: 100%;
      height: 240px;
      border-radius: 32px;
    }

    .form {
      margin: 32px 0;
      padding: 0 32px;
      box-shadow: inset 0 0 0 0 #EEEEEE;
      border-radius: 32px;
      background: #fff;

      .form-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 128px;

        &:first-child {
          border-bottom: 1px solid #EEEEEE;
        }

        h2 {
          font-size: 30px;
          color: #666666;
        }

        .right {
          display: flex;
          align-items: center;

          span, input {
            color: #333333;
            font-size: 30px;
          }

          input {
            text-align: right;
          }

          image {
            width: 32px;
            height: 32px;
          }
        }
      }
    }

    .upload {
      padding: 32px;
      background: #FFFFFF;
      border-radius: 32px;
      box-shadow: inset 0 0 0 0 #EEEEEE;

      h2 {
        margin-bottom: 24px;
        font-size: 30px;
        color: #666666;
      }

      .upload-wrapper {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
      }

      .imgs {
        position: relative;
        width: 200px;
        height: 200px;
        margin: 0 10px 10px 0;
        border-radius: 8px;

        image {
          width: 200px;
          height: 200px;
          border-radius: 8px;
        }
        .remove {
          position: absolute;
          top: 0%;
          right: 0%;
          z-index: 11;
          width: 36px;
          height: 36px;
          transform: translate(50%, -50%);
        }
      }

      .add {
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
        width: 200px;
        height: 200px;
        margin: 0 0px 10px 0;
        background: #EFF5FA;
        border-radius: 8px;

        span {
          margin-top: 16px;
          font-size: 26px;
          color: #999999;
        }

        div {
          position: relative;
          width: 64px;
          height: 64px;
          border-radius: 50%;
          background: #FFFFFF;

          &:after {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 4px;
            height: 32px;
            background: #333333;
            border-radius: 4px;
            transform: translate(-50%, -50%);
            content: ' ';
          }

          &::before {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 32px;
            height: 4px;
            background: #333333;
            border-radius: 4px;
            transform: translate(-50%, -50%);
            content: ' ';
          }
        }
      }
    }
  }
</style>
