<template>
  <!--填写注册信息-->
  <div class="section" @click="onHideAddress">
    <div class="register">
      <div class="x-form-set-header">
        <h4>企业注册信息</h4>
      </div>
      <div class="row">
        <label class="col-sm-2 x-required">企业名称：</label>
        <div class="col-sm-5">
          <input type="text" @change="nameCheck" :disabled="!loginData.isSelf" v-model="data.name" class="form-control" name="name" required="" placeholder="填写营业执照上的企业名称">
        </div>
        <div class="col-sm-5" v-show="!validName.isValidTypeName && !validName.init">
          <p>
            <i class="fa fa-info-circle"></i>请填写正确的企业名称，2~99个字符
          </p>
        </div>
        <div class="col-sm-5" v-show="!validName.isValidName && !validName.init">
          <p>
            <i class="fa fa-info-circle"></i>注册的企业名称已存在，请联系管理员
          </p>
        </div>
      </div>
      <div class="row">
        <label class="col-sm-2 x-required">企业简称：</label>
        <div class="col-sm-5">
          <input type="text" :disabled="!loginData.isSelf" @change="simpleNameCheck" v-model="data.simpleName" class="form-control" name="name" required="" placeholder="请填写正确的企业名称，2~40个字符">
        </div>
        <div class="col-sm-5" v-show="!validSimpleName.isValidSimpleName && !validSimpleName.init">
          <p>
            <i class="fa fa-info-circle"></i>请填写正确的企业名称，2~40个字符
          </p>
        </div>
      </div>
      <div class="row">
        <label class="col-sm-2 x-required">营业执照：</label>
        <div class="col-sm-5">
          <a class="x-btn-blank" v-if="loginData.isSelf">
            <i class="fa fa-picture-o"></i>
            请上传营业执照扫描件（≤5M的图片或PDF）
            <input type="file" @change="upload" class="form-control file-input" name="name" required="" placeholder="请上传营业执照扫描件（≤5M的图片或PDF）" accept="image/jpeg,image/jpg,image/gif,image/bmp,image/png,.pdf">
          </a>
          <img class="previewImg" v-if="data.url != ''" :src="isPdf?'/images/all/timg.png':data.url" alt="">
        </div>
        <div class="col-sm-5" v-show="!validUpload.isValidUpload && !validUpload.init"><p><i class="fa fa-info-circle"></i>请上传营业执照扫描件（≤5M的图片或PDF）</p></div>
      </div>
      <div class="row">
        <label class="col-sm-2 x-required">营业执照号：</label>
        <div class="col-sm-5">
          <input type="text" :disabled="!loginData.isSelf" @change="licenceCheck" v-model="data.licenceId" class="form-control" name="name" required="" placeholder="请填写营业执照上的注册号">
        </div>
        <div class="col-sm-5" v-show="!validLicence.isValidLicence && !validLicence.init"><p><i class="fa fa-info-circle"></i>请填写营业执照上的注册号</p></div>
      </div>
      <div class="row">
        <label class="col-sm-2 x-required">企业地址：</label>
        <div class="col-sm-5">
          <input type="text" readonly aria-haspopup="true" aria-expanded="false" @focus="onShowAddress" :style="!loginData.isSelf?'background-color: #eee;':''" :disabled="!loginData.isSelf" v-model="data.address" class="form-control" name="name" required="" placeholder="填写总部所在地详细地址" style="padding-left:20px;background-color: transparent;">
          <span class="fa fa-map-marker"></span>
          <div v-show="showAddressBox"
               @mouseenter="isInAddressBox = true"
               @mouseleave="isInAddressBox = false"
               style="display: block; left: 14px;" class="dropdown-menu x-union-menu" aria-labelledby="address">
            <div class="x-union-header">
              <div>省份</div>
              <div>城市</div>
              <div>县区</div>
              <div class="x-item-ext">详细地址</div>
            </div>
            <div class="x-union-list">
              <ul class="list-unstyled">
                <li v-for="province in cityData.province"
                    :class="province == address.currentProvince ? 'active' : ''"
                    v-text="province"
                    @click="getCity(province)"></li>
              </ul>
              <ul class="list-unstyled">
                <li v-for="city in cityData.city"
                    :class="city == address.currentCity ? 'active' : ''"
                    v-text="city"
                    @click="getDistrict(city)"></li>
              </ul>
              <ul class="list-unstyled">
                <li v-for="district in cityData.district"
                    v-text="district"
                    :class="district == address.currentDistrict ? 'active' : ''"
                    @click="chooseDistrict(district)"></li>
              </ul>
              <div class="x-item-ext">
                <div class="form-group">
                  <div class="col-sm-12">
                    <textarea id="street" name="street" rows="4" v-model="address.detail" class="form-control x-input" placeholder="xx路xx大厦xx栋xx楼xx室"></textarea>
                  </div>
                </div>
                <div class="text-right">
                  <a class="register-btn btn-submit" @click="submitAddress">确定</a> <a @click="showAddressBox = false" class="register-btn btn-console">取消</a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-5" v-show="!validAddress.isValidAddress && !validAddress.init"><p><i class="fa fa-info-circle"></i>填写总部所在地详细地址</p></div>
      </div>
      <div class="row">
        <label class="col-sm-2">官网地址：</label>
        <div class="col-sm-5">
          <input type="url" :disabled="!loginData.isSelf" @change="websiteCheck" v-model="data.website" class="form-control" name="name" required="" placeholder="www.example.com" style="padding-left:55px;">
          <span class="web">http://</span>
        </div>
        <div class="col-sm-5"></div>
      </div>
      <div class="row next-btn"><button class="btn" :style="loginData.isSelf && !isValid ? 'opacity: .65;':''" @click="sectionChange(2)">下一步</button></div>
    </div>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        data: {
          name: '',
          simpleName: '',
          url: '',
          licenceId: '',
          address: '',
          website: ''
        },
        validName: {
          isValidTypeName: true,
          isValidName: true,
          init: true
        },
        validUpload: {
          isValidUpload: true,
          init: true
        },
        validLicence: {
          isValidLicence: true,
          init: true
        },
        validSimpleName: {
          isValidSimpleName: true,
          init: true
        },
        validAddress: {
          isValidAddress: true,
          init: true
        },
        isValid: false,
        isPdf: false,
        showAddressBox: false,
        isInAddressBox: false,
        temCityData: {},
        cityData: {
          province: [],
          city: [],
          district: []
        },
        address: {
          currentProvince: '',
          currentCity: '',
          currentDistrict: '',
          detail: ''
        }
      }
    },
    props: ['loginData', 'enterpriseData', 'businessImgUrl'],
    watch: {
      enterpriseData: function (val, oldVal) {
        if (val !== {}) {
          this.data.name = val.enName || ''
          this.data.simpleName = val.enShortname || ''
          this.data.licenceId = val.enBussinessCode || ''
          this.data.address = val.enAddress || ''
          this.data.website = val.enUrl || ''
          this.data.url = val.enBussinessCodeImage || ''
          if (this.loginData.isSelf) {
            this.nameCheck()
            this.simpleNameCheck()
            this.licenceCheck()
            this.addressCheck()
            this.websiteCheck()
            this.imgUrlCheck()
            this.checkFullData()
            this.submitRegisterData()
          }
        }
      },
      businessImgUrl: function (val, oldVal) {
        this.data.url = val
        this.checkFullData()
        this.submitRegisterData()
      }
    },
    mounted () {
      this.$http.get('/data/city.json').then(response => {
        this.temCityData = response.data
        for (let province in response.data) {
          this.cityData.province.push(province)
        }
      })
    },
    methods: {
      sectionChange: function (type) {
        if (this.loginData.isSelf && !this.isValid) {
          this.$message.error('请填写正确的注册信息')
        } else {
          this.checkFullData()
          let enterprise = {
            enName: this.data.name,
            enShortName: this.data.simpleName,
            enBussinessCode: this.data.licenceId,
            enAddress: this.data.address,
            enUrl: this.data.website
          }
          let data = {}
          data.enterprise = enterprise
          data.isValidRegister = this.isValid
          data.url = this.data.url
          enterprise.enIsRead = false
          enterprise.enBussinessCodeImage = this.data.url
          if (this.loginData.isSelf) {
            this.$http.post('/basic/user/userCacheEnterprise', enterprise)
            this.$emit('isSelfCacheDataAction', enterprise)
          }
          this.$emit('registerAction', data)
          this.$emit('sectionEvent', type)
        }
      },
      upload: function (e) {
        let file = e.target.files[0]
        this.validUpload.init = false
        if (file.size > 5 * 1024 * 1024) {
          this.validUpload.isValidUpload = false
        } else {
          this.validUpload.isValidUpload = true
          if (file.type !== 'application/pdf') {
            this.isPdf = false
            let param = new FormData()
            param.append('file', file, file.name)
            param.append('chunk', '0')
            let config = {
              headers: {'Content-Type': 'multipart/form-data'}
            }
            this.$http.post('/api/images', param, config)
              .then(response => {
                this.data.url = response.data[0].path
                this.$emit('businessImgUrlAction', this.data.url)
              }, err => {
                console.log(err)
                this.validUpload.isValidUpload = false
              })
          } else {
            let param = new FormData()
            param.append('file', file, file.name)
            let config = {
              headers: {'Content-Type': file.type}
            }
            this.$http.post('/file', param, config)
              .then(response => {
                this.isPdf = true
                this.data.url = response.data[0].path
                this.$emit('businessImgUrlAction', this.data.url)
              }, err => {
                console.log(err)
                this.validUpload.isValidUpload = false
              })
          }
        }
        this.validCheck()
      },
      validCheck: function () {
        this.isValid =
          this.validUpload.isValidUpload && !this.validUpload.init &&
          this.validName.isValidTypeName && !this.validName.init && this.validName.isValidName &&
          this.validLicence.isValidLicence && !this.validLicence.init &&
          this.validSimpleName.isValidSimpleName && !this.validSimpleName.init &&
            this.validAddress.isValidAddress && !this.validAddress.init
      },
      checkFullData: function () {
        this.isValid =
          this.validUpload.isValidUpload &&
          this.validName.isValidTypeName && this.validName.isValidName &&
          this.validLicence.isValidLicence &&
          this.validSimpleName.isValidSimpleName &&
          this.validAddress.isValidAddress
      },
      nameCheck: function () {
        this.validName.init = false
        this.$http.post('/basic/enterprise/register/valid/name?name=' + this.data.name)
          .then(response => {
            this.validName.isValidName = response.data.success
          })
        this.validName.isValidTypeName = this.data.name !== '' && this.data.name.length >= 2 && this.data.name.length <= 99 && this.commonValid(this.data.name)
        this.validCheck()
      },
      simpleNameCheck: function () {
        this.validSimpleName.init = false
        this.validSimpleName.isValidSimpleName = this.data.simpleName !== '' && this.data.simpleName.length >= 2 && this.data.simpleName.length <= 40 && this.commonValid(this.data.simpleName)
        this.validCheck()
      },
      imgUrlCheck: function () {
        this.validUpload.init = false
        this.validUpload.isValidUpload = this.data.url !== ''
      },
      licenceCheck: function () {
        this.validLicence.init = false
        this.$http.post('/basic/enterprise/register/valid/businessCode?businessCode=' + this.data.licenceId)
          .then(response => {
            this.validLicence.isValidLicence = response.data.success && this.data.licenceId
          })
        this.validCheck()
      },
      addressCheck: function () {
        this.validAddress.init = false
        this.validAddress.isValidAddress = this.data.address !== ''
        this.validCheck()
      },
      websiteCheck: function () {
     // (/^([\w-]+\.)+[\w-]+(/[\w-./?%&=])?$/).test(this.messageBoard.userTel)
      },
      commonValid: function (str) {
        return str.indexOf(' ') === -1
      },
      submitRegisterData: function () {
        let enterprise = {
          enName: this.data.name,
          enShortName: this.data.simpleName,
          enBussinessCode: this.data.licenceId,
          enAddress: this.data.address,
          enUrl: this.data.website
        }
        let data = {}
        data.enterprise = enterprise
        data.isValidRegister = this.isValid
        data.url = this.data.url
        this.$emit('registerAction', data)
      },
      onShowAddress: function () {
        this.showAddressBox = true
        this.isClickInputAddress = true
      },
      onHideAddress: function () {
        if (!this.isInAddressBox && !this.isClickInputAddress) {
          this.showAddressBox = false
        }
        this.isClickInputAddress = false
      },
      getCity: function (province) {
        this.cityData.city = []
        this.address.currentProvince = province
        for (let item in this.temCityData[province]) {
          this.cityData.city.push(item)
        }
      },
      getDistrict: function (city) {
        this.address.currentCity = city
        this.cityData.district = this.temCityData[this.address.currentProvince][city]
      },
      chooseDistrict: function (district) {
        this.address.currentDistrict = district
      },
      submitAddress: function () {
        if (this.address.detail !== '') {
          this.data.address = this.address.currentProvince + this.address.currentCity + this.address.currentDistrict + this.address.detail
          this.showAddressBox = false
          this.addressCheck()
        } else {
          this.$message.error('请输入详细地址')
        }
      }
    }
  }
</script>

<style scoped>
  .register input[type="file"] {
    display: block;
  }
  .previewImg {
    max-height: 200px;
    max-width: 200px;
    margin-top: 5px;
  }
  .x-union-menu {
    width: 600px
  }
  .x-union-header>div{
    background: #f5f8fa;
    font-weight: 700;
    border-bottom: 1px solid #e4ecf3;
  }
  .x-union-header>div,.x-union-list>ul {
    float: left;
    width: 121px;
    border-right: 1px solid #e4ecf3;
  }
  .x-union-list>ul {
    height: 200px;
    margin: 0;
    overflow-y: auto;
  }
  .x-union-menu .x-item-ext {
    float: left;
    width: 235px;
  }
  .x-union-list .x-item-ext {
    padding: 10px
  }
  .x-union-header>div:last-child {
    border-right-width: 0
  }
  .x-union-header>div,.x-union-list>ul>li {
    padding: 2px 10px;
    cursor: pointer;
  }
  .x-union-list>ul>li:hover,.x-union-list>ul>li.active {
    background: #fee9c7;
  }
  .x-input {
    border-color: #ccc;
    border-radius: 0;
    box-shadow: none;
  }
  textarea.form-control {
    height: auto;
  }
  .text-right {
    text-align: right;
  }
  .register-btn {
    padding: 5px 10px;
    font-size: 12px;
    line-height: 1.5;
  }
  .btn-submit {
    background: #5078cb;
    color: #fff;
  }
  .btn-console {
    border: 1px solid #ccc;
    background: #fff;
    color: #888;
    margin-left: 5px;
    transition: all .2s ease-in-out;
  }
  .btn-console:hover {
    border: 1px solid #adadad;
    background: #e6e6e6;
    color: #333;
  }
</style>
