<template>
  <d2-container class="page">
    <el-tabs value="first">
      <el-tab-pane :label="'报考缴费 (报考准考证号: '+stdReg.ticket_no+')'" name="first">
         <div style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" class="el-alert" style="height: 120px !important;background-color:#fdf6ec;" v-if="year && month">
            <div class="el-alert__content">
              <span class="el-alert__title" v-if="timeControl">{{year}}年{{month}}报考时间：{{timeControl.start_time}} 到 {{timeControl.end_time}}</span>
              <br>
              <span class="el-alert__title" v-if="payControl">{{year}}年{{month}}缴费时间：{{payControl.start_time}} 到 {{payControl.end_time}}</span>
              <br>
              <span class="el-alert__title" v-if="enrolControl" v-html="enrolControl"></span>
              <br>
              <span class="el-alert__title" style="margin-top:10px;"  v-if="isOtherCity"><font color="red">您报考的考区存在跨市报考，请核实确认。</font></span>

              <!--
              <p class="el-alert__description" style="font-size:16px">
                助考班考生请到学校缴费
              </p>
              -->
              <div style="margin-top:10px" v-if="!timeControl || !inTime">
                  <font style="color:red;font-size:16px">暂不允许报考相关操作</font>
                </div>
                <!--
                 <div style="margin-top:10px" v-else>
                  <font style="color:red;font-size:16px">温馨提醒：已经提交缴费，正待后台审核，请不要重复缴费或取消报考。</font>
                </div>
                -->
            </div>
            
          </div>
        </div>
        <el-button type="primary" icon="el-icon-tickets" style="margin-bottom:1px;" @click="goPayUnionBatchForPhoneCode()" title="请勿重复缴费">多报考合并缴费</el-button>

        <el-button type="primary" icon="el-icon-refresh" style="margin-bottom:1px;" @click="refresh()">刷新列表</el-button><br>

        <!-- <el-button type="alert" @click="payOk()">完成支付后请点击确认</el-button> -->
        <el-table
          v-loading="loading"
          ref="dataTable"
          :data="courseList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="30">
          </el-table-column>
          
          <el-table-column
            prop="full_course_name"
            label="课程名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="ticket_no"
            label="准考证号"
            width="120">
          </el-table-column>
          
          <el-table-column
            prop="fee_price"
            label="费用 "
            width="80">
            <template slot-scope="scope">
              <span style="color:red;font-size:16px">
                {{scope.row.fee_price}}元
              </span>
              
            </template>
          </el-table-column>
          <el-table-column
            prop="enrol_type"
            label="报名类别"
            width="80">
            <template slot-scope="scope">
              <template v-if="scope.row.enrol_type=='1'">
                个人
              </template>
              <template v-if="scope.row.enrol_type=='2'">
                集体
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="exam_times"
            label="考试时间"
            width="120">
          </el-table-column>
          <el-table-column
            prop="enrol_place"
            label="考区"
            width="140">
          </el-table-column>
           <el-table-column
            prop="city_name"
            label="考区所属地市"
            width="110">
             <template slot-scope="scope">
              <span v-if="isOtherCity" style="color: red;font-size:16px">{{scope.row.city_name}}</span>		
              <span v-else>{{scope.row.city_name}}</span>	
            </template>
          </el-table-column>

          <el-table-column
            prop="fee_status"
            label="缴费状态 "
            width="80">
            <template slot-scope="scope">
              <template v-if="scope.row.fee_status=='0'">
                <span style="color: red;font-size:16px">待缴费</span>	
              </template>
              <template v-if="scope.row.fee_status=='1'">
                <span style="color: green;font-size:16px">已缴费</span>	
              </template>
              <template v-if="scope.row.fee_status=='2'">
                <span style="color: red;font-size:16px">缴费失败</span>	
              </template>
            </template>
          </el-table-column>
           <el-table-column
            prop="fee_no"
            label="缴费单号 "
            width="180">
          </el-table-column>
          <el-table-column
            prop="calculator"
            label="备注 "
            width="180">
          </el-table-column>
          <el-table-column
                fixed="right"
                label="操作"
                width="130">
          <template slot-scope="scope">
            <span v-if="inTime">
              <div v-if="scope.row.fee_status=='0'" >
                <center>
                  <el-button @click="del(scope.row)" type="warning" size="small" style="margin-bottom:1px;" title="已缴费课程，请勿取消。">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;取消报考&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button><br>
                  <el-button @click="goPayUnionForPhoneCode(scope.row)" type="primary" size="small" style="margin-bottom:1px;" title="请勿重复缴费">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;缴费&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button><br>
                </center>
              </div>
              <div v-if="scope.row.fee_status=='1'" >
                <center>
                <el-button @click="goPayDetail(scope.row)" type="primary" size="small" style="margin-bottom:1px;" plain>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;缴费记录&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                </center>
              </div>
              <div>
                 <center>
                  <el-button @click="goEditCourse(scope.row)" type="success" size="small" style="margin-bottom:1px;">修改课程或考区</el-button>
                 </center>
              </div>
            </span>
            <span v-else-if="payTime">
              <div v-if="scope.row.fee_status=='0'" >
                <center>
                  <el-button @click="goPayUnionForPhoneCode(scope.row)" type="primary" size="small" style="margin-bottom:1px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;缴费&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button><br>
                </center>
              </div>
              
              
            </span>

          </template>
          </el-table-column>
          
        </el-table>

      </el-tab-pane>
    </el-tabs>
    <el-row>
      <center>
        <div style="margin-top:10px">
          <el-button type="primary" @click="goEnrol()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;报考&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
        </div>
      </center>
    </el-row>

     <!-- before-close="alertPaycheck()" -->
    <el-dialog width="500px" id="paymodal" title="缴费" :visible.sync="payDialogVisible" :show-close="false" :close-on-click-modal="false">
     <table style="padding-top:0px;margin:0px auto;">
       
       <tr>
         <td align="right">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</td>
        <td>{{stdName}}</td>
         <td align="right">准考证号:</td>
        <td>{{ticketNo}}</td>
        
        
      </tr>

       <tr>
         <td>支付金额:</td>
        <td>RMB <font style="color:green;font-weight: bold;font-size:20px">{{fee}}</font> 元&nbsp;&nbsp;</td>
      
         <td align="right">订单编号:</td>
         <td>{{orderNum}}</td>
          </tr>
     
     </table>
     <div style="margin:5px">
      <center>
        手机<font style="color:green;font-weight: bold;font-size:16px">微信</font>或<font style="color:green;font-weight: bold;font-size:16px">支付宝</font>扫码支付<br>
          <canvas id="canvasQrcode" style="width:300px;height:300px"></canvas><br>
          <el-button type="primary" size="mini" @click="payOk()">完成支付后请点击确认</el-button>
      </center>
     </div>
     <font color="red">请勿重复缴费(已缴费但订单待缴费或异常时,请勿重复缴费)</font><br>
     <font color="red">由于对帐流程需要,您的缴费可能会在24小时后确认！</font><br>
     如果没有微信或支付宝,可以点击【网银支付】使用网银缴费(需在银行柜台开通银联网银，并使用IE浏览器访问广西自考网上系统)<br>
    因近期银联支付较为繁忙，如遇支付失败，请使用微信或支付宝扫码支付。技术支持电话:0771-5337940。
  <!--
     如在支付过程中有疑问，可拨打银联商务咨询电话：95534。
    ，如已扣款请24小时后再登录查询 -->

     <div style="margin:5px">
       <center>
         <el-button type="primary" size="mini" v-if="map" @click="goWyPay()">网银支付</el-button>
         <el-button type="primary" size="mini" @click="closePayWin()">关闭窗口</el-button>
       </center>
     </div>
    </el-dialog>

    <el-dialog width="500px" id="paymodal" title="短信验证" :visible.sync="payNeedPhoneCodeDialogVisible" :show-close="false" :close-on-click-modal="false">
     <table style="padding-top:0px;margin:0px auto;">
       
       <tr>
         <td align="right" style="padding-bottom:10px;">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</td>
        <td style="padding-bottom:10px;">{{stdName}}</td>
         <td align="right" style="padding-bottom:10px;">准考证号:</td>
        <td style="padding-bottom:10px;">{{ticketNo}}</td>
        
        
      </tr>

       <tr>
         <td style="padding-bottom:10px;">绑定手机号码:</td>
        <td style="padding-bottom:10px;">{{bindphone}}</td>
      
         <td align="right" style="padding-bottom:10px;"></td>
         <td style="padding-bottom:10px;">

         </td>
          </tr>

          <tr>
         <td align="right">验证码:</td>
         <td colspan="3">
           <el-input type="text" v-model="code" maxlength="6" placeholder="请填写短信验证码"></el-input>

         </td>
          </tr>

  
          <tr>
         <td colspan="4" align="center">
           <el-button type="primary" :disabled="secCountDown>0" @click="sendSms">{{secCountDownInfo}}</el-button>
           <el-button @click="goPayUnion(stdEnrol)" type="primary"  title="请勿重复缴费">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;缴费&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
           <el-button type="primary" @click="payNeedPhoneCodeDialogVisible = false">关闭窗口</el-button>

           </td>

          </tr>
     
     </table>
  
    </el-dialog>

    <el-dialog width="500px" id="paymodal" title="短信验证" :visible.sync="payBatchNeedPhoneCodeDialogVisible" :show-close="false" :close-on-click-modal="false">
     <table style="padding-top:0px;margin:0px auto;">
       
       <tr>
         <td align="right" style="padding-bottom:10px;">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</td>
        <td style="padding-bottom:10px;">{{stdName}}</td>
         <td align="right" style="padding-bottom:10px;">准考证号:</td>
        <td style="padding-bottom:10px;">{{ticketNo}}</td>
        
        
      </tr>

       <tr>
         <td style="padding-bottom:10px;">绑定手机号码:</td>
        <td style="padding-bottom:10px;">{{bindphone}}</td>
      
         <td align="right" style="padding-bottom:10px;"></td>
         <td style="padding-bottom:10px;">

         </td>
          </tr>

          <tr>
         <td align="right">验证码:</td>
         <td colspan="3">
           <el-input type="text" v-model="code" maxlength="6" placeholder="请填写短信验证码"></el-input>

         </td>
          </tr>

  
          <tr>
         <td colspan="4" align="center">
           <el-button type="primary" :disabled="secCountDown>0" @click="sendSms">{{secCountDownInfo}}</el-button>
           <el-button @click="goPayUnionBatch()" type="primary"  title="请勿重复缴费">多报考合并缴费</el-button>
           <el-button type="primary" @click="payBatchNeedPhoneCodeDialogVisible = false">关闭窗口</el-button>

           </td>

          </tr>
     
     </table>
  
    </el-dialog>

  <el-dialog title="缴费记录" width="1000px" :visible.sync="payListDialogVisible">
     <el-table
          :data="payList"
          style="width: 100%">
           <el-table-column
            prop="bill_no"
            label="订单号"
            width="240">
          </el-table-column>
          <el-table-column
            prop="bill_amount"
            label="缴费金额"
            width="100">
          </el-table-column>
          <el-table-column
            prop="bill_status"
            label="缴费状态"
             width="140">
          </el-table-column>
          <el-table-column
            prop="remark"
            label="说明"
             width="140">
          </el-table-column>
          <el-table-column
            prop="bill_time"
            label="订单生成时间"
             width="160">
          </el-table-column>
          <el-table-column
            prop="reply_time"
            label="支付成功时间"
            width="160">
          </el-table-column>
     </el-table>
    </el-dialog>
    <el-dialog title="修改报考课程" width="1300px" :visible.sync="editCourseDialogVisible">
        <div v-if="stdReg && stdMajor" style="margin: 0px 10px;font-size:  16px;">
          <table v-if="selectedEditItem" style="margin-left:120px" width="750px">
            <tr style="height:35px">
              <td width="120px" align="right">报考准考证号:</td>
              <td width="240px">{{stdReg.ticket_no}}</td>
              <td width="120px" align="right">专业:</td>
              <td>{{stdMajor.major_name}} - {{stdMajor.major_level_name}}</td>
           
            </tr>
 
            <tr style="height:35px">
              <td align="right">原课程:</td>
              <td>{{selectedEditItem.course_code}} - {{selectedEditItem.course_name}}</td>
              <td align="right">考试批次:</td>
              <td>{{selectedEditItem.exam_times}}</td>
            </tr>
            <tr style="height:35px">
              <td align="right">考区:</td>
              <td>{{selectedEditItem.enrol_place}}({{selectedEditItem.city_name}})</td>
              <td align="right">费用:</td>
              <td>{{selectedEditItem.fee_price}}</td>
            </tr>
          </table>

          <!-- <el-form label-position="right" label-width="80px" v-if="selectedEditItem">
            <el-form-item label="报考准考证号">
               {{stdReg.ticket_no}}
            </el-form-item>
            <el-form-item label="专业">
               {{stdMajor.major_name}} - {{stdMajor.major_level_name}}
            </el-form-item>
            <el-form-item label="原课程">
               {{selectedEditItem.course_code}} - {{selectedEditItem.course_name}}
            </el-form-item>
            <el-form-item label="考试时间">
               {{selectedEditItem.exam_date}}
            </el-form-item>
            <el-form-item label="考区">
               {{selectedEditItem.enrol_place}}
            </el-form-item>
    
          </el-form> -->

        </div>
        <h3 style="margin-bottom:5px;padding-bottom:0px;border-bottom: 2px solid #0090ff;"></h3>
        <el-tabs tab-position="left" style="height: 250px;" v-if="timeControl" :value="majorTab">
          <el-tab-pane label="本专业课程" style="padding: 10px 10px" name="major">
            <div v-for="(item,index ) in majorCouse" :key="index" class="text item" style="margin-bottom: 5px;">
              <!-- v-if="showIndex==index" -->
              <div >
              {{item.key}}： <el-select size="medium" v-model="selectedMajorCourse.id[index]" @change="courseChange('selectedMajorCourse',index,selectedMajorCourse.id[index])" clearable filterable placeholder="请选择课程">
                              <el-option
                                v-for="opt in item.data"
                                :key="'majorCouse_'+item.key+opt.id"
                                :label="opt.course_code + '-' +opt.course_name"
                                :value="opt.id">
                              </el-option>
                            </el-select>
                            &nbsp;--&nbsp;
                            <el-select size="medium" v-model="selectedMajorCourse.examAreaId[index]" clearable filterable placeholder="请选择考区">
                              <el-option
                                v-for="opt in selectedMajorCourse[`examAreaArray${index+1}`]"
                                :key="'majorCouse_examAreaArray'+item.key+opt.org_id+index"
                                :label="opt.org_code+'-'+opt.org_name+'('+opt.city_name+')'"
                                :value="opt.org_id">
                              </el-option>
                            </el-select>
                             &nbsp;<span style="font-size: 12px;" v-html="selectedMajorCourse.calculator[index]"></span>

                </div>
            </div>

          </el-tab-pane>
          <el-tab-pane label="其他专业课程" style="padding: 10px 10px" name="nMajor">
            <div v-for="(item,index ) in otherCouse" :key="index" class="text item" style="margin-bottom: 5px;">
               <!-- v-if="showIndex==index" -->
              <div>
              {{item.key}}： <el-select size="medium" v-model="selectedOtherCourse.id[index]" @change="courseChange('selectedOtherCourse',index,selectedOtherCourse.id[index])" clearable filterable placeholder="请选择课程">
                              <el-option
                                v-for="opt in item.data"
                                :key="'otherCouse_'+item.key+opt.id"
                                :label="opt.course_code + '-' +opt.course_name"
                                :value="opt.id">
                              </el-option>
                            </el-select>
                            &nbsp;--&nbsp;
                            <el-select size="medium" v-model="selectedOtherCourse.examAreaId[index]" clearable filterable placeholder="请选择考区">
                              <el-option
                                v-for="opt in selectedOtherCourse[`examAreaArray${index+1}`]"
                                :key="'otherCouse_examAreaArray'+item.key+opt.org_id+index"
                                :label="opt.org_code+'-'+opt.org_name+'('+opt.city_name+')'"
                                :value="opt.org_id">
                              </el-option>
                            </el-select>
                            &nbsp;<span style="font-size: 12px;" v-html="selectedOtherCourse.calculator[index]"></span>

              </div>
            </div>

          </el-tab-pane>

          <el-tab-pane label="选考课程" style="padding: 10px 10px" name="sMajor">
            <div v-for="(item,index ) in selectedCouse" :key="index" class="text item" style="margin-bottom: 5px;">
               <!-- v-if="showIndex==index" -->
              <div>
              {{item.key}}： <el-select size="medium" v-model="selectedSelectedCourse.id[index]" @change="courseChange('selectedSelectedCourse',index,selectedSelectedCourse.id[index])" clearable filterable placeholder="请选择课程">
                              <el-option
                                v-for="opt in item.data"
                                :key="'selectedCouse_'+item.key+opt.id"
                                :label="opt.course_code + '-' +opt.course_name"
                                :value="opt.id">
                              </el-option>
                            </el-select>
                            &nbsp;--&nbsp;
                            <el-select size="medium" v-model="selectedSelectedCourse.examAreaId[index]" clearable filterable placeholder="请选择考区">
                              <el-option
                                v-for="opt in selectedSelectedCourse[`examAreaArray${index+1}`]"
                                :key="'selectedCouse_examAreaArray'+item.key+opt.org_id+index"
                                :label="opt.org_code+'-'+opt.org_name+'('+opt.city_name+')'"
                                :value="opt.org_id">
                              </el-option>
                            </el-select>
                            &nbsp;<span style="font-size: 12px;" v-html="selectedSelectedCourse.calculator[index]"></span>

              </div>
            </div>
            <div style="margin: 20px 10px;font-size:  16px;">
              公告：<a style="color:blue;font-size: 16px;" href="https://www.gxeea.cn/view/content_1148_15806.htm" target="_new">我区高等教育自学考试英语和数学等课程由必考课改为选考课</a>

            </div>
      
          </el-tab-pane>
        </el-tabs>
         <el-row>
      <center>
        <div style="margin-top:10px" v-if="timeControl">
          <el-button type="primary" @click="saveEnrol()">提交报考课程</el-button>
          <el-button type="primary" @click="editCourseDialogVisible = false">关闭窗口</el-button>

        </div>
      </center>
    </el-row>
    </el-dialog>
    <!-- style="display:none" -->
    <div style="display:none">
      <form id="ylForm" action="" method="post" target="_blank" v-if="map">
        <input type="text" name="orderNum" :value="map.orderNum"><br>
        <input type="text" name="orderAmount" :value="map.orderAmount"><br>
        <input type="text" name="orderDesc" :value="map.orderDesc"><br>
        <input type="text" name="systemName" :value="map.systemName"><br>
	      <input type="text" name="notifyUrl" :value="map.notifyUrl"><br>
	      <input type="text" name="frontNotifyUrl" :value="map.frontNotifyUrl"><br>
		    <input type="text" name="expireTime" :value="map.expireTime"><br>
	      <input type="text" name="sign" :value="map.sign"><br>

        <input type="submit" id="ylFormSubBtn">
      </form>
    </div>
    

  </d2-container>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { log } from "util";
import QRCode from "qrcode";
import { setInterval } from 'timers';

export default {
  components: {},
  computed: {
    ...mapState({
      stdReg: state => state.enrol.StdReg,
      stdMajor: state => state.enrol.StdMajor,
    })
  },
  data() {
    return {
      majorTab:"",
      loading: false,
      curStep: "list",
      year: null,
      month: null,
      timeControl: {},
      payControl: {},
      inTime:false,
      payTime:false,
      courseList: [],
      payChannel: null,
      payDialogVisible: false,
      payNeedPhoneCodeDialogVisible: false,
      payBatchNeedPhoneCodeDialogVisible: false,
      enrolControl: null,
      ticketNo: "",
      stdName: "",
      fee: "",
      orderNum: "",
      payList: null,
      payListDialogVisible: false,
      map: null,
      editCourseDialogVisible: false,
      selectedEditItem: null,
      payConfirm: false,
      isOtherCity: false,
      selectedMajorCourse:{
        id:[],
        calculator: [],
        examAreaId:[],
        // examAreaArray:[[],[],[],[]]
        examAreaArray1:[],
        examAreaArray2:[],
        examAreaArray3:[],
        examAreaArray4:[],
        examAreaArray5:[],
        examAreaArray6:[]
      },
      selectedOtherCourse:{
        id:[],
        calculator: [],
        examAreaId:[],
        // examAreaArray:[[],[],[],[]]
        examAreaArray1:[],
        examAreaArray2:[],
        examAreaArray3:[],
        examAreaArray4:[],
        examAreaArray5:[],
        examAreaArray6:[]
      },
      selectedSelectedCourse:{
        id:[],
        calculator: [],
        examAreaId:[],
        // examAreaArray:[[],[],[],[]]
        examAreaArray1:[],
        examAreaArray2:[],
        examAreaArray3:[],
        examAreaArray4:[],
        examAreaArray5:[],
        examAreaArray6:[]
      },
      majorCouse:[],
      otherCouse:[],
      selectedCouse:[],
      edit_examDate: null,
      edit_enrolArea: null,
      multipleSelection: [],
      showIndex:0,
      willRollFetchPayStatus:false,
      secCountDown: 0,
      secCountDownInfo:"获取验证码",
      code:"",
      bindphone:"",
      payNeedPhoneCode:"",
      stdEnrol:{}
    };
  },
  async mounted() {
    this.init();
  },
  methods: {
   async closePayWin(){
      let res = await this.$http.post("/std/stdEnrol/payUnion/checkOrderIsSuccess.htm",
      this.Qs.stringify({
          orderNum:this.orderNum,
          // orderNum:"1564826664874"
        }));
      this.init();
      this.payDialogVisible=false;
    },
    async refresh(){
      this.$nextTick(() => {
        this.init();
     })
    },
    async init() {
      this.loading = true;
      this.courseList = [];
      let res = await this.$http.post("/std/stdEnrol/list.htm");
      this.timeControl = res.data.map.timeControl;
      this.payControl = res.data.map.payControl;
      this.courseList = res.data.map.courseList;
      this.inTime = res.data.map.inTime;
      this.payTime = res.data.map.payTime;
      this.month = res.data.map.month;
      this.year = res.data.map.year;
      this.isOtherCity = res.data.map.isOtherCity;
      this.enrolControl = res.data.map.enrolControl;
      // for (let i = 0; i < this.courseList.length; i++) {
      //   const item = this.courseList[i];
      //   //存在没有缴费的 开启轮询
      //   if(item.fee_status == '0'){
      //     this.willRollFetchPayStatus = true;
      //     break;
      //   }
        
      // }


      // let listres = await this.$http.post("/std/stdEnrol/list.htm");
      // this.timeControl = listres.data.map.timeControl;
      // this.inTime = listres.data.map.inTime;
      // this.month = listres.data.map.month;
      // this.year = listres.data.map.year;

      this.loading = false;
      // await this.initIntervalNoLoading();
    },
    //轮询查询报考数据 更新支付状态
    async initIntervalNoLoading(){
       setInterval(async ()=>{
        if(this.willRollFetchPayStatus == true){
          let res = await this.$http.post("/std/stdEnrol/list.htm");
          this.courseList = [];
          this.courseList = res.data.map.courseList;
          let isAllPay = true;
          for (let i = 0; i < this.courseList.length; i++) {
            const item = this.courseList[i];
            if(item.fee_status == '0'){
              isAllPay = false;
            }
            
          }
          //全部缴费无需轮询
          if(isAllPay == true){ this.willRollFetchPayStatus = false;}
        }
       },2000)
    },

    goEnrol() {
      this.goUrl("/enrol");
    },
    // alertPaycheck(done){
    //   
    //   if(!this.payConfirm){
    //     this.alert("如果已支付,请点击二维码下方按钮,未支付忽略此提示!")
    //   }
    //   return true;
    // },
    async del(item) {
      if (item.fee_status != 0) {
        this.alert("只能删除未缴费课程报考", "信息提示");
        return;
      }

      let res1 = await this.$http.post("/std/stdEnrol/payUnion/checkOrderIsSuccessForDel.htm",
        this.Qs.stringify({
            business_id:item.id
          }));
      if(res1.data.success){
       // 报考课程已缴费，或者查询订单状态异常，不允许删除。
       this.alert(res1.data.errorMsg);
       this.init();
       return;
      }else{
        // 报考课程没有生成订单、或者未缴费，允许删除。
        
      }

      this.$confirm("确定取消报考?(如果已经支付,请不要取消)", "信息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let { data } = await this.$http.post(
            "/std/stdEnrol/delete.htm",
            this.Qs.stringify({ ids: item.id })
          );
          if (data.success) {
            this.alert("删除成功", "信息提示");
          }else{
            this.alert(data.errorMsg, "信息提示");
          }
          this.init();
        })
        .catch(() => {});
    },

    //统一支付平台调用接口
    async goPayUnion(item) {

       if (this.payNeedPhoneCode == 'true' && !this.code) {
          this.alert("请填写验证码!");
          return;
        }

      this.loading = true;
      //刷新支付状态

      let { data } = await this.$http.post(
        "/std/stdEnrol/payUnion/makePayBill.htm",
        this.Qs.stringify({ id: item.id,std_id:this.stdReg.id,code:this.code })
      );
      if (data.success) {
        if (data.entity.statusCode != 200) {
          this.alert("请求支付平台接口异常!");
          return;
        }
        let respJson = JSON.parse(data.entity.response);
        this.orderNum = respJson.orderNum;
        this.fee = respJson.orderAmount/100;
        this.ticketNo = data.entity.map.ticketNo;
        this.stdName = data.entity.map.stdName;
        this.map = data.entity.map;
        this.payNeedPhoneCodeDialogVisible = false;
        this.payDialogVisible = true;
        this.$nextTick(() => {
          let canvasQrcode = document.getElementById("canvasQrcode");
          this.loading = false;
          QRCode.toCanvas(canvasQrcode, respJson.qrCodeUrl, function(error) {
            console.log("QRCode success");
          });
        });
      } else {
        this.loading = false;
        this.alert(data.errorMsg);
      }
    },

    async goPayUnionForPhoneCode(item) {
      
      let _this = this;
      
      this.loading = true;
      //刷新支付状态

      let { data } = await this.$http.post(
        "/std/stdEnrol/payUnion/makePayBillForPhoneCode.htm",
        this.Qs.stringify({std_id:this.stdReg.id })
      );
      if (data.success) {
        
        _this.ticketNo = data.entity.ticketNo;
        _this.stdName = data.entity.stdName;
        _this.bindphone = data.entity.bindphone;
        _this.payNeedPhoneCode = data.entity.payNeedPhoneCode;

        if(_this.payNeedPhoneCode == 'true'){
            _this.stdEnrol = item;
           _this.payNeedPhoneCodeDialogVisible = true;
        }else{
          _this.goPayUnion(item);
        }

       
        _this.loading = false;
      } else {
        _this.loading = false;
        _this.alert(data.errorMsg);
      }
    },

    handleSelectionChange(val){
      this.multipleSelection = val;
      
    },


async goPayUnionBatchForPhoneCode() {
      
      let _this = this;
      
      this.loading = true;
      //刷新支付状态

      let { data } = await this.$http.post(
        "/std/stdEnrol/payUnion/makePayBillForPhoneCode.htm",
        this.Qs.stringify({std_id:this.stdReg.id })
      );
      if (data.success) {
        
        _this.ticketNo = data.entity.ticketNo;
        _this.stdName = data.entity.stdName;
        _this.bindphone = data.entity.bindphone;
        _this.payNeedPhoneCode = data.entity.payNeedPhoneCode;

        if(_this.payNeedPhoneCode == 'true'){
           _this.payBatchNeedPhoneCodeDialogVisible = true;
        }else{
          _this.goPayUnionBatch();
        }

       
        _this.loading = false;
      } else {
        _this.loading = false;
        _this.alert(data.errorMsg);
      }
    },
    //批量付费
    async goPayUnionBatch() {
       if (this.payNeedPhoneCode == 'true' && !this.code) {
          this.alert("请填写验证码!");
          return;
        }

      //自动选中未付费
      _.forEach(this.courseList,(row)=>{
        
        if(row.fee_status == 0){
          this.$refs.dataTable.toggleRowSelection(row,true);
        }
      })


      //多选报考项目
      let idArray = [];
      let existPayed = false;
      if(this.multipleSelection.length < 1){
        this.alert("请选择一个以上报考项");
        return;
      }


      this.multipleSelection.forEach((item)=>{
        //验证所选是否状态都为未缴费
        if(item.fee_status != 0){
          existPayed = true;
        }
        idArray.push(item.id);
      });

      if(existPayed == true){
        this.loading = false;
        this.alert("请选择未缴费报考!");
        return;
      }
      this.loading = true;
      let ids = idArray.join();
      let { data } = await this.$http.post(
        "/std/stdEnrol/payUnion/makePayBillBatch.htm",
        this.Qs.stringify({ ids: ids ,std_id:this.stdReg.id})
      );
      if (data.success) {
        if (data.entity.statusCode != 200) {
          this.alert("请求支付平台接口异常!");
          return;
        }
        let respJson = JSON.parse(data.entity.response);
        this.orderNum = respJson.orderNum;
        this.fee = respJson.orderAmount/100;
        this.ticketNo = data.entity.map.ticketNo;
        this.stdName = data.entity.map.stdName;
        this.map = data.entity.map;
        this.payBatchNeedPhoneCodeDialogVisible = false;
        this.payDialogVisible = true;
        this.$nextTick(() => {
          let canvasQrcode = document.getElementById("canvasQrcode");
          this.loading = false;
          QRCode.toCanvas(canvasQrcode, respJson.qrCodeUrl, function(error) {
            console.log("QRCode success");
          });
        });
      } else {
        this.loading = false;
        this.alert(data.errorMsg);
      }
    },


    async goEditCourse(row) {
      if(!this.inTime){
        this.alert("不在课程报考时间允许范围内无法变更!");
        return;
      }
      let loading =  this.showLoading("初始化数据加载中...");
      this.selectedEditItem = row;
      let res = await this.$http.post("/std/stdEnrol/detail.htm");
      this.majorCouse = this.transData(res.data.map.majorCouse);
      this.otherCouse = this.transData(res.data.map.otherCouse);
      this.selectedCouse = this.transData(res.data.map.selectedCouse);

      
      let editRes = await this.$http.post("/std/stdEnrol/editDetail.htm", 
        this.Qs.stringify({
          course_id: row.course_id
        })
      )
      this.edit_examDate = editRes.data.map.examDate;
      this.edit_enrolArea = editRes.data.map.enrolArea;
      this.edit_courseInfo = editRes.data.map.courseInfo;
      let majorFlag =  editRes.data.map.majorFlag;
      // this.hideLoading(loading);
      this.editCourseDialogVisible = true;

      setTimeout(() => {
        this.selectedMajorCourse={
          id:[],
          calculator: [],
          examAreaId:[],
          examAreaArray1:[],
          examAreaArray2:[],
          examAreaArray3:[],
          examAreaArray4:[],
          examAreaArray5:[],
          examAreaArray6:[]
        };

        this.selectedOtherCourse={
          id:[],
          calculator: [],
          examAreaId:[],
          examAreaArray1:[],
          examAreaArray2:[],
          examAreaArray3:[],
          examAreaArray4:[],
          examAreaArray5:[],
          examAreaArray6:[]
        },

        this.selectedSelectedCourse={
          id:[],
          calculator: [],
          examAreaId:[],
          examAreaArray1:[],
          examAreaArray2:[],
          examAreaArray3:[],
          examAreaArray4:[],
          examAreaArray5:[],
          examAreaArray6:[]
        },
        

        this.initEditData(majorFlag,res.data.map.majorCouse , res.data.map.otherCouse, res.data.map.selectedCouse);
      }, 50);

    },

    //初始化修改回显
    async initEditData(majorFlag,majorCouse,otherCouse,selectedCouse){
        //this.majorTab = majorFlag==1?"major":"nMajor";

        if(majorFlag==1){
            this.majorTab='major';
          }else if(majorFlag==2){
            this.majorTab='sMajor';
          }else{
            this.majorTab='nMajor';
          }
        //专业课程
        if(majorFlag == 1){

          let index = 0;
          for (const key in majorCouse) {
            
            if (majorCouse.hasOwnProperty(key) && key == this.edit_examDate) {
              this.$set(this.selectedMajorCourse.id,index,this.edit_courseInfo.id);
              await this.courseChange("selectedMajorCourse",index,this.edit_courseInfo.id);
              this.$set(this.selectedMajorCourse.examAreaId,index,this.edit_enrolArea);
              this.showIndex = index;
            }else{
              this.$set(this.selectedMajorCourse.id,index,"");
              this.$set(this.selectedMajorCourse.examAreaId,index,"");
            }
            index++;
          }
        }else if(majorFlag == 2){
          // 选考课程
          let index = 0;
          for (const key in selectedCouse) {
            if (majorCouse.hasOwnProperty(key) && key == this.edit_examDate) {
              this.$set(this.selectedSelectedCourse.id,index,this.edit_courseInfo.id);
              await this.courseChange("selectedSelectedCourse",index,this.edit_courseInfo.id);
              this.$set(this.selectedSelectedCourse.examAreaId,index,this.edit_enrolArea);
           
            }
            else{
              this.$set(this.selectedSelectedCourse.id,index,"");
              this.$set(this.selectedSelectedCourse.examAreaId,index,"");
            }
            index++;
          }
        }
        //非专业
        else{
          let index = 0;
          for (const key in otherCouse) {
            if (majorCouse.hasOwnProperty(key) && key == this.edit_examDate) {
              this.$set(this.selectedOtherCourse.id,index,this.edit_courseInfo.id);
              await this.courseChange("selectedOtherCourse",index,this.edit_courseInfo.id);
              this.$set(this.selectedOtherCourse.examAreaId,index,this.edit_enrolArea);
           
            }
            else{
              this.$set(this.selectedOtherCourse.id,index,"");
              this.$set(this.selectedOtherCourse.examAreaId,index,"");
            }
            index++;
          }
        }
    },
    transData(mapData){
      let array = [];
      for (const key in mapData) {
        if (mapData.hasOwnProperty(key)) {
          const data = mapData[key];
          array.push({
            key:key,
            data:data,
            course_id:"",
          });
        }
      }
      return array;
    },

    
    async courseChange(type,index,val){
       if (!val) {
          if (type == "selectedMajorCourse") {
          this.selectedMajorCourse.examAreaId[index] = "";
          this.selectedMajorCourse.calculator[index] = "";
        } else if (type == "selectedOtherCourse") {
          this.selectedOtherCourse.examAreaId[index] = "";
          this.selectedOtherCourse.calculator[index] = "";
        }else if (type == "selectedSelectedCourse") {
          this.selectedSelectedCourse.examAreaId[index] = "";
          this.selectedSelectedCourse.calculator[index] = "";
        }
        return;
      }

      let loading = this.showLoading();
      let res = await this.$http.post("/pl/plExamAreaCourse/list.htm",this.Qs.stringify({course_id:val}));
     let res_calculator = await this.$http.post(
        "/pl/plExamAreaCourse/queryCourseCalculator.htm",
        this.Qs.stringify({ course_id: val })
      );

      if(type == "selectedMajorCourse"){
        this.selectedMajorCourse[`examAreaArray${index+1}`] = res.data.array;
        this.selectedMajorCourse.examAreaId[index] = "";
        if(res_calculator.data.entity){
          this.selectedMajorCourse.calculator[index] = res_calculator.data.entity.calculator;
        }else{
          this.selectedMajorCourse.calculator[index] = "";
        }
      } else if(type == "selectedOtherCourse"){
        this.selectedOtherCourse[`examAreaArray${index+1}`] = res.data.array;
        this.selectedOtherCourse.examAreaId[index] = "";
        this.selectedOtherCourse.examAreaId[index] = "";
        if(res_calculator.data.entity){
          this.selectedOtherCourse.calculator[index] = res_calculator.data.entity.calculator;
        }else{
          this.selectedOtherCourse.calculator[index] = "";
        }
      } else if(type == "selectedSelectedCourse"){
        this.selectedSelectedCourse[`examAreaArray${index+1}`] = res.data.array;
        this.selectedSelectedCourse.examAreaId[index] = "";
        if(res_calculator.data.entity){
          this.selectedSelectedCourse.calculator[index] = res_calculator.data.entity.calculator;
        }else{
          this.selectedSelectedCourse.calculator[index] = "";
        }
      }
      this.hideLoading(loading);

    },
    async saveEnrol(){
      
      let courseIdArray = [];
      let examAreaIdArray = [];
      let validate = true
      this.selectedMajorCourse.id.forEach((id,index) => {
        if(id != null && id != ''){
          let examAreaId = this.selectedMajorCourse.examAreaId[index]
          if(examAreaId != null && examAreaId != ''){
            courseIdArray.push(id);
            examAreaIdArray.push(examAreaId);
          }
          else{
            this.alert("每个课程必须选择考区!","信息提示");
            validate = false;
          }
        }
      });
      if(courseIdArray.length >1){
        this.alert("只允许变更一个课程。请切换“本专业课程”或“其他专业课程”或“选考课程”，删除其他课程后再修改。");
        return;
      }

      if(!validate) return;
      validate = true;
      this.selectedOtherCourse.id.forEach((id,index) => {
        if(id != null && id != ''){
          let examAreaId = this.selectedOtherCourse.examAreaId[index]
          if(examAreaId != null && examAreaId != ''){
            courseIdArray.push(id);
            examAreaIdArray.push(examAreaId);
          }
          else{
            this.alert("每个课程必须选择考区!","信息提示");
            validate = false;
          }
        }
      });
      if(courseIdArray.length >1){
        this.alert("只允许变更一个课程。请切换“本专业课程”或“其他专业课程”或“选考课程”，删除其他课程后再修改。");
        return;
      }
      if(!validate) return;

      validate = true;
      this.selectedSelectedCourse.id.forEach((id,index) => {
        if(id != null && id != ''){
          let examAreaId = this.selectedSelectedCourse.examAreaId[index]
          if(examAreaId != null && examAreaId != ''){
            courseIdArray.push(id);
            examAreaIdArray.push(examAreaId);
          }
          else{
            this.alert("每个课程必须选择考区!","信息提示");
            validate = false;
          }
        }
      });
      if(courseIdArray.length >1){
        this.alert("只允许变更一个课程。请切换“本专业课程”或“其他专业课程”或“选考课程”，删除其他课程后再修改。");
        return;
      }
      if(!validate) return;

      if(courseIdArray.length == 0){
        this.alert("请选择报考课程","信息提示");
        return;
      }

      let res1 = await this.$http.post("/std/stdEnrol/checkOtherCity.htm",
        this.Qs.stringify({
            enrol_id:this.selectedEditItem.id,
            courseId:courseIdArray[0],
            examId:examAreaIdArray[0],
            std_id:this.stdReg.id,
          }));
          
      if(res1.data.success && res1.data.errorCode ==247){
        
        // 跨市修改考区
         this.$confirm("跨市修改考区，同一天的其他课程将同时修改考区，确定修改吗？", "信息提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(async () => {
              // 跨市修改考区
              this.doSaveEnrol(courseIdArray,examAreaIdArray,1);
            })
            .catch(() => {});
      }else if(res1.data.success){
        // 非跨市修改考区
        this.doSaveEnrol(courseIdArray,examAreaIdArray);
      }else{
        // 检验失败
        this.alert(res1.data.errorMsg);
      }

    },

    async doSaveEnrol(courseIdArray,examAreaIdArray,otherCity){
      let res = await this.$http.post("/std/stdEnrol/editCourse.htm",
        this.Qs.stringify({
            enrol_id:this.selectedEditItem.id,
            courseId:courseIdArray[0],
            examId:examAreaIdArray[0],
            std_id:this.stdReg.id,
            otherCity:otherCity
          }));
      if(res.data.success){
        // this.alert("报考提交成功",'信息提示');
         this.confirm(
          "报考课程变更已提交成功。如未缴费，请尽快缴费!避免错过考试。",
          "操作确定",
          {
            confirm: function() {
              // this.goUrl('/enrolGuid');
            }
          }
        );
        this.editCourseDialogVisible = false;
        this.init();
      }else{
        this.alert(res.data.errorMsg);
      }
    },

    //支付确认
    async payOk() {
      let res = await this.$http.post("/std/stdEnrol/payUnion/checkOrderIsSuccess.htm",
        this.Qs.stringify({
            orderNum:this.orderNum,
            // orderNum:"1564826664874"
          }));
      if(res.data.success){
        this.alert("支付成功!");
        setTimeout(() => {
          this.init();
        }, 500);
        return true;
      }else{
         if(res.data.errorMsg){
          this.alert(res.data.errorMsg);
          return false;
        }
      }

      this.payConfirm = true;
    },
    //网银支付
    async goWyPay() {
      ;
      let cloneMap = JSON.parse(JSON.stringify(this.map));
      delete cloneMap["ticketNo"];
      delete cloneMap["stdName"];

      // let params = this.Qs.stringify(cloneMap);
      // window.open(
      //   `http://epaytest.gxeea.cn:8086/unifiedPay/unionPay?${params}`,
      //   "网银支付",
      //   "fullscreen=1"
      // );
      // console.log(cloneMap);
      let { data } = await this.$http.post(
        "/std/getWyUrl.htm"
      );
      ;
      document.getElementById("ylForm").action = data.entity;
      setTimeout(() => {
        document.getElementById("ylFormSubBtn").click();
      }, 100);

    },
    //禾木系统支付接口
    async goPay(item) {
      let { data } = await this.$http.post(
        "/std/stdEnrol/pay/channel/list.htm"
      );
      if (data.array == 0) {
        this.alert(
          "此考点未开放网络缴费，请联系考点进行缴费确认！",
          "信息提示"
        );
        return;
      }
      if (data.array > 1) {
        // 多个缴费渠道，显示列表供选择
        return;
      }
      if (!data.array) {
        this.alert("支付未启用，未配置任何有效的商户渠道", "信息提示");
        return;
      }
      this.payChannel = data.array[0];

      this.channelPay(item);
    },
    async channelPay(item) {
      let enrol;
      let { data } = await this.$http.post(
        "/std/stdEnrol/pay/check.htm",
        this.Qs.stringify({ enrol_id: item.id })
      );
      enrol = data.entity;
      if (data.entity.fee_status == 1) {
        this.alert(
          "已经对该报考进行了缴费确认，无需再进行缴费操作！",
          "信息提示"
        );
      } else {
        if (this.payChannel.channel_id == "WeiXin") {
          //模态框 扫码 TODO
        } else {
          this.alert(
            "系统打开了新的页面导航到银行支付页面，请在新页面完成支付操作，如未能打开新页面，请检查浏览器拦截设置。<br/>在完成支付前，请勿刷新本页面",
            "请在新页面进行支付操作"
          );
          let url =
            "/std/stdEnrol/order.htm?enrol_id=" +
            enrol.id +
            "&channel_id=" +
            this.payChannel.channel_id;
          // url = "/sesenrol" + url;
          url = "/ses-enrol-v1" + url;
          window.open(url);
        }
      }
    },
    async goPayDetail(item) {
      // this.alert("缴费记录 Todo");
      this.loading = true;
      let { data } = await this.$http.post(
        "/pay/payBillUnion/listByEnrol.htm",
        this.Qs.stringify({
          enrol_id: item.id
        })
      );
      if (data.success) {
        this.payListDialogVisible = true;
        this.loading = false;
        this.$nextTick(() => {
          console.log(data.array.length);
          //已经支付成功 只显示支付成功的订单
          if (item.fee_status == 1) {
            this.payList = _.filter(data.array, function(o) {
              return o.bill_status == "支付成功";
            });
          } else {
            this.payList = data.array;
          }
        });
      }
    },

    async sendSms() {
        var _this = this;

        
        let {data} = await this.$http.post("/std/sendSmsForPay.htm",{});
      if(data.success){
          _this.secCountDown = 60;
          var int = setInterval(function(){
          _this.secCountDown--;
          if(_this.secCountDown <= 0){
            clearInterval(int);
            //恢复 发送按钮
            _this.secCountDownInfo = "获取验证码";
          }else{
            //倒计时提示
            _this.secCountDownInfo = _this.secCountDown+"秒后可重新发送";
          }
        },1000);

          this.alert("验证码发送成功!","信息提示");
          
      }else{
          this.alert(data.errorMsg);
      }
            
        
    }

  }
};
</script>

<style lang="scss">
#paymodal{
  .el-dialog__body{
    padding:10px 20px;
    color:#606266;
    font-size:14px;
    word-break:break-all
    }
}

#enrol_guid_index_scoped {
  .el-card__body {
    padding: 9px !important;
  }
  .el-card__header {
    padding: 11px 20px;
  }
  .cell {
    margin-left: 10px;
    border-bottom: 1px;
  }
  .el-table td,
  .el-table th {
    padding: 5px 0;
  }
  .el-card__header {
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
  }
  .el-card__body {
    padding: 0px;
  }
  .redBold {
    color: red;
    font-size: 15px;
    font-weight: 200;
    font-weight: bold;
  }
  .el-button-group {
    margin-top: 10px;
  }
  .el-button {
    margin-right: 10px;
  }
  .title {
    color: #409eff;
    margin-bottom: 15px;
  }
}
</style>
