<template>
  <div class="form">
    <div class="form-title">技能培训报名信息填写</div>
    <div class="form-box">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" :disabled="isPay">
        <el-form-item label="真实姓名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio v-for="item in sexList" :label="item.value" :key="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </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="验证码" prop="code" v-if="!isLogin" required>
          <el-input v-model="form.code">
            <template #append>
              <countdown size="small" :disabled="disabledSend" @start="sendCodeRequest" ref="countdown"></countdown>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="学生来源" prop="source">
          <el-radio-group v-model="form.source">
            <el-radio label="院校"></el-radio>
            <el-radio label="企事业单位"></el-radio>
            <el-radio label="社会人员"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属院校" prop="school_name" v-if="form.source === '院校'">
          <el-input v-model="form.school_name"></el-input>
        </el-form-item>
        <el-form-item label="单位名称" prop="department_duty" v-if="form.source === '企事业单位'">
          <el-input v-model="form.department_duty"></el-input>
        </el-form-item>
        <el-form-item label="个人照片" prop="avatar" required>
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="handleUpload"
            accept="image/*">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="form-tips">注：照片需为蓝底免冠一寸照片，jpg格式。</p>
        </el-form-item>
        <el-form-item label="等级" prop="grade" required>
          <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" required>
          <el-input type="textarea" :rows="4" v-model="form.address"></el-input>
          <p class="form-tips">注：请务必确保填写的邮寄地址准确无误，此地址将用于证书的邮寄</p>
        </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="isPay">
            <el-button style="width: 290px" type="primary">已支付</el-button>
          </template>
          <template v-else>
            <el-button style="width: 140px" type="primary" @click="handleSubmit">提 交</el-button>
            <el-button
              plain
              type="primary"
              style="width: 140px; margin-left: 10px"
              @click="payVisible = true"
              v-if="isSubmit"
              >去付款</el-button
            >
          </template>
        </el-form-item>
      </el-form>
    </div>

    <pay-pop
      class="payPop"
      :train="train"
      :form="form"
      @success="getDetail"
      @close="payVisible = false"
      v-if="payVisible" />

    <el-dialog v-if="isPay" :visible.sync="paySuccessDialogVisible" width="600px">
      <el-result icon="success">
        <template slot="extra">
          <p style="margin-bottom: 40px">
            您已缴费成功！待后台审核，为方便您快速开启学习之旅，请加入 QQ 群：1032404918
            。入群后，您将获取专属学习账号，即可按照指引进行课程学习，如有任何疑问，群内工作人员会随时为您答疑解惑，祝您学业有成！
          </p>
          <el-button type="primary" @click="paySuccessDialogVisible = false">确定</el-button>
        </template>
      </el-result>
    </el-dialog>

    <div class="form-card" @click="handleDownload" v-if="form.admission_pic">
      <i class="el-icon el-icon-postcard"></i>
      <p>准考证下载</p>
    </div>
  </div>
</template>
<script>
import * as api from '@/api/article'
import payPop from './components/pay.vue'
import countdown from '@/components/countdown.vue'
import { upload } from '@/utils/upload'
import { saveAs } from 'file-saver'
import datalist from '@/assets/data.js'

import { IDCARD_REG, MOBILE_REG } from '@/utils/validate'

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 {
      isLogin: false,
      isSubmit: false,
      isPay: false,
      payVisible: false,
      paySuccessDialogVisible: true,
      gradList: [
        { label: '初级', value: '初级' },
        { label: '中级', value: '中级' },
        { label: '高级', value: '高级' },
      ],
      sexList: [
        { label: '男', value: '1' },
        { label: '女', value: '2' },
      ],
      form: {
        source: '院校',
        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: '',
        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' },
        ],
      },
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    },
    train() {
      return datalist.find((item) => item.id == this.id) || {}
    },
    disabledSend() {
      return !MOBILE_REG.test(this.form.mobile)
    },
  },
  created() {
    if (!this.id) {
      this.$router.push('/train')
    }
    api.getUser().then((res) => {
      if (res && res.code === 0) {
        this.isLogin = true
        this.getDetail()
      }
    })
  },
  methods: {
    async handleUpload(xhr) {
      const url = await upload(xhr.file)
      this.form.avatar = url
    },
    handleDownload() {
      saveAs(this.form.admission_pic, '准考证')
    },
    // 获取报名信息
    async getDetail() {
      const res = await api.getFormDetail({ periods: this.id })
      const detail = res.data.detail
      this.isSubmit = Object.keys(detail).length > 0
      if (this.isSubmit) {
        this.form = Object.assign(this.form, detail)
        this.isPay = detail.order_status
        this.payVisible = false
      }
    },
    // 提交报名信息
    async handleSubmit() {
      await this.$refs.form.validate()
      if (!this.isLogin) {
        await api.registerAndLogin({
          mobile: this.form.mobile,
          code: this.form.code,
          nickname: this.form.username,
          project_id: 5009,
        })
      }
      await api.submitForm({ ...this.form, periods: this.id })
      this.$message.success('报名信息提交成功')
      this.getDetail()
    },
    // 发送验证码
    sendCodeRequest() {
      api.sendCode({ account: this.form.mobile, service: 'eec.ezijing.com' }).then((res) => {
        if (res.code === 0) {
          this.$message({ message: '验证码发送成功', type: 'success' })
        } else {
          // 停止计时
          this.$refs.countdown.stop()
          this.$message({ message: res.msg || '发送验证码失败', type: 'error' })
        }
      })
    },
  },
}
</script>
<style lang="scss">
.form {
  .form-title {
    text-align: center;
    font-size: 26px;
    // line-height: 30px;
    margin-top: 30px;
    color: #222;
  }

  .form-box {
    padding: 30px 0;
    width: 400px;
    margin: 0 auto;
    .width100 {
      width: 100%;
    }
    .form-tips {
      margin-top: 5px;
      font-size: 13px;
      line-height: 1.4;
      color: #999;
    }
  }

  .payPop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(#000000, 0.5);
    z-index: 99;
  }
  .avatar-uploader {
    line-height: 1;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    background-color: #fff;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: contain;
  }
  .form-card {
    position: fixed;
    top: 40%;
    right: 0;
    background-color: #fff;
    padding: 10px;
    border-radius: 6px;
    text-align: center;
    cursor: pointer;
    .el-icon {
      margin-bottom: 10px;
      font-size: 40px;
    }
  }
}
</style>
