<template>
  <div>
    <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="真实姓名" id="name" prop="username">
          <el-input v-model="form.username"></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="手机号码" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="form.checked_code">
            <template #append>
              <countdown @start="getCheckedCode"></countdown>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="学生来源" prop="school_name">
          <el-input v-model="form.school_name"></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="grade">
          <el-select v-model="form.grade" class="width100">
            <el-option v-for="item in gradList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证书邮寄地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="是否需要发票" prop="has_invoice">
          <el-radio-group v-model="form.has_invoice">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.has_invoice == 1">
          <el-form-item label="发票类型" prop="invoice_type">
            <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="发票抬头"
            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="纳税人识别号"
            prop="taxpayer_registration_num"
            :rules="{ required: true, message: '请输入纳税人识别号', trigger: 'blur' }">
            <el-input v-model="form.taxpayer_registration_num"></el-input>
          </el-form-item>
          <template v-if="form.invoice_type === '增值税专用发票'">
            <el-form-item
              label="注册地址"
              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"
              prop="opening_bank_account"
              :rules="{ required: true, message: '请输入开户行及账号', trigger: 'blur' }">
              <el-input v-model="form.opening_bank_account"></el-input>
            </el-form-item>
          </template>
          <el-form-item label="发票内容" prop="invoice_detail">
            <el-input v-model="form.invoice_detail"></el-input>
          </el-form-item>
        </template>

        <el-form-item>
          <template v-if="isPayStatus">
            <el-button style="width: 200px" type="primary">已支付</el-button>
          </template>
          <template v-else>
            <el-button style="width: 100px" type="primary" @click="formVerification(onSubmit)">提 交</el-button>
            <el-button style="width: 100px; margin-left: 10px" type="primary" @click="formVerification(goPay)"
              >去付款</el-button
            >
          </template>
        </el-form-item>
      </el-form>
    </div>
    <pay-pop
      v-show="isPayPopShow"
      :train="train"
      :form="form"
      @payStatus="payStatus"
      @closePayPop="closePayPop"
      class="payPop" />
  </div>
</template>
<script>
import * as api from '@/api/article'
import payPop from './components/pay.vue'
import nations from '@/utils/nations'
import countdown from '@/components/countdown.vue'
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}$/

export default {
  components: { payPop, countdown },
  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 {
      isSubmit: false,
      isPayStatus: false,
      nations: nations,
      gradList: [
        { label: '初级', value: '初级' },
        { label: '中级', value: '中级' },
        { label: '高级', value: '高级' },
      ],
      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: '',
        grade: '',
        address: '',
        avatar: '',
        has_invoice: '0',
      },
      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() {
      return this.$route.query.id
    },
    train() {
      return datalist.find((item) => item.id == this.id) || {}
    },
  },
  created() {
    if (!this.id) {
      this.$router.push('/train')
    }
    api.getUser().then((res) => {
      if (res && res.code === 0) {
        window.sessionStorage.userInfo = JSON.stringify(res.data)
        this.isLogin = true
        this.getDetail()
      }
    })
  },
  methods: {
    goPay() {
      this.isPayPopShow = true
    },
    // 获取报名信息
    async getDetail(call) {
      const res = await api.getFormDetail({ periods: this.id })
      this.isSubmit = Object.keys(res.data.detail).length > 0
      this.form = Object.assign(this.form, res.data.detail)
      if (res.data.detail.order_info) {
        this.checkPay(res.data.detail.order_info.pay_order_id, call)
      }
    },
    // 支付
    checkPay(id, call) {
      api.checkPay(id).then((res) => {
        if (res.code === 0) {
          const [order = {}] = res.data
          if (order.status === 1) {
            this.isPayStatus = true
          } else {
            call && call()
          }
        }
      })
    },
    payStatus() {
      this.isPayStatus = true
      this.isPayPopShow = false
    },
    // 关闭支付弹窗
    closePayPop() {
      this.isPayPopShow = false
    },

    formVerification(call) {
      if (this.isLogin) {
        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
        }
      })
    },
    onSubmit() {
      // 登录了直接走报名表单   没有登录走注册登录后再走报名表单
      if (this.isLogin) {
        this.submitForm()
          .then((res) => {
            this.message('提交成功！', 'success', 6000)
            this.getDetail()
            this.updateUser()
            // 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.submitForm()
              .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)
                }
              })
          )
        })
      }
    },
    async submitForm() {
      const res = await api.submitForm({ ...this.form, periods: this.id })
      if (res && res.code === 200) {
        this.$message('报名信息提交成功')
      } else {
        this.$message.error('报名信息提交失败')
      }
    },
    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',
        }
        api.sendCode(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()
      }
    },
    defaultRegister() {
      let param = {
        mobile: this.form.mobile,
        code: this.form.checked_code,
        nickname: this.form.username,
        project_id: 5002,
        // password: '123456',
        // secret: true,
        // service: 'sofia.ezijing.com'
      }
      let promise = new Promise((resolve, reject) => {
        api.registerAndLogin(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 || '注册失败',
            })
          }
        })
      })

      return promise
    },
    message(errMsg, type, dur) {
      this.$message({ message: errMsg, type: type || 'info', duration: dur || 3000 })
    },
    async updateUser() {
      if (!this.form.username) {
        return
      }
      await api.updateUser({ real_name: this.form.username })
    },
  },
}
</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>
