<template>
  <div class="certification" @click="onHideBox">
    <div class="container">
      <div class="content" v-show="goNextStep">
        <div class="content-top">
          <h3>更换管理员</h3>
        </div>
        <div>
          <el-form :model="changeManager" :rules="rules" ref="changeManager" label-width="100px" class="demo-ruleForm">
            <el-form-item prop="mobile">
              <el-input v-model="changeManager.mobile"
                        placeholder="新管理员手机号"></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input type="text" v-model="changeManager.code"
                        v-bind:class="{active: codeErrorChecked}"
                        auto-complete="off" class="msg"
                        placeholder="短信验证码"></el-input>
              <el-button type="primary" class="code"
                         v-show="sendManagerCode"
                         @click="getCheckCode"
                         :disabled="getCodeBtnIsDisabled">获取验证码</el-button>
              <el-button type="primary"  v-show="!sendManagerCode" class="code code-send">已发送({{account_time}}s)</el-button>
              <span v-show="codeErrorChecked" class="tip codeError-tip" >{{codeErrorMsg}}</span>
            </el-form-item>
            <el-form-item prop="spaceName">
              <el-input type="text"
                        v-model="changeManager.spaceName"
                        v-bind:class="{ active: isSpaceNameExist }"
                        auto-complete="off"
                        placeholder="企业名称"
              ></el-input>
              <span class="tip exist" v-show="isSpaceNameExist">企业不存在，请确认。</span>
            </el-form-item>
            <el-form-item prop="businessCode">
              <el-input type="text" v-model="changeManager.businessCode" auto-complete="off" placeholder="营业执照号"></el-input>
            </el-form-item>
            <el-form-item class="padding55">
              <a class="x-btn-blank" title="上传营业执照扫描件" v-bind:class="{ correct: uploadFileChecked }">
                <i class="fa fa-picture-o"></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="changeManager.businessCodeImage !== ''"><img class="previewImg" alt="" :src="isPdf?'/images/all/timg.png':changeManager.businessCodeImage"></a>
            </el-form-item>
            <el-form-item prop="corporation">
              <el-input v-model="changeManager.corporation" placeholder="法定代表人"></el-input>
            </el-form-item>
            <el-form-item prop="regAddress" class="padding45">
              <input type="text" readonly aria-haspopup="true" aria-expanded="false"
                     @click="onShowAddress"
                     v-model="changeManager.regAddress"
                     v-bind:class="{ correct: addressCheck }"
                     class="form-control"
                     name="name"
                     placeholder="注册地址"/>
              <i class="fa fa-map-marker"></i>
              <div v-show="showAddressBox"
                   @mouseenter="isShowAddressBox = true"
                   @mouseleave="isShowAddressBox = false"
                   style="display: block;" 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.regProvince ? 'active' : ''"
                        v-text="province"
                        @click="getCity(province)"></li>
                  </ul>
                  <ul class="list-unstyled">
                    <li v-for="city in cityData.city"
                        :class="city == address.regCity ? '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.regDistrict ? '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.regStreet" 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>
            </el-form-item>
            <el-form-item prop="description">
              <el-input type="textarea" v-model="changeManager.description" placeholder="申诉说明"></el-input>
              <span class="tip description" v-show="descriptionTip">请描述您申诉的原因，并尽可能多地列举出证明此账号为您所有的证据</span>
            </el-form-item>
            <el-form-item prop="contactName">
              <el-input type="text" v-model="changeManager.contactName" auto-complete="off" placeholder="姓名"></el-input>
            </el-form-item>
            <el-form-item prop="contactTel">
              <el-input type="text" v-model="changeManager.contactTel" auto-complete="off" placeholder="联系电话"></el-input>
            </el-form-item>
            <el-form-item prop="contactEmail">
              <el-input type="text" v-model="changeManager.contactEmail" auto-complete="off" placeholder="电子邮箱"></el-input>
            </el-form-item>
            <el-form-item>
              <a class="btn finish"
                 @click="submit"
                 :disabled="!checked || !mobileChecked || !codeChecked || !spaceNameChecked || !businessCodeChecked || !uploadFileChecked || !addressCheck || !descriptionChecked || !contactNameChecked || !contactTelChecked || !contactEmailChecked">提交</a>
            </el-form-item>
            <el-form-item>
              <el-checkbox name="type" v-model="checked" @click="checkboxChecked"></el-checkbox>
              <span class="agree">我已阅读并同意 <a href="/common/agreement">《优软云服务条款》</a></span>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="content" v-show="!goNextStep">
        <div class="content-top">
          <h3>更换管理员</h3>
        </div>
        <div class="content-bottom">
          <p class="passed"><img src="/images/all/pass.png" alt=""/>申诉已提交</p>
          <span>申诉内容已提交，请耐心等待审核</span>
          <div class="close-btn" @click="goCloudCenter">关闭</div>
        </div>
      </div>
      <loading v-show="isShowLoading"/>
    </div>
  </div>
</template>

<script>
  import Loading from '~components/common/loading/Loading.vue'
  export default {
    name: 'AccountAppeal',
    components: {
      Loading
    },
    data () {
      var validateMobile = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的手机号'))
          this.getCodeBtnIsDisabled = true
          this.mobileChecked = false
        } else {
          if (this.changeManager.mobile !== '') {
            var reg = /^1[0-9]{10}$/
            if (!reg.test(value)) {
              callback(new Error('请填写正确的手机号'))
              this.getCodeBtnIsDisabled = true
              this.mobileChecked = false
            } else {
              this.getCodeBtnIsDisabled = false
              this.mobileChecked = true
            }
          }
          callback()
        }
      }
      var validateCode = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的验证码'))
          this.codeErrorChecked = false
          this.codeChecked = false
        } else {
          if (this.changeManager.code !== '') {
            if (this.changeManager.mobile === '') {
              callback(new Error('请先填写正确的手机号'))
            } else {
              if (this.token) {
                let param = new FormData()
                param.append('mobile', this.changeManager.mobile)
                param.append('code', this.changeManager.code)
                param.append('token', this.token)
                let config = {
                  headers: {'Content-Type': 'multipart/form-data'}
                }
                this.$http.post(`/appeal/check/mobile`, param, config)
                  .then(response => {
                    if (response.data.success) {
                      this.codeChecked = true
                      this.codeErrorChecked = false
                    } else {
                      this.codeErrorChecked = true
                      this.codeChecked = false
                      return Promise.reject(response.data)
                    }
                  }).catch(err => {
                    this.codeErrorMsg = err.errMsg
                  // this.$message.error(err.errMsg)
                  })
              } else {
                callback(new Error('请先获取验证码'))
                this.codeChecked = false
                this.codeErrorChecked = false
              }
            }
          }
          callback()
        }
      }
      var validateSpaceName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的企业名称'))
          this.spaceNameChecked = false
          this.isSpaceNameExist = false
        } else {
          if (this.changeManager.spaceName !== '') {
            if (value.length > 20) {
              callback(new Error('输入长度过长，20个字符以内'))
              this.spaceNameChecked = false
            } else {
              this.$http.get(`/api/userspace/checkSpaceName`, {params: {spaceName: this.changeManager.spaceName}})
                .then(response => {
                  if (response.data.success) {
                    this.spaceNameChecked = false
                    this.isSpaceNameExist = true
                  } else {
                    this.spaceNameChecked = true
                    this.isSpaceNameExist = false
                    return Promise.reject(response.data)
                  }
                }).catch(err => {
                  console.log(err)
                  // this.$message.error(err.errMsg)
                })
            }
          }
          callback()
        }
      }
      var validateBusinessCode = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的营业执照号'))
          this.businessCodeChecked = false
        } else {
          if (this.changeManager.businessCode !== '') {
            let reg = /^[A-Za-z0-9]+$/
            if (reg.test(value)) {
              if (value.length > 20) {
                callback(new Error('输入长度过长，20个字符以内'))
                this.businessCodeChecked = false
              } else {
                this.businessCodeChecked = true
              }
            } else {
              callback(new Error('请填写正确的营业执照号'))
              this.businessCodeChecked = false
            }
          }
          callback()
        }
      }
      var validateCorporation = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的法定代表人'))
          this.corporationChecked = false
        } else {
          if (this.changeManager.corporation !== '') {
            if (value.length > 20) {
              callback(new Error('输入长度过长，20个字符以内'))
            } else {
              this.corporationChecked = true
            }
          }
          callback()
        }
      }
      var validateDescription = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写申诉说明'))
          this.descriptionChecked = false
          this.descriptionTip = false
        } else {
          if (this.changeManager.description !== '') {
            if (value.length >= 100) {
              callback(new Error('输入长度过长，100个字符以内'))
              this.descriptionChecked = false
              this.descriptionTip = false
            } else {
              this.descriptionChecked = true
              this.descriptionTip = false
            }
          }
          callback()
        }
      }
      var validateContactName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写您的姓名'))
          this.contactNameChecked = false
        } else {
          if (this.changeManager.contactName !== '') {
            if (value.length >= 20) {
              callback(new Error('输入长度过长，20个字符以内'))
              this.contactNameChecked = false
            } else {
              this.contactNameChecked = true
            }
          }
          callback()
        }
      }
      var validateContactTel = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的联系电话'))
          this.contactTelChecked = false
        } else {
          if (this.changeManager.contactTel !== '') {
            var reg = /^1[0-9]{10}$/
            if (!reg.test(value)) {
              callback(new Error('请填写正确的联系电话'))
              this.contactTelChecked = false
            } else {
              this.contactTelChecked = true
            }
          }
          callback()
        }
      }
      var validateContactEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的电子邮箱'))
          this.contactEmailChecked = false
        } else {
          if (this.changeManager.contactEmail !== '') {
            var reg = /@/
            if (!reg.test(value)) {
              callback(new Error('请输入正确的邮箱地址格式'))
              this.contactEmailChecked = false
            } else {
              this.contactEmailChecked = true
            }
          }
          callback()
        }
      }
      return {
        goNextStep: true,
        changeManager: {
          mobile: '',
          code: '',
          spaceName: '',
          businessCode: '',
          businessCodeImage: '',
          corporation: '',
          regAddress: '',
          description: '',
          contactName: '',
          contactTel: '',
          contactEmail: ''
        },
        isShowLoading: false,
        codeErrorMsg: '',
        isPdf: false,
        checked: true,
        showAddressBox: false,
        isShowAddressBox: false,
        sendManagerCode: true,
        account_time: 0,
        getCodeBtnIsDisabled: true,
        codeErrorChecked: false,
        descriptionTip: true,
        isSpaceNameExist: false,
        mobileChecked: false,
        codeChecked: false,
        spaceNameChecked: false,
        businessCodeChecked: false,
        uploadFileChecked: false,
        addressCheck: false,
        descriptionChecked: false,
        contactNameChecked: false,
        contactTelChecked: false,
        contactEmailChecked: false,
        allCityData: {},
        cityData: {
          province: [],
          city: [],
          district: []
        },
        address: {
          regProvince: '',
          regCity: '',
          regDistrict: '',
          regStreet: ''
        },
        rules: {
          mobile: [
            {validator: validateMobile, trigger: 'blur'}
          ],
          code: [
            {validator: validateCode, trigger: 'blur'}
          ],
          spaceName: [
            {validator: validateSpaceName, trigger: 'blur'}
          ],
          businessCode: [
            {validator: validateBusinessCode, trigger: 'blur'}
          ],
          corporation: [
            {validator: validateCorporation, trigger: 'blur'}
          ],
          description: [
            {validator: validateDescription, trigger: 'blur'}
          ],
          contactName: [
            {validator: validateContactName, trigger: 'blur'}
          ],
          contactTel: [
            {validator: validateContactTel, trigger: 'blur'}
          ],
          contactEmail: [
            {validator: validateContactEmail, trigger: 'blur'}
          ]
        }
      }
    },
    mounted () {
//      获取城市地址
      this.$http.get('/data/city.json').then(response => {
        this.allCityData = response.data
        for (let province in response.data) {
          this.cityData.province.push(province)
        }
      })
    },
    methods: {
//      判断我同意是否被选中
      checkboxChecked () {
        this.checked = !this.checked
      },
//      获取校验码
      getCheckCode () {
        this.isShowLoading = true
        this.$http.get(`/appeal/check/mobile`, {params: {mobile: this.changeManager.mobile}})
          .then(response => {
            this.isShowLoading = false
            if (response.data.success) {
              this.token = response.data.content.token
              if (this.token !== '') {
                this.$message({
                  message: '验证码已经发送到您的手机，请注意查收',
                  type: 'success'
                })
                this.sendManagerCode = false
                this.account_time = 60
                var accountTime = setInterval(() => {
                  this.account_time--
                  if (this.account_time <= 0) {
                    this.sendManagerCode = true
                    clearInterval(accountTime)
                  }
                }, 1000)
              }
            } else {
              return Promise.reject(response.data)
            }
          }).catch(err => {
            this.isShowLoading = false
            this.$message.error(err.errMsg)
          })
      },
      //      上传营业执照扫描件
      upload (e) {
        this.isShowLoading = true
        let file = e.target.files[0]
        if (file) {
          if (file.size > 5 * 1024 * 1024) {
            this.uploadFileChecked = false
            this.isShowLoading = false
            this.$message.error('文件大小不能超过5M')
          } else {
            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.isShowLoading = false
                if (response.data.success) {
                  let path = response.data.content
                  if (path.slice(path.lastIndexOf('.')).toLowerCase() === '.pdf') {
                    this.isPdf = true
                  } else {
                    this.isPdf = false
                  }
                  this.changeManager.businessCodeImage = response.data.content
                  this.uploadFileChecked = true
                } else {
                  this.uploadFileChecked = false
                  return Promise.reject(response.data)
                }
              }).catch(err => {
                console.log(err)
              // this.$message.error(err.errMsg)
                this.isShowLoading = false
                this.uploadFileChecked = false
              })
          }
        } else {
          this.isShowLoading = false
        }
      },
//      地址选择
      onHideBox: function () {
        this.onHideAddress()
      },
      onHideAddress () {
        if (!this.isShowAddressBox && !this.isClickInputAddress) {
          this.showAddressBox = false
        }
        this.isClickInputAddress = false
      },
      onShowAddress () {
        if (this.showAddressBox) {
          this.onHideAddress()
        } else {
          this.showAddressBox = true
          this.isClickInputAddress = true
        }
      },
      getCity (province) {
        this.cityData.city = []
        this.address.regCity = ''
        this.cityData.district = []
        this.address.regDistrict = ''
        this.address.regProvince = province
        for (let item in this.allCityData[province]) {
          this.cityData.city.push(item)
        }
      },
      getDistrict (city) {
        this.address.regCity = city
        this.address.regDistrict = ''
        this.cityData.district = this.allCityData[this.address.regProvince][city]
      },
      chooseDistrict (district) {
        this.address.regDistrict = district
      },
      submitAddress () {
        if (this.address.regDistrict !== '' && this.address.regCity !== '' && this.address.regProvince !== '') {
          if (this.address.regStreet) {
            let reg = /^(?=.*([\w\u4e00-\u9fa5]+)).*$/
            if (!reg.test(this.address.regStreet)) {
              this.addressCheck = false
              this.$message.error('请输入详细地址')
            } else {
              this.changeManager.regAddress = this.address.regProvince + this.address.regCity + this.address.regDistrict + this.address.regStreet
              this.showAddressBox = false
              this.addressCheck = true
            }
          } else {
            this.$message.error('请输入详细地址')
            this.addressCheck = false
          }
        } else {
          this.$message.error('请输入省、市、区')
          this.addressCheck = false
        }
      },
      //    提交表单
      submit () {
        if (this.mobileChecked && this.codeChecked && this.spaceNameChecked && this.businessCodeChecked && this.uploadFileChecked && this.addressCheck && this.descriptionChecked && this.contactNameChecked && this.contactTelChecked && this.contactEmailChecked && this.checked) {
          this.isShowLoading = true
          let param = new FormData()
          param.append('mobile', this.changeManager.mobile)
          param.append('code', this.changeManager.code)
          param.append('spaceName', this.changeManager.spaceName)
          param.append('businessCode', this.changeManager.businessCode)
          param.append('businessCodeImage', this.changeManager.businessCodeImage)
          param.append('corporation', this.changeManager.corporation)
          param.append('regAddress', this.changeManager.regAddress)
          param.append('regProvince', this.address.regProvince)
          param.append('regCity', this.address.regCity)
          param.append('regDistrict', this.address.regDistrict)
          param.append('regStreet', this.address.regStreet)
          param.append('description', this.changeManager.description)
          param.append('contactName', this.changeManager.contactName)
          param.append('contactTel', this.changeManager.contactTel)
          param.append('contactEmail', this.changeManager.contactEmail)
          param.append('token', this.token)
          param.append('appId', this.$store.state.option.appId)
          let config = {
            headers: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/appeal/changeAdmin', param, config)
            .then(response => {
              this.isShowLoading = false
              if (response.data.success) {
                this.goNextStep = false
              } else {
                this.goNextStep = true
                return Promise.reject(response.data)
              }
            }).catch(err => {
              this.$message.error(err.errMsg)
              this.isShowLoading = false
              // this.codeErrorChecked = true
              // this.codeChecked = false
              this.account_time = 0
            })
        }
      },
//      跳转至个人中心页面
      goCloudCenter () {
        if (this.$route.query.returnURL) {
          window.location.href = decodeURIComponent(this.$route.query.returnURL)
        } else {
          this.$router.push('/cloudcenter')
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .certification {
    margin: 0 auto;
    width: 100%;
    background: #eee;
  .container{
    padding-top: 50px;
    margin: 0 auto;
    width: 980px;
    text-align: center;
  .content{
    padding: 0 50px;
    margin: 50px auto 0;
    width: 100%;
    text-align: center;
    background: #fff;
  .content-top{
    height: 80px;
    line-height: 80px;
  h3{
    margin-bottom: 0;
    font-size: 24px;
    color: #000;
    border-bottom: 1px solid #dcdcdc;
  }
  .step{
    position: relative;
    margin-top: 10px;
  img{
    width: 315px;
    height: 46px;
  }
  .step-item{
    position: absolute;
    top: 45px;
    left: 265px;
  span{
    margin-right: 85px;
    font-size: 14px;
    color: #b4b4b4;
  }
  span.active {
    color: #0076ad;
  }
  }
  }
  }
  form {
    padding-bottom: 44px;
    margin-top: 36px;
  input{
    padding: 0 0 0 18px;
    width: 360px;
    height: 44px;
    line-height: 44px;
    font-size: 14px;
    color: #000;
    border-radius: 0;
  }
  .padding55 input{
    padding-left: 55px;
  }
  .padding45 input{
    padding-left: 45px;
  }
  .pwd {
    margin: 6px 0 -15px 0;
    text-align: left;
    font-size: 13px;
  em{
    display: inline-block;
    margin: 0 8px 2px 0;
    width: 24px;
    height: 6px;
  &:first-child{
     margin-left: 10px;
   }
  }
  span{
    margin-left: 10px;
    font-size: 13px;
  }
  }
  .pwd.sm{
    color: #8c8c8c;
  em {
    background: #bfbfbf;
  &:first-child{
     background: #ff4e00;
   }
  }
  span{
    color: #ff4e00;
  }
  }
  .pwd.md{
    color: #8c8c8c;
  em {
    background: #22ac38;
  &:nth-child(3){
     background: #bfbfbf;
   }
  }
  span{
    color: #22ac38;
  }
  }
  .pwd.lar{
    color: #8c8c8c;
  em {
    background: #00a0e9;
  }
  span{
    color: #00a0e9;
  }
  }
  .pwd.low{
    color: #8c8c8c;
  em{
    background: #bfbfbf;
  }
  }
  span.tip{
    position: absolute;
    top: 0;
    right: -140px;
    font-size: 13px;
    color: #8c8c8c;
  a{
    font-size: 13px;
    color: #0076ad;
  }
  }
  span.tip.tip-mobile{
    top: 3px;
    right: -105px;
    color: #ff4949;
    font-size: 12px;
  }
  span.tip.exist {
    color: #f56c6c;
    font-size: 12px;
  }
  span.tip.description {
    top: 10px;
    right: -266px;
    width: 245px;
    line-height: 18px;
    text-align: left;
  }
  span.tip.codeError-tip {
    position: absolute;
    top: 3px;
    left: 378px;
    width: 200px;
    text-align: left;
    color: #ff4949;
    font-size: 12px;
  }
  i{
    position: absolute;
    top: 13px;
    left: 20px;
    font-size: 20px;
    color: #a0a0a0;
  }
  input[type='checkbox']{
    margin: 0 14px 0 55px;
    float: left;
    width: 16px;
    height: 16px;
  }
  span.agree{
    float: left;
    margin: 1px 0 0 10px;
    font-size: 14px;
    color: #8b8b8b;
  a{
    color: #0076ad;
  }
  }
  .form-group.agree{
    margin: 20px auto 0 !important;
  }
  .btn {
    margin: 34px 0 16px 0;
    width: 360px;
    height: 44px;
    line-height: 44px;
    font-size: 16px;
    color: #fff;
    background: #0076AD;
    border-radius: 3px;
  }
  }
  .content-bottom{
    margin-top: 35px;
    padding-bottom: 50px;
  p{
    font-size: 24px;
    color: #323232;
  img{
    margin-right: 20px;
    width: 30px;
    height: 28px;
  }
  }
  p.pass{
    font-size: 24px;
    color: #e77405;
  img{
    height: 30px;
  }
  }
  p.passed {
    color: #2ab300;
  img{
    height: 30px;
  }
  }
  span{
    display: inline-block;
    margin: 15px 0 140px 0;
    font-size: 14px;
    color: #8b8b8b;
  }
  .close-btn{
    margin: 0 auto;
    width: 200px;
    height: 36px;
    line-height: 36px;
    font-size: 14px;
    text-align: center;
    color: #323232;
    border: 1px solid #d2d2d2;
    border-radius: 3px;
    cursor: pointer ;
  }
  }
  }
  }
  }
</style>
