<template>
  <div>
    <template v-if="!showChooseAddress">
      <div class="f-main">
        <div class="content-top">
          <p>企业认证</p>
        </div>
        <div class="f-form">
          <div class="page-part">
            <mt-field placeholder="企业名称"
                      v-model="valid.spaceName"
                      :state="state.spaceName"
                      @blur.native.capture="validateSpaceName"
            ></mt-field>
          </div>
          <div class="page-part">
            <mt-field placeholder="营业执照号"
                      v-model="valid.businessCode"
                      auto-complete="off"
                      :state="state.businessCode"
                      @blur.native.capture="validateBusinessCode"
            ></mt-field>
          </div>
          <div class="page-part">
            <a class="phone-btn-blank" title="上传营业执照扫描件" v-bind:class="{isEmpty: valid.businessCodeImage}">
              <i class="fa fa-picture-o fa-p"></i>
              <span class="upload">上传营业执照扫描件</span>
              <input type="file"
                     class="form-control file-input"
                     name="name"
                     accept="image/jpeg,image/jpg,image/gif,image/bmp,image/png,.pdf"
                     @change="upload"/>
            </a>
            <a class="thumbnail" v-if="valid.businessCodeImage !== ''"><img class="previewImg" alt="" :src="isPdf ? '/images/all/timg.png' : valid.businessCodeImage"></a>
          </div>
          <div class="page-part">
            <mt-field placeholder="法定代表人"
                      v-model="valid.corporation"
                      auto-complete="off"
                      :state="state.corporation"
                      @blur.native.capture="validateCorporation"
            ></mt-field>
          </div>
          <div class="page-part" style="position: relative">
            <!--// 注册地址-->
            <mt-field readonly aria-haspopup="true" aria-expanded="false"
                      placeholder="注册地址"
                      v-model="regAddress"
                      @click.native="chooseAddress"></mt-field>
            <i class="fa fa-map-marker fa-p" v-show="regAddress.length === 0"></i>
          </div>
          <div class="form-btn">
            <div class="page-part">
              <el-checkbox v-model="checked">我已阅读并同意 <a href="/common/agreement" class="rgba">《优软云服务条款》</a></el-checkbox>
            </div>
            <mt-button size="large" type="primary" @click="sureAccount('await')">提 交</mt-button>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <address-choose
        @getAddress="setAddress"
        @getProvince="setProvince"
        @getCity="setCity"
        @getArea="setArea"
        @getDetailAddress="setDetailAddress"
        @getPopAddress="setPopAddress"
        @showEvent="showAddress"
        :popAddress="popAddress"
        :regStreet="regStreet"
        :regProvince="regProvince"
        :regCity="regCity"
        :regDistrict="regDistrict"/>
    </template>
  </div>
</template>

<script>
  import addressChoose from '~components/mobile/enterpriseCertification/addressChoose.vue'
  export default {
    name: 'step-one',
    data () {
      return {
        uploadFileChecked: false,
        isPdf: false,
        showChooseAddress: false,
        checked: true,
        state: {
          spaceName: 'error',
          businessCode: 'error',
          corporation: 'error'
        },
        valid: {
          spaceName: '',
          businessCode: '',
          businessCodeImage: '',
          corporation: ''
        },
        regAddress: '',
        regProvince: '',
        regCity: '',
        regDistrict: '',
        popAddress: '',
        regStreet: ''
      }
    },
    components: {
      addressChoose
    },
    methods: {
      // 弹窗处理
      downToast (type) {
        this.$toast({
          message: type,
          iconClass: 'el-icon-warning'
        })
      },
      // 获取地址
      chooseAddress () {
        this.showChooseAddress = true
      },
      setAddress (detail) {
        this.regAddress = detail
      },
      setProvince (detail) {
        this.regProvince = detail
      },
      setCity (detail) {
        this.regCity = detail
      },
      setArea (detail) {
        this.regDistrict = detail
      },
      setDetailAddress (detail) {
        this.regStreet = detail
      },
      setPopAddress (detail) {
        this.popAddress = detail
      },
      showAddress (info) {
        this.showChooseAddress = info
      },
      // 验证企业名称
      validateSpaceName () {
        if (!this.valid.spaceName) {
          this.downToast('请填写企业名称')
          this.state.spaceName = 'error'
        } else {
          if (this.valid.spaceName.length >= 20) {
            this.state.spaceName = 'warning'
            this.downToast('请填写合适的企业名称，20个字符以内')
          } else {
            this.$http.get(`/api/userspace/name/valid`, {params: {spaceName: this.valid.spaceName}})
              .then(response => {
                if (response.data.content.isValid) {
                  this.state.spaceName = 'warning'
                  this.downToast('该企业已被认证，请确认。')
                } else {
                  this.state.spaceName = 'success'
                }
              }).catch(err => {
                this.downToast(err.errMsg)
              })
          }
        }
      },
      // 验证营业执照号
      validateBusinessCode () {
        let reg = /^[A-Za-z0-9]+$/
        if (!this.valid.businessCode) {
          this.downToast('请填写营业执照号')
          this.state.businessCode = 'error'
        } else {
          if (this.valid.businessCode.length >= 20) {
            this.downToast('输入长度过长，20个字符以内')
            this.state.businessCode = 'warning'
          } else {
            if (reg.test(this.valid.businessCode)) {
              this.$http.get(`/api/userspace/businessCode/valid`, {params: {businessCode: this.valid.businessCode}})
                .then(response => {
                  if (!response.data.content.isValid) {
                    this.state.businessCode = 'success'
                  } else {
                    this.state.businessCode = 'warning'
                    this.downToast('该企业已被认证，请确认')
                  }
                }).catch(err => {
                  this.$message.error(err.errMsg)
                })
            } else {
              this.downToast('营业执照号只能填写字母和数字的组合')
              this.state.businessCode = 'error'
            }
          }
        }
      },
      // 验证法定代表人
      validateCorporation () {
        if (!this.valid.corporation) {
          this.downToast('请填写法定代表人')
          this.state.description = 'error'
        } else {
          if (this.valid.corporation.length >= 20) {
            this.downToast('输入长度过长，20个字符以内')
            this.state.corporation = 'warning'
          } else {
            this.state.corporation = 'success'
          }
        }
      },
      // 上传营业执照扫描件
      upload (e) {
        let file = e.target.files[0]
        if (file) {
          if (file.size > 5 * 1024 * 1024) {
            this.uploadFileChecked = false
            this.downToast('文件大小不能超过5M')
          } else {
            this.$indicator.open('上传中...')
            let param = new FormData()
            param.append('image', file, file.name)
            let config = {
              headers: {'Content-Type': 'multipart/form-data'}
            }
            // 图片上传接口
            this.$http.post('/api/userspace/upload', param, config)
              .then(response => {
                this.$indicator.close()
                if (response.data.success) {
                  let path = response.data.content
                  if (path.slice(path.lastIndexOf('.')).toLowerCase() === '.pdf') {
                    this.isPdf = true
                  } else {
                    this.isPdf = false
                  }
                  this.valid.businessCodeImage = response.data.content
                  this.uploadFileChecked = true
                } else {
                  this.uploadFileChecked = false
                  return Promise.reject(response.data)
                }
              }).catch(err => {
                this.downToast(err.errMsg)
                this.uploadFileChecked = false
              })
          }
        } else {
          this.$indicator.close()
        }
      },
      sureAccount (type) {
        if (this.state.spaceName !== 'success' ||
          this.state.businessCode !== 'success' ||
          this.state.corporation !== 'success' ||
          this.valid.businessCodeImage === '' ||
          this.regAddress === '') {
          this.downToast('请确认填写部分是否有误')
        } else {
          if (!this.checked) {
            this.downToast('您对阅读条款未做勾选')
          } else {
            this.$indicator.open('验证过程中...')
            let param = new FormData()
            param.append('spaceName', this.valid.spaceName)
            param.append('businessCode', this.valid.businessCode)
            param.append('corporation', this.valid.corporation)
            param.append('businessCodeImage', this.valid.businessCodeImage)
            param.append('regAddress', this.regAddress)
            param.append('regProvince', this.regProvince)
            param.append('regCity', this.regCity)
            param.append('regDistrict', this.regDistrict)
            param.append('regStreet', this.regStreet)
            let config = {
              headers: {'Content-Type': 'multipart/form-data'}
            }
            this.$http.post('/valid/userspace/submit', param, config)
              .then(response => {
                this.$indicator.close()
                if (response.data.success) {
                  this.$emit('stepEvent', type)
                } else {
                  this.downToast(response.data.errMsg)
                }
              }).catch((err) => {
                this.$indicator.close()
                this.downToast(err.errMsg)
              })
          }
        }
      }
    }
  }
</script>
