<template>
  <div>
    <!-- <breadcrumb class="content-max-width crumb" :data="crumbData"/> -->
    <div class="title-form">师资培训报名信息填写</div>
    <div class="form-box">
      <el-form ref="form" :model="form" label-width="80px" class="forms">
        <el-form-item label="院校名称" label-width="110px">
          <el-input v-model="form.school_name"></el-input>
        </el-form-item>
        <el-form-item label="院校地址" label-width="110px">
          <el-input v-model="form.school_address"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" id="name" label-width="110px">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" id="sex" label-width="110px">
          <el-select v-model="form.sex" placeholder="请选择" class="width100">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="民族" id="mz" label-width="110px">
          <el-input v-model="form.nation"></el-input>
        </el-form-item>
        <el-form-item label="院系及职务" label-width="110px">
          <el-input v-model="form.department_duty"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" label-width="110px">
          <el-input v-model="form.id_num"></el-input>
        </el-form-item>
        <el-form-item label="常用邮箱" id="mail" label-width="110px">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="单/合住" id="zs" label-width="110px">
          <el-select v-model="form.live_status" placeholder="请选择" class="width100">
            <el-option label="单住" value="1"></el-option>
            <el-option label="合住" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="110px">
          <div class="line">发票信息填写</div>
        </el-form-item>
        <el-form-item label="发票类型" id="fplx" label-width="110px">
          <el-select v-model="form.invoice_type" placeholder="请选择" class="width100">
            <el-option label="增值税普通发票" value="增值税普通发票"></el-option>
            <el-option label="增值税专用发票" value="增值税专用发票"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票抬头" label-width="110px">
          <el-input v-model="form.invoice_title"></el-input>
        </el-form-item>
        <el-form-item label="纳税人识别号" label-width="110px">
          <el-input v-model="form.taxpayer_registration_num"></el-input>
        </el-form-item>
        <el-form-item label="地址电话" label-width="110px">
          <el-input v-model="form.invoice_address_mobile"></el-input>
        </el-form-item>
        <el-form-item label="开户行及账号" id="account" label-width="110px">
          <el-input v-model="form.opening_bank_account"></el-input>
        </el-form-item>
        <el-form-item label="发票内容" id="sh" label-width="110px">
          <el-input v-model="form.invoice_detail" readonly></el-input>
        </el-form-item>
        <el-form-item label="手机号码" label-width="110px">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="验证码" label-width="110px">
          <el-input style="width: 166px" v-model="form.checked_code"></el-input>
          <el-button
            style="border-radius: 3px; width: 118px"
            :disabled="isBtnDisabled"
            @click="getCheckedCode"
            id="checkedCode"
            >获取验证码</el-button
          >
        </el-form-item>
        <!-- <el-form-item label="付款方式" label-width="110px">
          <el-select v-model="form.i9" placeholder="请选择" class="width110">
            <el-option label="微信" value="shanghai"></el-option>
            <el-option label="支付宝" value="beijing"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="身份证号" label-width="110px">
          <el-input v-model="form.i10"></el-input>
        </el-form-item>
        <el-form-item label="地址" label-width="110px">
          <el-input type="textarea" v-model="form.i11"></el-input>
        </el-form-item>
        <el-form-item label="培训需求" label-width="110px">
          <el-input type="textarea" v-model="form.i12"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label-width="110px">
          <el-upload
            class="upload-demo"
            drag
            action="https://jsonplaceholder.typicode.com/posts/"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item> -->
        <el-form-item label-width="110px">
          <el-button style="width: 200px; margin-left: 44px" type="primary" @click="onSubmit">提 交</el-button>
          <!-- <el-button @click="back">返回</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import action from '@action'
import breadcrumb from '@/components/breadcrumb'
const IDCARD_REG = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/
const MOBILE_REG = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
const EMAIL_REG = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
export default {
  components: {
    breadcrumb
  },
  data() {
    return {
      crumbData: [
        {
          path: '/',
          name: '首页'
        },
        {
          name: '师资培训'
        }
      ],
      form: {
        school_name: '',
        school_address: '',
        username: '',
        sex: '',
        nation: '',
        department_duty: '',
        id_num: '',
        email: '',
        live_status: '',
        invoice_type: '',
        invoice_title: '',
        taxpayer_registration_num: '',
        invoice_address_mobile: '',
        opening_bank_account: '',
        invoice_detail: '非学历教育*培训费',
        mobile: '',
        checked_code: ''
      },
      isBtnDisabled: false
    }
  },
  mounted() {
    // $('#name label').html('姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名')
    $('#sex label').html('性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别')
    $('#mz label').html('民&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;族')
    // $('#mail label').html('邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱')
    $('#zs label').html('单&nbsp;/合住')
    // $('#account label').html('账&nbsp;&nbsp;&nbsp;号')
    // $('#sh label').html('税&nbsp;&nbsp;&nbsp;号')
  },
  methods: {
    /* onSubmit() {
      let flag = true
      Object.keys(this.form).map(item => {
        if (item === 'i11' || item === 'i12') {
        } else {
          if (this.form[item] === '') {
            flag = false
          }
        }
      })
      if (!flag) {
        this.$message('请完善信息')
      } else {
        const param = {}
        param.tag = 1
        param.url = ''
        const formData = {}
        Object.keys(this.form).map(name => {
          formData[this.formName[name]] = this.form[name]
        })
        param.table_content = JSON.stringify(formData)
        action.articleAction.formCommit(param).then(res => {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
        })
      }
    }, */
    onSubmit() {
      let flag = true
      // console.log(this.form)
      Object.keys(this.form).map(item => {
        if (this.form[item] === '') {
          flag = false
        }
      })
      if (!flag) {
        this.$message('请完善信息')
      } else if (!MOBILE_REG.test(this.form.mobile)) {
        this.$message('手机号格式错误')
      } else if (!IDCARD_REG.test(this.form.id_num)) {
        this.$message('身份证号格式错误')
      } else if (!EMAIL_REG.test(this.form.email)) {
        this.$message('邮箱格式错误')
      } else {
        /* this.defaultRegister()
        .then((res) => {
          return this.sendEnrollInfo()
        },(error) => {
          let errorMsg = '验证码检测失败'
          if (error && error.code === 3) errorMsg = '真实姓名错误'
          else if (error && error.msg) errorMsg = error.msg
          this.$message.error(errorMsg)
        }).then((res) => {
          if (res === 'enroll success') {
            this.$message.success('报名信息提交成功')
          }
        },(error) => {
          console.log('error2',error)
          let errorMsg = '报名信息提交失败'
          if (error && error.msg) errorMsg = error.msg
          this.$message.error(errorMsg)
        }).finally((data) => {
        }) */
        /* Promise.all([this.defaultRegister(), this.sendEnrollInfo()])
          .then(res => {
            console.log(res)
          })
          .catch(error => {
            console.log(error)
          }) */
        /* Promise.all([this.defaultRegister(), this.sendEnrollInfo()])
          .then(res => {
            console.log(res)
          })
          .catch(err => {
            console.log(err)
          }) */
          let arr = [this.defaultRegister(), this.sendEnrollInfo()];
          Promise.all(arr.map((promise)=>promise.catch((e)=>{
            return e
            })))
          .then(res => {
            let msg = ''
            let registerError = '';
            let enrollError = '';
            res.forEach(item => {
              if (item.type === 'register') {
                if (item.state === 'fail') registerError = item.msg
              } else {
                if (item.state === 'fail') enrollError = item.msg
              }
            })
            console.log(registerError, enrollError)
            if(!registerError && !enrollError) {
              this.$message.success('报名信息提交成功！')
              setTimeout(() => {
                this.$message.success('手机号注册成功！')
              }, 300)
            } else if (registerError && !enrollError) {
              this.$message.success('报名信息提交成功！')
              setTimeout(() => {
                this.$message.error('注册失败，' + registerError)
              }, 300)
            } else {
              this.$message.error(enrollError)
            }
          })
          .catch(err => {
          })
      }
    },
    sendEnrollInfo() {
      let promise = new Promise((resolve, reject) => {
        action.articleAction.formCommit(this.form).then(res => {
          if (res && res.code === 200) {
            resolve({
              type: 'enroll',
              state: 'success',
              msg: '报名信息提交成功'
            })
          } else {
            reject({
              type: 'enroll',
              state: 'fail',
              msg: res.msg || '报名信息提交失败'
            })
          }
        })
      })
      return promise
    },
    getCheckedCode() {
      if (!this.form.mobile) {
        this.$message('请填写手机号')
      } else if (!MOBILE_REG.test(this.form.mobile)) {
        this.$message('手机号格式错误')
      } else {
        let param = {
          account: this.form.mobile,
          service: 'sofia.ezijing.com'
        }
        action.articleAction.sendCheckedCode(param).then(res => {
          if (res && res.code === 0) {
            this.$message({
              message: '验证码发送成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.msg || '发送验证码失败',
              type: 'error'
            })
          }
        })
        this.isBtnDisabled = true
        this.btnDisabledTimer()
      }
    },
    btnDisabledTimer() {
      let count = 60
      let timer = setInterval(() => {
        count--
        if (count < 1) {
          clearInterval(timer)
          this.isBtnDisabled = false
          $('#checkedCode').html('获取验证码')
        } else {
          $('#checkedCode').html(count + '秒后重发')
        }
      }, 1000)
    },
    defaultRegister() {
      let param = {
        account: this.form.mobile,
        code: this.form.checked_code,
        username: this.randomNickname(),
        password: '123456',
        secret: true,
        service: 'sofia.ezijing.com'
      }
      let promise = new Promise((resolve, reject) => {
        action.articleAction.register(param).then(res => {
          if (res && res.code === 0) {
            //code: 0注册成功 5已注册
            resolve({
              type: 'register',
              state: 'success',
              msg: 'success'
            })
          } else if (res && res.code === 5){
            reject({
              type: 'register',
              state: 'fail',
              msg: res.msg || '此手机号已经被注册'
            })
          } else {
            reject({
              type: 'register',
              state: 'fail',
              msg: res.msg || '注册失败'
            })
          }
        })
      })
      /* let promise = new Promise((resolve, reject) => {
        resolve('success')
      }) */
      return promise
    },
    randomNickname() {
      const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
      let str = ''
      for (let i = 0; i < 5; i++) {
        let idx = parseInt(14 * Math.random())
        str += chars[idx]
      }
      const timeStamp = Date.now()
      return str + '_' + timeStamp
    },
    back() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="scss" scoped>
.div-form {
  display: flex;
}
.title-form {
  text-align: center;
  font-size: 26px;
  // line-height: 30px;
  margin-top: 30px;
  color: #222;
}
.line {
  position: absolute;
  top: 0;
  left: 50%;
  width: 1000px;
  transform: translate(-50%, -10px);
  border-top: 1px dashed #ccc;
  line-height: 20px;
  // margin-bottom: 30px;
}
.content-max-width {
  width: 1112px;
  margin: 24px auto 0 auto;
}
.form-box {
  padding: 30px 0;
  width: 400px;
  margin: 0 auto;
  .width100 {
    width: 100%;
  }
}
.reg-form-box {
  width: 380px;
  margin: 0 auto;
  padding: 24px 0;
}
::v-deep {
  .forms {
    i {
      font-size: 20px;
    }
    input {
      border-radius: 4px;
    }
  }
}
</style>
