<template>
  <d2-container class="page">
    <el-tabs value="first">
      <el-tab-pane label="转至外省" name="first">
        <div style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" style="padding-bottom: 0px;padding-top: 0px;margin-top: 0px;margin-bottom: 0px;" class="el-alert el-alert--warning" v-if="timeLimit">
            <div class="el-alert__content" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">
              <span class="el-alert__title" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">转至外省在线申请时间：{{timeLimit.start_time}} 到 {{timeLimit.end_time}}</span>
            </div>
          </div>
          <div role="alert" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;" class="el-alert el-alert--warning" v-if="auditTimeLimit">
            <div class="el-alert__content" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">
              <span class="el-alert__title" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">转至外省地市审核时间：{{auditTimeLimit.start_time}} 到 {{auditTimeLimit.end_time}}</span>
            </div>
          </div>

          <div role="alert" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;" class="el-alert el-alert--warning" v-if="confirmLimit">
            <div class="el-alert__content" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">
              <span class="el-alert__title" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">转至外省网上确认时间：{{confirmLimit.start_time}} 到 {{confirmLimit.end_time}}</span>
            </div>
          </div>

           <div role="alert" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;" class="el-alert el-alert--warning" v-if="ByTurnOutApplyControl">
            <div class="el-alert__content" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">
              <span class="el-alert__title" style="padding-top: 0px;padding-bottom: 0px;margin-top: 0px;margin-bottom: 0px;">{{ByTurnOutApplyControl}}</span>
            </div>
          </div>
<!--
          <div role="alert" class="el-alert el-alert--warning">
            <div class="el-alert__content">
              <a class="el-alert__title" style="color:red;font-size:16px;font-weight:600;cursor:pointer" @click="shouPlaces()">点击查看材料接受地点 </a>
             
            </div>
          </div>
-->
        </div>
        <div v-if="timeLimit && timeLimit.in_time">
          <el-button type="primary" @click="item={};goApply()">申请转至外省</el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="applyList"
          style="width: 100%">
         <el-table-column
            type="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column
            prop="batch"
            label="批次"
            width="120">
          </el-table-column>
          <el-table-column
            prop="out_ticket_no"
            label="转出准考证"
            width="120">
          </el-table-column>
          <el-table-column
            prop="major_code"
            label="专业代码"
            width="100">
          </el-table-column>
          <el-table-column
            prop="major_name"
            label="专业名称"
            width="200"
            >
          </el-table-column>
          <el-table-column
            prop="province_name"
            label="转至省份 "
            width="140"
            >
          </el-table-column>
          <el-table-column
            prop="in_ticket_no"
            label="外省准考证 "
            width="120">
          </el-table-column>
          <el-table-column
            prop="std_mobile"
            label="手机号码 "
            width="120">
          </el-table-column>
          <el-table-column
            prop="reject_advice"
            label="驳回意见 "
            width="150">
          </el-table-column>
          <el-table-column
            prop="status_text"
            label="状态"
            width="120">
          </el-table-column>
          
          <el-table-column
            prop="receive_status_text"
            label="外省接收回执"
            width="140">
          </el-table-column>
          <el-table-column
            prop="back_reason"
            label="外省退回原因"
            width="200">
          </el-table-column>
           <el-table-column
            prop="overtime"
            label="是否过期"
            width="100">
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="140">
              <template slot-scope="scope">
                <div v-if="scope.row.status == 0"> 
                  <el-button @click="goEdit(scope.row)">修改申请信息</el-button>
                </div>
                <div v-if="scope.row.status == 8 && scope.row.overtime != '已过期'"> 
                  <el-button @click="showTableDialog(scope.row)">网上确认</el-button>
                </div>
              </template>
          </el-table-column>
         
        </el-table>
<!--
        <div class="el-alert__content " style="padding-top:10px">
          <span class="el-alert__title">申请步骤：</span>
          <p class="el-alert__description">
            1 考生在此页面填写转考申请。
          </p>
          <p class="el-alert__description">
            2 社会考生携带相关证明材料到就近市考办，具体办理时间请先打电话咨询各市考办，助学考生携带相关证明材料到主考学校，现场填写申请表。
          </p>
          <p class="el-alert__description">
            3 市考办或主考学校现场审核，上报考试院。
          </p>
          <p class="el-alert__description">
            4 考试院审核通过后，待指定时间同步国家系统。
          </p>
           <p class="el-alert__description">
            5 外省接收回执为接收时，考生可在转入省办理转入业务。（请考生及时在转入省办理转入业务）
          </p>
        </div>
-->
        <el-dialog title="材料接受地点列表" width="1100px" :visible.sync="showPlacesWin">
          <el-table
          v-loading="loading"
          :data="places">
            <el-table-column
              type="index"
              label="序号"
              width="50">
            </el-table-column>
             <el-table-column
              prop="org_name"
              label="市考办/主考学校"
              width="150">
            </el-table-column>
            <el-table-column
              prop="start_time"
              label="开始时间"
              width="100">
            </el-table-column>
            <el-table-column
              prop="end_time"
              label="结束时间"
              width="100">
            </el-table-column>
            <el-table-column
              prop="phone"
              label="电话"
              width="120">
            </el-table-column>
             <el-table-column
              prop="qq"
              label="qq"
              width="100">
            </el-table-column>
             <el-table-column
              prop="website"
              label="网址"
              width="180">
              <template slot-scope="scope">
                        <span v-if="scope.row.website ">
                          
                          <a v-bind:href ="scope.row.website" target="new">{{scope.row.website}}</a>
                        </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="地址"
              width="250">
            </el-table-column>
           
          </el-table>
        </el-dialog>
        <el-dialog title="申请转至外省" width="1000px" :visible.sync="applyDialogVisible">
            <el-form ref="itemForm" :model="item" :rules="itemRules" label-width="160px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="选择专业(准考证)" prop="major_id">
                   <el-select size="medium" v-model="item.major_id" filterable clearable placeholder="请选择专业" @change="majorChange" style="width:400px">
                      <el-option v-for="item in ticketList" :key="item.major_id" :label="item.full_name" :value="item.major_id + ''"></el-option>
                   </el-select>
                  </el-form-item>
                  <el-form-item label="转至省份" prop="in_prov_code">
                   <el-select size="medium" v-model="item.in_prov_code" filterable clearable placeholder="请选择转至省份" style="width:400px">
                      <el-option v-for="item in provList" :key="item.province_id" :label="item.province_name" :value="item.province_id + ''"></el-option>
                   </el-select>
                  </el-form-item>
                  <el-form-item label="外省准考证" prop="in_ticket_no">
                    <div style="width:400px">
                      <el-input size="medium" v-model="item.in_ticket_no" maxlength="20" placeholder="外省准考证必须准确，否则外省将打回"></el-input>
                    </div>
                  </el-form-item>

                   <el-form-item label="手机号码" prop="std_mobile">
                    <div style="width:400px">
                      <el-input size="medium" v-model="item.std_mobile" maxlength="20" placeholder="请保持电话通畅"></el-input>
                    </div>
                  </el-form-item>
                 <!-- <el-form-item label="附件" prop="file">
                     <div style="width:350px">-->
                       <!-- action="https://jsonplaceholder.typicode.com/posts/" -->
                        <!--<el-upload
                          :http-request = "customUpload"
                          class="upload-demo"
                          
                          ref="upload"
                          :on-preview="handlePreview"
                          :on-remove="handleRemove"
                          :before-upload="beforeUpload"
                          :before-remove="beforeRemove"
                           multiple
                          :limit="1"
                           action=""
                          :on-exceed="handleExceed"
                          :on-change="handleChange"
                          :auto-upload="false"
                          list-type="picture"
                          :file-list="fileList"
                          accept="image/jpeg,image/jpg,image/png" 
                          >
                          <el-button size="small" type="primary">点击上传</el-button>
                          <div slot="tip" class="el-upload__tip" style="color:red">只能上传jpg/jpeg/png文件，且不超过2MB</div>
                        </el-upload>
                       
                      </div>
                  </el-form-item> -->
                </el-col>
              </el-row>
            
            </el-form>
             <el-table
                v-loading="courseLoading"
                :data="courseList"
                style="width: 100%">
                <el-table-column
                  prop="course_name"
                  label="课程名称"
                  width="150">
                </el-table-column>
                <el-table-column
                  prop="course_code"
                  label="课程代码"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="course_exam_type"
                  label="课程考试类型"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="course_score"
                  label="学分">
                </el-table-column>
                <el-table-column
                  prop="origin_score"
                  label="考试成绩">
                </el-table-column>
              </el-table>
            <center>
              <br>
              <el-button type="primary" v-if="can_submit" @click="submit()">提交</el-button>
            </center>

        </el-dialog>

        <el-dialog title="网上确认" width="800px" :visible.sync="tableDialogVisible">
          <div>
            
          
            <center>
              <el-button type="primary" @click="downByApplyRegisterPdf">下载转考（转出）登记表</el-button>

            </center>
            <br>
             <br>
              <br>
             <center v-if="item && item.status=='8'">

              <el-button type="primary" @click="confirmByApply(item)">确认转至外省信息无误</el-button>

            </center>
             
          </div>

          
          

        </el-dialog>

      </el-tab-pane>
    </el-tabs>
  </d2-container>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { json } from "body-parser";

export default {
  computed: {
    ...mapState({
      stdReg: state => state.enrol.StdReg
    })
  },

  data() {
    return {
      loading: false,
      courseLoading: false,
      applyDialogVisible: false,
      showPlacesWin:false,
      tableDialogVisible: false,
      timeLimit: null,
      auditTimeLimit:null,
      confirmLimit:null,
      ByTurnOutApplyControl:null,
      applyList: null,
      place: null,
      ticketList: null,
      provList: null,
      courseList: null,
      uploadNeed: false,
      can_submit:true,
      places:[],
      item: {
        major_id: "",
        in_prov_code: "",
        in_ticket_no: "",
        std_mobile: "",
        file: ""
      },
      itemRules: {
        major_id: [{ required: true, message: "请选择专业", trigger: "blur" }],
        in_prov_code: [
          { required: true, message: "请选择转至省份", trigger: "blur" }
        ],
        in_ticket_no: [
          { required: true, message: "请输入外省准考证", trigger: "blur" }
        ],
        std_mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" }
        ],
        file: [{ required: true, message: "请上传文件", trigger: "blur" }]
      },
      // file: "",
      fileList: []
    };
  },

  async mounted() {
    this.loading = true;
    this.init();
    this.loading = false;
  },
  methods: {
    //初始化列表查询
    async init() {
      let res = await this.$http.post(
        "/by/byTurnOutApply/list.htm",
        {},
        this.$http.headers.FORM
      );
      this.timeLimit = res.data.map.timeLimit;
      this.applyList = res.data.map.applyList;
      this.auditTimeLimit = res.data.map.auditTimeLimit;
      this.confirmLimit = res.data.map.confirmLimit;
      this.ByTurnOutApplyControl = res.data.map.ByTurnOutApplyControl;
      // if(res.data.map.placeList.length >0)
      // this.place = res.data.map.placeList[0];
      this.places =  res.data.map.placeList;
    },
    shouPlaces(){
      this.showPlacesWin = true;
    },
     showTableDialog(item){
      this.item = item;
      
      this.tableDialogVisible = true;
    },
    //跳转申请页面
    async goApply() {
      for (const key in this.item) {
        if (this.item.hasOwnProperty(key)) {
          this.item[key] = "";
        }
      }

      this.fileList = [];
      
      this.loading = true;
      let { data } = await this.$http.post(
        "/by/byTurnOutApply/toAdd.htm",
        {},
        this.$http.headers.FORM
      );
      this.ticketList = data.map.ticketList;
      this.provList = data.map.provList;

      //默认选择第一个
      if (this.ticketList.length > 0) {
        let major_id = this.ticketList[0].major_id+"";
        this.item.major_id = major_id;
        
        this.reqCourse(major_id);
      }
      
      this.item.std_mobile = this.stdReg.std_mobile;
      this.loading = false;
      this.applyDialogVisible = true;
    },
    async goEdit(item){
      let { data } = await this.$http.post(
        "/by/byTurnOutApply/get.htm",
        this.Qs.stringify({id:item.id}),
        this.$http.headers.FORM
      );
      if (data.success) {
        let item = await this.goApply();
        await this.reqCourse(data.entity.major_id);
        this.item = data.entity; 
        this.item.major_id = data.entity.major_id  + "";
        this.item.in_prov_code = data.entity.in_prov_code + "";
        this.item.in_ticket_no = data.entity.in_ticket_no  + "";
        this.item.std_mobile = data.entity.std_mobile  + "";
        this.fileList = [{name:`${data.entity.ticket_path}`,url:`${window.uploadServerUrl}${data.entity.ticket_path}`}]
        this.item.file = this.fileList;
        this.uploadNeed = false;
        this.$nextTick(() => {
          this.applyDialogVisible = true;
        });
      }else{
        this.alert(data.errorMsg);
      }

   },
    //专业下拉联动事件
    async majorChange(major_id) {
      this.loading = true;
      await this.reqCourse(major_id);
      this.loading = false;
    },

    //请求课程数据
    async reqCourse(major_id) {
      this.courseLoading = true;
      let courseListResp = await this.$http.post(
        "/by/byTurnOutApply/courseList.htm",
        this.Qs.stringify({
          std_major_id: major_id
        }),
        this.$http.headers.FORM
      );
      this.courseList = courseListResp.data.array;
      this.courseLoading = false;
    },

    submit() {
      
      if(!String(this.item.major_id)){
        this.alert("请选择专业(准考证)");
        return ;
      }

      if(!String(this.item.in_prov_code)){
        this.alert("请选择转至省份");
        return ;
      }

       if(!String(this.item.in_ticket_no)){
        this.alert("请输入外省准考证");
        return ;
      }

       if(!String(this.item.std_mobile)){
        this.alert("请输入手机号码");
        return ;
      }

      if(this.uploadNeed){
        this.$refs.upload.submit();
      }else{
        this.saveData();
      }
    },

    //保存
    async saveData(filePath) {
      this.can_submit = false;
      if(filePath)this.item["filePath"] = filePath;
    
      let reqUrl = (typeof(this.item.id)!="undefined")?"/by/byTurnOutApply/edit.htm":"/by/byTurnOutApply/add.htm";
      let { data } = await this.$http.post(
        reqUrl,
        this.Qs.stringify(this.item),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.alert("提交成功");
        this.init();
        this.$nextTick(() => {
          this.applyDialogVisible = false;
        });
      }else{
        this.alert(data.errorMsg);
      }

       this.can_submit = true;
    },

    handleRemove(file, fileList) {
      if (fileList.length == 0) {
        this.item.file = null;
      }
      this.fileList = [];
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeUpload(file, fileList){
      const isJPEG = file.type === 'image/jpeg';
      const isJPG = file.type === 'image/jpg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isJPEG && !isPNG) {
          this.alert('上传图片必须是JPG/JPEG/PNG/格式!');
      }
      if (!isLt2M) {
          this.alert('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isJPEG || isPNG) && isLt2M;
    },
    beforeRemove(file, fileList) {
    
    },
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.item.file = fileList[0].name;
        this.uploadNeed = true;
      }else{
        this.uploadNeed = false;
      }
    },
    customUpload(file) {
      
       this.$refs["itemForm"].validate(valid => {
        if (valid) {
          this.fileUpload(file).then(response => {
            //上传成功提交表单
            if (response.data.success) {
              let filePath = response.data.entity;
              this.uploaded = true;
              this.saveData(filePath);
            } else {
              this.alert(response.data.errorMsg);
            }
          });
          return true;
        } else {
          console.log("error submit!!");
          return false;
        }
      });

      
    },

    fileUpload(fileobj) {
      let param = new FormData();
      param.append("file", fileobj.file);
      return this.$http.request({
        method: "post",
        url: "by/byTurnOutApply/upload.htm",
        headers: { "Content-Type": "multipart/form-data" },
        data: param
      });
    },

    async downByApplyRegisterPdf(){
      let res = await this.$http({
        method: "post",
        url: `/by/byTurnOutApply/downApplyPdf.htm?id=`+this.item.id,
        responseType: "blob"
      });
      let fileName = null;
      
      if(this.stdReg.ticket_no){
        fileName = `高等教育自学考试转考（转出）登记表(${this.stdReg.ticket_no}).pdf`;
      }else{
        fileName = `高等教育自学考试转考（转出）登记表.pdf`;
      }
      if (window.navigator.msSaveBlob) {
        try {
          var blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, fileName);
        } catch (e) {
          console.log(e);
        }
      } else {
        let loading = this.showLoading();
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);

        document.body.appendChild(link);
        link.click();
        this.hideLoading(loading);
      }
    },

     async confirmByApply(item){
    
    this.$confirm("确认转至外省信息无误吗？", "信息提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(async () => {

              this.doConfirmByApply(item);
              
            })
            .catch(() => {});
  },

  async doConfirmByApply(item){
    let loading = this.showLoading();
          let { data } = await this.$http.post(
              "by/byTurnOutApply/confirmByApply.htm",
              this.Qs.stringify({
                id: item.id
              }),
              this.$http.headers.FORM
            );
            this.hideLoading(loading);
            
            if (data.success) {
              this.alert("网上确认成功");
              this.init();
              this.$nextTick(() => {
                this.tableDialogVisible = false;
              });
            } else {
             
              this.hideLoading(loading);
              this.alert(data.errorMsg);
              return false;
            }
  },
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/public.scss";
</style>
