<template>
  <d2-container class="page" v-loading="loading">
    <el-tabs value="first">
      <el-tab-pane label="非学历证书学习成果认证" name="first">
        <div v-if="timeLimit" style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" class="el-alert el-alert--warning" v-if="timeLimit">
            <div class="el-alert__content">
              <span class="el-alert__title">非学历证书学习成果认证在线申请时间：{{timeLimit.start_time}} 到 {{timeLimit.end_time}}</span>
             
            </div>
          </div>
        </div>

        <div v-if="authTimeLimit" style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" class="el-alert el-alert--warning" v-if="authTimeLimit">
            <div class="el-alert__content">
              <span class="el-alert__title">现场确认截止时间为：{{authTimeLimit.end_time}} ，具体的确认时间安排由各现场确认点确定，考生须在现场确认点所规定的时间内进行确认。</span>
             
            </div>
          </div>
        </div>

        <div  v-if="pushTimeLimit" style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" class="el-alert el-alert--warning" v-if="pushTimeLimit">
            <div class="el-alert__content">
              <span v-if="pushTimeLimit.time == 1" class="el-alert__title">{{pushTimeLimit.year}}年上半年免考审定结果公布时间：{{pushTimeLimit.start_time}}</span>
              <span v-else-if="pushTimeLimit.time == 2" class="el-alert__title">{{pushTimeLimit.year}}年下半年免考审定结果公布时间：{{pushTimeLimit.start_time}}</span>
              <span v-else class="el-alert__title">免考审定结果公布时间：</span>
             
            </div>
          </div>
        </div>

       <!--
        <div v-if="timeLimit" style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" class="el-alert el-alert--warning" v-if="timeLimit">
            <div class="el-alert__content">
              <span class="el-alert__title">为做好新型冠状病毒感染疫情防控工作，目前仅开放自学考试免考线上申请，暂停现场确认工作，具体现场确认时间另行通知。</span>
             
            </div>
          </div>
        </div>
        -->

        <div v-if="timeLimit && timeLimit.in_time">
          <el-button type="primary" @click="goApply()">申请非学历学习成果认证课程</el-button>
        </div>
        <el-table
          :data="applyList"
          style="width: 100%">
          <el-table-column
            prop="time_name"
            label="批次"
            width="100">
          </el-table-column>
          <el-table-column
            prop="std_name"
            label="录入姓名"
            width="80">
          </el-table-column>
          <el-table-column
            prop="std_cert_no"
            label="录入身份证"
            width="170">
          </el-table-column>
          <!-- <el-table-column
            prop="source_unit"
            label="颁发单位"
            width="140"
            >
          </el-table-column> -->
          <el-table-column
            prop="cert_name"
            label="证书类别"
            width="240"
            >
          </el-table-column>
          <el-table-column
            prop="exam_date"
            label="考试时间"
            width="80">
          </el-table-column>
          <el-table-column
            prop="score"
            label="成绩"
            width="60">
          </el-table-column>
          <el-table-column
            prop="cert_no"
            label="证件编号"
            width="140">
          </el-table-column>
          <el-table-column
            prop="status_text"
            label="状态"
            width="100">
          </el-table-column>
          <el-table-column
            prop="is_overtime"
            label="是否过期"
            width="100">
          </el-table-column>
          <el-table-column
            prop="verify_remark1"
            label="确认意见"
            width="120">
          </el-table-column>
          <el-table-column
            prop="verify_remark2"
            label="审核意见"
            width="140">
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="140">
              <template slot-scope="scope">
                <div v-if="scope.row.status == 0 && scope.row.is_overtime !='已过期'"> 
                  <el-button @click="goEdit(scope.row)">修改申请信息</el-button>
                </div>
                <div v-if="scope.row.status == 1"> 
                  <el-button @click="back(scope.row)">撤回申请信息</el-button>
                </div>
              </template>
          </el-table-column>
        </el-table>

         <el-table
          :data="courseList"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="60">
          </el-table-column>
          <el-table-column
            prop="std_cert_no"
            label="身份证"
            width="180">
            <template slot-scope="scope">{{scope.row.std_cert_no? scope.row.std_cert_no.replace(/^(.{6})(?:\w+)(.{4})$/, "\$1********\$2"):""}}</template>
          </el-table-column>
          <el-table-column
            prop="cert_no"
            label="证书号"
            width="140"
            >
          </el-table-column>
          <el-table-column
            prop="course_code"
            label="课程代码"
            width="100"
            >
          </el-table-column>
          <el-table-column
            prop="course_name"
            label="课程名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="score"
            label="课程成绩"
            width="80">
          </el-table-column>
          <el-table-column
            prop="status_text"
            label="状态"
            width="100">
          </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="1000px" :visible.sync="applyDialogVisible">
            <el-form ref="itemForm" :model="item" :rules="itemRules" label-width="120px">
              <el-row>
                <el-col :span="10">
                  
                  <el-form-item label="证书身份证号" prop="std_cert_no">
                    <div style="width:300px">
                      <el-input size="medium" v-model="item.std_cert_no" disabled="disabled" placeholder="请输入内容"></el-input> 
                    </div>
                  </el-form-item>

                  <el-form-item label="证书考生姓名" prop="std_name">
                     <div style="width:300px">
                      <el-input size="medium" v-model="item.std_name" placeholder="请输入内容"></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item label="证书类别" prop="cert_type_id">
                    <el-select size="medium" style="width:300px" v-model="item.cert_type_catalog" filterable clearable placeholder="请选择证书分类" @change="certTypeCatalogChange">
                      <el-option v-for="item in certTypeCatalogList" :key="item.dict_value" :label="item.dict_text" :value="item.dict_value"></el-option>
                   </el-select>
                   
                   <!-- item.cert_code+'-'+item.cert_name -->
                    <el-select size="medium" style="width:300px" v-model="item.cert_type_id" filterable clearable placeholder="请选择证书类型" @change="certTypeChange">
                      <el-option v-for="item in certTypeList" :key="item.id" :label="item.dict_text" :value="item.dict_value"></el-option>
                   </el-select>
                  </el-form-item>
                   <el-form-item label="证书编号" prop="cert_no">
                     <div style="width:300px">
                      <el-input size="medium" v-model="item.cert_no" placeholder="请输入内容"></el-input>
                    </div>
                  </el-form-item>
                   <el-form-item label="考试时间" prop="exam_date">
                     <div style="width:300px">
                      <el-input size="medium" v-model="item.exam_date" placeholder="请输入内容"></el-input>证书上的考试时间，例:201103
                    </div>
                  </el-form-item>
                  <el-form-item label="考试成绩" prop="score">
                     <div style="width:300px">
                      <el-input size="medium" v-model="item.score" placeholder="请输入内容"></el-input>请输入数字，如:99 。60（及格） 70（取中间值）90（优秀）
                    </div>
                  </el-form-item>
                  <el-form-item label="附件" prop="file">
                     <div style="width:300px">
                       <!-- multiple -->
                        <el-upload
                          :http-request = "customUpload"
                          class="upload-demo"
                          action="https://jsonplaceholder.typicode.com/posts/"
                          ref="upload"
                          :on-preview="handlePreview"
                          :on-remove="handleRemove"
                          :before-upload="beforeUpload"
                          :before-remove="beforeRemove"
                           
                          :limit="1"
                          :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-col :span="2">
                  <hr style="height:80%;width:1px;height: 600px; width: 1px;" />
                </el-col>
                <el-col :span="12">
                  <el-form-item label="选择专业" prop="major_id">
                   <el-select size="medium" v-model="item.major_id" filterable clearable placeholder="请选择专业" @change="majorChange">
                      <el-option v-for="i in majorList" :key="i.major_id" :label="i.full_name" :value="i.id+''"></el-option>
                   </el-select>
                  </el-form-item>
                  
                  <el-table
                      :data="editCourseList"
                      style="margin-left:10px;width:500px">
                     
                      <el-table-column
                        prop=""
                        label="课程名称"
                        width="300">
                         <template scope="scope">
                              {{scope.row.full_name}}
                          </template>
                      </el-table-column>
                       <el-table-column label="申请学习成果认证" width="140">
                          <template scope="scope">
                            <center>
                              <el-checkbox :label="scope.row.id" v-model="checkedCourse[scope.row.index]">&nbsp;</el-checkbox>
                            </center>
                          </template>
                      </el-table-column>
                    </el-table>
                </el-col>
              </el-row>
            
            </el-form>
            <center>
              <br>
              <el-button type="primary" @click="submit()">提交</el-button>
            </center>

        </el-dialog>

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

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

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

  data() {
    return {
      majorList: null,
      loading: false,
      applyDialogVisible: false,
      timeLimit: null,
      pushTimeLimit: null,
      authTimeLimit:null,
      applyList: null,
      courseList: null,
      certTypeList: null,
      certTypeCatalogList: null,
      checkedCourse: [],
      editCourseList: null,
      uploadNeed: false,
      item: {
        major_id: "",
        std_cert_no: "",
        std_name: "",
        cert_type_id: "",
        cert_no: "",
        exam_date: "",
        score: "",
        file: ""
      },
      itemRules: {
        major_id: [{ required: true, message: "请选择专业", trigger: "blur" }],
        std_cert_no: [
          { required: true, message: "请输入证书身份证号", trigger: "blur" }
        ],
        std_name: [
          { required: true, message: "请输入考试姓名", trigger: "blur" }
        ],
        cert_type_id: [
          { required: true, message: "请输入证书类型", trigger: "blur" }
        ],
        cert_no: [
          { required: true, message: "请输入证书编号", trigger: "blur" }
        ],
        exam_date: [
          { required: true, message: "请输入考试时间", trigger: "blur" }
        ],
        score: [{ 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(
        "/mk/mkCertNeduApply/list.htm",
        {},
        this.$http.headers.FORM
      );
      this.timeLimit = res.data.map.timeLimit;
      this.pushTimeLimit = res.data.map.pushTimeLimit;
      this.authTimeLimit = res.data.map.authTimeLimit;
      this.applyList = res.data.map.applyList;


     res = await this.$http.post(
        "/mk/mkCertNeduApplyCourse/listByStd.htm",
        {},
        this.$http.headers.FORM
      );
      this.courseList = res.data.array;
        
      },

    //跳转申请页面
    async goApply() {
      for (const key in this.item) {
        if (this.item.hasOwnProperty(key)) {
          this.item[key] = "";
        }
      }

      this.fileList = [];
      this.checkedCourse = [];
      this.editCourseList = null;

      this.loading = true;
      this.item.std_cert_no = this.stdReg.cert_no;
      let { data } = await this.$http.post(
        "mk/mkCertNeduApply/toApply.htm",
        {},
        this.$http.headers.FORM
      );
      this.majorList = data.map.majorList;
      this.certTypeCatalogList = data.map.certTypeCatalogList;

      //默认选择第一个
      // alert(this.majorList.length)
      if (this.majorList.length > 0) {
        let major_id = this.majorList[0].major_id+"";
        this.item.major_id = major_id;
        this.majorChange(major_id)
      }
      this.loading = false;
      this.applyDialogVisible = true;
    },
    async majorChange(major_id){
      this.loading = true;
      this.editCourseList = [];
      let resp = await this.$http.post(
        "pl/plMajor/listMajorCourse.htm",
        this.Qs.stringify({
          major_id: major_id
        }),
        this.$http.headers.FORM
      );
      let array = resp.data.array;
      let newArray = [];
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        element["index"] = index;
        newArray.push(element);
      }
      this.editCourseList = newArray;
      this.loading = false;

    },
    //专业下拉联动事件
    async certTypeCatalogChange(cert_catalog) {
      this.loading = true;
      console.log(cert_catalog);
      this.item.cert_type_id;
      this.reqCertType(cert_catalog);
      this.loading = false;
    },
    //专业下拉联动事件
    async certTypeChange(major_id) {
      if (!major_id) return;
      this.loading = true;
      // this.reqCourse(major_id);
      this.loading = false;
    },

    //请求课程数据 TODO
    async reqCertType(cert_type) {
      this.courseLoading = true;
      // let resp = await this.$http.post(
      //   "mk/mkCertType/listByType.htm",
      //   this.Qs.stringify({
      //     cert_type: cert_type
      //   }),
      //   this.$http.headers.FORM
      // );
      let resp = await this.$http.post(
        "mk/mkCertNeduApply/queryCertTypeBylevel.htm",
        this.Qs.stringify({
          cert_level: cert_type
        }),
        this.$http.headers.FORM
      );
      this.certTypeList = resp.data.array;
      
      //if (this.certTypeList && this.certTypeList.length > 0) {
        
        //this.item.cert_type_id = this.certTypeList[0].id;
        // this.reqCourse(this.item.cert_type_id);
      //}
    },

    //请求课程数据
    async reqCourse(cert_type_id) {
     
      this.courseLoading = true;
      let resp = await this.$http.post(
        "/mk/mkCertCourse/listByCertTypeId.htm",
        this.Qs.stringify({
          cert_type_id: cert_type_id
        }),
        this.$http.headers.FORM
      );
      let array =  resp.data.array;
      let newArray = [];
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        element["index"] = index;
        newArray.push(element);
      }
      this.editCourseList = newArray;
      this.courseLoading = false;
    },

    async back(row){
       let { data } = await this.$http.post(
        "mk/mkCertNeduApply/back.htm",
        this.Qs.stringify({ id: row.id }),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.init();
      } else {
        this.alert(data.errorMsg);
      }

    },

    submit() {
      if (!this.item.file) {
        this.alert("请先上传附件再提交!");
        return;
      }

       if (this.item.score && !(new RegExp(/^[0-9]+$/g).test(this.item.score))) {
          this.alert("考试成绩只允许输入整数!");
          return;
        } 

      // 上传-->customUpload-->fileUpload-->上传成功-->返回上传附件路径 调用saveDate保存数据
      
      if (this.uploadNeed) {
        this.$refs.upload.submit(); 
      }else{
        this.saveData();
      }
    },

    //保存
    async saveData(filePath) {
      if(this.checkedCourse.length == 0) {
        this.alert("请选择申请学习成果认证的课程");
        return;
      }
      if(this.checkedCourse.length == 0){
        this.alert("无课程可以提交免考申请!");
        return;
      }else{
          let course_code1 = "";
          let course_code2 = "";
          let course_count = 0;
          for (let index = 0; index < this.checkedCourse.length; index++) {
              const checked = this.checkedCourse[index];
              if(checked == true){
                
                if(course_count == 0){
                  course_code1 = this.editCourseList[index].course_code;
                }else if(course_count == 1){
                  course_code2 = this.editCourseList[index].course_code;
                }

                course_count++;
              }
            }
            
            // 只允许同时选择计算机应用基础00018和计算机应用基础（实践）00019
            if(course_count == 2 && !((course_code1 == '00018' && course_code2 == '00019')||(course_code1 == '00019' && course_code2 == '00018'))&& !((course_code1 == '00051' && course_code2 == '00052')||(course_code1 == '00052' && course_code2 == '00051'))){
              this.alert("一条申请单只允许选择一门课程或同时选择00018-计算机应用基础和00019-计算机应用基础（实践）或同时选择00051-管理系统中计算机应用和00052-管理系统中计算机应用（实践）!");
              return;
            }else if(course_count>2){
              this.alert("一条申请单只允许选择一门课程或同时选择00018-计算机应用基础和00019-计算机应用基础（实践）!或同时选择00051-管理系统中计算机应用和00052-管理系统中计算机应用（实践）!");
              return;
            }else if(course_count==0){
              this.alert("请选择一门课程!");
              return;
            }
      }
      

      if(this.item.cert_type_id == null || this.item.cert_type_id ==""){
        this.alert("请选择证书类别!");
        return;
      }

      this.loading = true;
      if(filePath) this.item["file_path"] = filePath;
      let cloneItem = _.cloneDeep(this.item);
      let reqCheckedCourse = [];
      for (let index = 0; index < this.checkedCourse.length; index++) {
        const checked = this.checkedCourse[index];
        if(checked == true)
          reqCheckedCourse.push(this.editCourseList[index].id);
        
      }
      cloneItem.courseIds = reqCheckedCourse.join();
      let { data } = await this.$http.post(
        "mk/mkCertNeduApply/apply.htm",
        this.Qs.stringify(cloneItem),
        this.$http.headers.FORM
      );
      this.loading = false;
      if (data.success) {
        this.alert("提交成功");
        this.init();
        this.$nextTick(() => {
          this.applyDialogVisible = false;
          this.init();
        });
      } else {
        this.alert(data.errorMsg);
      }
    },

    async goEdit(row){
      let { data } = await this.$http.post(
        "mk/mkCertNeduApply/get.htm",
        this.Qs.stringify({id:row.id}),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.goApply();
        //entity  无major_id的值
        data.map.entity.major_id = this.item.major_id;
        this.item = data.map.entity;
        
        if(null == data.map.entity.cert_type_catalog){
          this.item.cert_type_catalog = "";
           this.item.cert_type_id = "";
        }
        this.applyDialogVisible = true;
        this.certTypeCatalogList = data.map.certTypeCatalogList;
        this.$nextTick(()=>{
          this.item.cert_type_catalog = this.item.cert_type_catalog+"";
          this.item.cert_type_id = this.item.cert_type_id+"";
          this.certTypeCatalogChange(this.item.cert_type_catalog);
          this.fileList = [{name:`${this.item.file_path}`,url:`${window.uploadServerUrl}${this.item.file_path}`}]
          this.item.file = this.item.file_path;
        })
      } else {
        this.alert(data.errorMsg);
      }
    },


    handleRemove(file, fileList) {
      this.item.file = null;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一个附件!");
    },
    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;
        this.item.file = file;
      }else{
        this.uploadNeed= false;
        this.item.file = "";
      }
    },
    customUpload(file) {
      
      this.$refs["itemForm"].validate(valid => {
        if (valid) {
          this.fileUpload(file).then(response => {
            //上传成功提交表单
            if (response.data.success) {
              let filePath = response.data.entity;
              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: "mk/mkCertNeduApply/upload.htm",
        headers: { "Content-Type": "multipart/form-data" },
        data: param
      });
    }
  }
};
</script>

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