<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" :rules="rules" label-width="110px" class="forms" :disabled="isPayStatus">
        <el-form-item label="院校名称" prop="school_name">
          <el-input v-model="form.school_name"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" id="name" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" id="sex" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="民族" id="mz" prop="nation">
          <el-select v-model="form.nation" placeholder="请选择" class="width100" @change="invoiceTypeChange">
            <el-option :label="item.name" :value="item.id" v-for="item in nations" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="院系及职务">
          <el-input v-model="form.department_duty"></el-input>
        </el-form-item> -->
        <el-form-item label="身份证号" prop="id_num">
          <el-input v-model="form.id_num"></el-input>
        </el-form-item>
        <!-- <el-form-item label="常用邮箱" id="mail">
          <el-input v-model="form.email"></el-input>
        </el-form-item> -->
        <el-form-item label="住宿方式" id="zs" prop="live_status">
          <el-radio-group v-model="form.live_status">
            <el-radio :label="1">单住</el-radio>
            <el-radio :label="2">合住</el-radio>
            <el-radio :label="0">无</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="height: 10px">
          <div class="line">发票信息填写</div>
        </el-form-item>
        <el-form-item label="发票类型" id="fplx" prop="invoice_type">
          <el-select v-model="form.invoice_type" placeholder="请选择" class="width100" @change="invoiceTypeChange">
            <el-option label="无" value="无"></el-option>
            <el-option label="普通发票" value="增值税普通发票"></el-option>
            <el-option label="专用发票" value="增值税专用发票"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="发票抬头"
          v-if="form.invoice_type && form.invoice_type !== '无'"
          prop="invoice_title"
          :rules="{ required: true, message: '请输入发票抬头', trigger: 'blur' }">
          <el-input v-model="form.invoice_title"></el-input>
        </el-form-item>
        <el-form-item
          label="纳税人识别号"
          v-if="form.invoice_type && form.invoice_type !== '无'"
          prop="taxpayer_registration_num"
          :rules="{ required: true, message: '请输入纳税人识别号', trigger: 'blur' }">
          <el-input v-model="form.taxpayer_registration_num"></el-input>
        </el-form-item>
        <el-form-item
          label="注册地址"
          v-if="form.invoice_type === '增值税专用发票'"
          prop="invoice_address_mobile"
          :rules="{ required: true, message: '请输入注册地址', trigger: 'blur' }">
          <el-input v-model="form.invoice_address_mobile"></el-input>
        </el-form-item>
        <el-form-item
          label="开户行及账号"
          id="account"
          v-if="form.invoice_type === '增值税专用发票'"
          prop="opening_bank_account"
          :rules="{ required: true, message: '请输入开户行及账号', trigger: 'blur' }">
          <el-input v-model="form.opening_bank_account"></el-input>
        </el-form-item>
        <el-form-item label="发票内容" id="sh" v-if="form.invoice_type && form.invoice_type !== '无'">
          <el-input v-model="form.invoice_detail" readonly></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="验证码" v-if="!isLogin">
          <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">
          <template v-if="isPayStatus">
            <el-button style="width: 200px; margin-left: 44px" type="primary">已支付</el-button>
          </template>
          <template v-else>
            <template v-if="isLogin">
              <template v-if="isInfoNull">
                <el-button style="width: 200px; margin-left: 44px" type="primary" @click="formVerification(onSubmit)"
                  >提 交</el-button
                >
              </template>
              <template v-else>
                <el-button style="width: 100px" type="primary" @click="formVerification(onSubmit)">提 交</el-button>
                <el-button
                  v-if="!hidePayBtn"
                  style="width: 100px; margin-left: 10px"
                  type="primary"
                  @click="formVerification(goPay)"
                  >去付款</el-button
                >
              </template>
            </template>
            <template v-else>
              <el-button style="width: 200px; margin-left: 44px" type="primary" @click="formVerification(onSubmit)"
                >提 交</el-button
              >
            </template>
          </template>
          <!-- <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>
    <pay-pop
      v-show="isPayPopShow"
      :formData="form"
      :train="train"
      @payStatus="payStatus"
      @closePayPop="closePayPop"
      class="payPop" />
  </div>
</template>
<script>
import action from '@action'
// import { updateUserInfo } from '@/api/common'
import breadcrumb from '@/components/breadcrumb'
import payPop from './components/payPop'
import nations from '@/tool/nations'
import datalist from './data.js'

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,
    payPop,
  },
  data() {
    const IDChecked = (rule, value, callback) => {
      if (value) {
        if (!IDCARD_REG.test(value)) {
          callback(new Error('身份证号格式错误'))
        } else {
          callback()
        }
      }
    }
    const mobileChecked = (rule, value, callback) => {
      if (value) {
        if (!MOBILE_REG.test(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
    }
    return {
      datalist,
      isInfoNull: false,
      isPayStatus: false,
      crumbData: [
        {
          path: '/',
          name: '首页',
        },
        {
          name: '师资培训',
        },
      ],
      nations: nations,
      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: '',
      },
      rules: {
        school_name: { required: true, message: '请输入院校名称', trigger: 'blur' },
        username: { required: true, message: '请输入真实姓名', trigger: 'blur' },
        sex: { required: true, message: '请选择性别', trigger: 'change' },
        nation: { required: true, message: '请输入民族', trigger: 'blur' },
        id_num: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: IDChecked, trigger: 'blur' },
        ],
        live_status: { required: true, message: '请选择居住方式', trigger: 'change' },
        invoice_type: { required: true, message: '请选择发票类型', trigger: 'change' },
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: mobileChecked, trigger: 'blur' },
        ],
      },
      isBtnDisabled: false,
      isPayPopShow: false,
      isLogin: false,
    }
  },
  computed: {
    id() {
      let id
      if (this.$route.query.id) id = parseInt(this.$route.query.id)
      return id
    },
    hidePayBtn() {
      return [6, 202201, 202202, 2022001, 2022002].includes(this.id)
    },
    train() {
      return this.datalist.find((item) => item.id == this.id) || {}
    },
  },
  created() {
    if (!this.id) {
      this.$router.push('/train')
    }
    action.articleAction.getUserInfo().then((res) => {
      if (res && res.code === 0) {
        window.sessionStorage.userInfo = JSON.stringify(res.data)
        this.isLogin = true
        this.getDetail()
      }
    })
  },
  mounted() {
    // document.querySelector('#name label').innerHTML = '姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名'
    // document.querySelector('#sex>label').innerHTML = '性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别'
    // document.querySelector('#mz>label').innerHTML = '民&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;族'
    // document.querySelector('#mail label').innerHTML = '邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱'
    // document.querySelector('#zs>label').innerHTML = '单&nbsp;/合住'
    // document.querySelector('#account label').innerHTML = '账&nbsp;&nbsp;&nbsp;号'
    // document.querySelector('#sh label').innerHTML = '税&nbsp;&nbsp;&nbsp;号'
  },
  methods: {
    goPay() {
      this.isPayPopShow = true
    },
    invoiceTypeChange(val) {
      if (val !== '无') {
        this.form.invoice_detail = '非学历教育*培训费'
      }
    },
    getDetail(call) {
      // 登录状态不需要手机号验证码
      const params = {
        periods: this.id,
      }
      action.articleAction.getFormDetail(params).then((res) => {
        if (res.code === 200) {
          if (!Object.keys(res.data.detail).length) {
            this.isInfoNull = true
          } else {
            this.form = Object.assign(this.form, res.data.detail)
            this.form.sex = this.form.sex && this.form.sex.toString()
            this.form.live_status = this.form.live_status && this.form.live_status.toString()
            if (res.data.detail.order_info) {
              this.checkPay(res.data.detail.order_info.pay_order_id, call)
            }
          }
        }
      })
    },
    // 支付
    checkPay(id, call) {
      action.articleAction.checkPay(id).then((res) => {
        if (res.code === 0) {
          const [order = {}] = res.data
          if (order.status === 1) {
            this.isPayStatus = true
          } else {
            call && call()
          }
        }
        // isCodeShow = true
      })
    },
    payStatus() {
      this.isPayStatus = true
      this.isPayPopShow = false
    },
    // 关闭支付弹窗
    closePayPop() {
      this.isPayPopShow = false
    },
    /* 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'
          })
        })
      }
    }, */
    formVerification(call) {
      if (this.isLogin) {
        // this.form.mobile = '13111111111'
        this.form.checked_code = '1234'
        if (this.form.order_no === '') {
          this.form.order_no = '1'
        }
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          call()
        } else {
          return false
        }
      })
      // let flag = true
      // Object.keys(this.form).map(item => {
      //   if (this.form[item] === '') {
      //     console.log(item)
      //     flag = false
      //   }
      // })
      // console.log(this.form)
      // if (!flag) {
      //   // this.$message('请完善信息')
      //   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 {
      //   call()
      // }
    },
    onSubmit() {
      /* 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
            }
          })
          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 => {
        }) */
      // 登录了直接走报名表单   没有登录走注册登录后再走报名表单
      if (this.isLogin) {
        this.sendEnrollInfo()
          .then((res) => {
            this.isInfoNull = false
            this.getDetail()
            this.message('提交成功！', 'success', 6000)
            this.fetchUpdateUserInfo()
            // setTimeout(() => {
            //   this.message('手机号注册成功！','success', 6000)
            // }, 300)
          })
          .catch((error) => {
            if (error && error.type === 'register') {
              // this.message('报名信息提交成功！','success', 6000)
              // setTimeout(() => {
              //   this.message('注册失败，' + error.msg + '，请重新注册','error', 6000)
              // }, 300)
            } else {
              let errorMsg = error.msg || ''
              this.message('报名信息提交失败！' + errorMsg, 'error', 6000)
            }
          })
      } else {
        this.defaultRegister().then((res) => {
          this.getDetail(
            this.sendEnrollInfo()
              .then((res) => {
                this.message('报名信息提交成功！', 'success', 6000)
                // this.message('报名信息修改成功！','success', 6000)
                // setTimeout(() => {
                //   this.message('手机号注册成功！','success', 6000)
                // }, 300)
                setTimeout(() => {
                  this.$router.go(0)
                }, 1000)
              })
              .catch((error) => {
                if (error && error.type === 'register') {
                  // this.message('报名信息提交成功！','success', 6000)
                  // setTimeout(() => {
                  //   this.message('注册失败，' + error.msg + '，请重新注册','error', 6000)
                  // }, 300)
                } else {
                  let errorMsg = error.msg || ''
                  this.message('报名信息提交失败！' + errorMsg, 'error', 6000)
                }
              })
          )
        })
      }
    },
    sendEnrollInfo() {
      let promise = new Promise((resolve, reject) => {
        const form = { ...this.form }
        form.periods = this.id
        if (form.invoice_type !== '增值税专用发票') {
          form.invoice_address_mobile = ''
          form.opening_bank_account = ''
          if (form.invoice_type === '无') {
            form.invoice_title = ''
            form.taxpayer_registration_num = ''
            form.invoice_detail = ''
          }
        }
        action.articleAction.formCommit(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
          document.querySelector('#checkedCode').innerHTML = '获取验证码'
        } else {
          document.querySelector('#checkedCode').innerHTML = 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 param = {
        mobile: this.form.mobile,
        code: this.form.checked_code,
        nickname: this.form.username || this.randomNickname(),
        project_id: 5002,
        // password: '123456',
        // secret: true,
        // service: 'sofia.ezijing.com'
      }
      let promise = new Promise((resolve, reject) => {
        action.articleAction.register2(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 {
            this.$message.error(res.msg)
            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)
    },
    message(errMsg, type, dur) {
      this.$message({
        message: errMsg,
        type: type || 'info',
        duration: dur || 3000,
      })
    },
    fetchUpdateUserInfo() {
      console.log(1111)
      const params = {
        real_name: this.form.username || '',
      }
      action.articleAction.updateUserInfo(params).then((res) => {
        console.log(res)
      })
    },
  },
}
</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: 10px;
  left: 50%;
  width: 1000px;
  transform: translate(-50%, -10px);
  border-top: 1px dashed #ccc;
  line-height: 30px;
  // 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;
    }
  }
}
.payPop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(#000000, 0.5);
  z-index: 99;
}
</style>
