<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="MkCertEduApplyControl" style="margin-bottom: 8px; border-left: 3px solid; color: rgb(230, 162, 60);">
          <div role="alert" class="el-alert el-alert--warning">
            <div class="el-alert__content">
              <span class="el-alert__title">{{MkCertEduApplyControl}}</span>
             
            </div>
          </div>
        </div>
        
        
        <!-- timeLimit && timeLimit.in_time -->
        <div v-if="timeLimit && timeLimit.in_time">
          <el-button type="primary" @click="goApply();applyDialogVisible = true;">申请学历学习成果认证课程</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="ticket_no"
            label="准考证号"
            width="120">
          </el-table-column>
          <!-- <el-table-column
            prop="cert_no"
            label="证书编号"
            width="120">
          </el-table-column> -->
  >
          <el-table-column
            prop="cert_name"
            label="证书名称"
            width="140"
            >
          </el-table-column>
          <el-table-column
            prop="cert_course_code"
            label="课程代码"
            width="80">
          </el-table-column>
          <el-table-column
            prop="cert_course_name"
            label="课程名称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="done_course_name"
            label="已学课程"
            width="180">
          </el-table-column>
          <el-table-column
            prop="done_course_score"
            label="已学课程成绩"
            width="110">
          </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="verify1_remark"
            label="确认意见"
            width="140">
          </el-table-column>
          <el-table-column
            prop="verify2_remark"
            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>
        <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="160px">
              <el-row>
                <el-col :span="24">
                   <el-form-item label="选择专业" prop="major_id">
                    <el-select style="width:400px;" size="medium" v-model="item.major_id" filterable clearable placeholder="选择专业" @change="major_change">
                      <el-option v-for="item in majorList" :key="item.id" :label="item.major_name" :value="item.id"></el-option>
                   </el-select>
                  </el-form-item>
                  
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="选择学历证书" prop="cert_type_id">
                    <el-select style="width:400px;" size="medium" v-model="item.cert_type_id" filterable clearable placeholder="选择学历证书" >
                      <el-option v-for="item in certTypeList" :key="item.id" :label="item.cert_code +'-'+item.cert_name" :value="item.id"></el-option>
                   </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
               <el-row>
                <el-col :span="24">
                  <el-form-item label="选择免考课程" prop="nexam_course_id">
                    <el-select style="width:400px;" size="medium" v-model="item.nexam_course_id" filterable clearable placeholder="选择免考课程" @change="courseChange">
                      <el-option  label="--请选择--" value=""></el-option>
                      <el-option v-for="item in courseList" :key="item.id" :label="item.full_name" :value="item.id"></el-option>
                   </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                   <el-form-item label="附件">
                     <div style="width:400px">
                        <el-upload
                          :http-request = "customUpload"
                          action=""
                          class="upload-demo"
                          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"
                          >
                          <el-button size="small" type="primary">点击上传</el-button>
                          <div slot="tip" class="el-upload__tip" style="color:red">注意：毕业证书和成绩表图片请打包成rar或zip压缩文件上传，且不超过10MB</div>
                        </el-upload>

                        <!-- <el-upload
                          class="avatar-uploader"
                          action=""
                          :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                          <img v-if="imageUrl" :src="imageUrl" class="avatar">
                          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload> -->

                      </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <table style="margin-left:60px;" v-if="ready == true && courseList && courseList.length>0">
                    <thead>
                      <tr>
                        <th style="width:40px">序号</th>
                        <th style="width:250px">课程名称</th>
                        <th style="width:250px">已考课程名称</th>
                        <th style="width:260px">已考分数</th>
                        <th>&nbsp;</th>
                      </tr>
                    </thead>
                    <tr v-for="(i,index) in selectedCourseList" :key="i.id">
                      <td align="center">{{index+1}}</td>
                      <td align="center">
                        {{i.course_name}}
                      </td>
                      <td>
                        <el-input size="medium" v-model="i.course_name_input" placeholder="请输入已考课程名称" maxlength="100"></el-input>
                      </td>
                      <td>
                        <el-input size="medium" v-model="i.course_score_input" placeholder="请输入已考分数。多个分数用；分隔" maxlength="100"></el-input>
                      </td>
                      <td>
                        
                        
                      </td>
                    </tr>
                  </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 {
      loading: false,
      applyDialogVisible: false,
      timeLimit: null,
      MkCertEduApplyControl: null,
      pushTimeLimit: null,
      authTimeLimit: null,
      applyList: null,
      majorList: null,
      courseList: null,
      certTypeList: null,
      List: null,
      ready: false,
      selectedCourseList: [],
      uploadNeed: false,
      fileList: [],
      imageUrl:"",
      item: {
        major_id: "",
        std_cert_no: "",
        std_name: "",
        cert_type_id: "",
        nexam_course_id: "",
        course_scores: [{ value: "" }],
        course_names: [{ value: "" }],
        file_path: ""
      },
      itemRules: {
        major_id: [
          { required: true, message: "请选择专业", trigger: "blur" }
        ],
        std_name: [
          { required: true, message: "请输入考试姓名", trigger: "blur" }
        ],
        cert_type_id: [
          { required: true, message: "请选择学历证书", trigger: "blur" }
        ],
        nexam_course_id: [
          { required: true, message: "请选择免考课程", trigger: "blur" }
        ]
      }
    };
  },

  async mounted() {
    this.loading = true;
    this.init();
    this.loading = false;
  },
  methods: {
    //初始化列表查询
    async init() {
      this.selectedCourseList = [];
      let res = await this.$http.post(
        "/mk/mkCertEduApply/listByStd.htm",
        {},
        this.$http.headers.FORM
      );
      this.timeLimit = res.data.map.timeLimit;
      this.pushTimeLimit = res.data.map.pushTimeLimit;
      this.authTimeLimit = res.data.map.authTimeLimit;
      this.MkCertEduApplyControl = res.data.map.MkCertEduApplyControl;
      
      this.applyList = res.data.map.applyList;
    },
    //跳转申请页面
    async goApply() {
      for (const key in this.item) {
        if (this.item.hasOwnProperty(key)) {
          this.item[key] = "";
        }
      }

      this.courseList = [];
      this.course_scores = [];
      this.course_names = [];
      this.selectedCourseList = [];
      this.fileList=[];
      this.uploadNeed=false;

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

      //默认选择第一个
      if (this.majorList.length > 0) {
        this.item.major_id = this.majorList[0].id;
        this.major_change(this.item.major_id);
      }
      if (this.certTypeList.length > 0) {
        this.item.cert_type_id = this.certTypeList[0].id;
        // this.major_change(this.item.cert_type_id);
      }
      this.loading = false;
      return this.item;
    },

    async major_change(major_id) {
      if (!major_id) {
        this.courseList = null;
        return;
      }
      this.loading = true;
      await this.reqCourse(major_id);
      this.ready = true;
      this.loading = false;
    },

    async courseChange(course_id) {
      this.selectedCourseList = [];
      this.$nextTick(() => {
        this.selectedCourseList.push(
          this.courseList.find(item => {
            return item.id == course_id;
          })
        );
      });
    },

    async reqCourse(major_id) {
      // let preEdu = _.find(this.certTypeList, { id: cert_type_id });
      // this.item.cert_no = preEdu.cert_no;
      this.courseLoading = true;
      let resp = await this.$http.post(
        // "mk/mkCertEduApply/listCourse.htm",
        "pl/plMajor/listMajorCourse.htm",
        this.Qs.stringify({
          // cert_type_id: cert_type_id,
          major_id: major_id
        }),
        this.$http.headers.FORM
      );
      this.courseList = resp.data.array;

      if(this.courseList.length > 1){
        this.item.nexam_course_id = ""
      }
    },

    async submit() {
       if(!this.item.file){
          this.alert("请上传图片或者压缩文件");
          return ;
        }

      this.confirm("确定提交申请?", "操作确定", {
        confirm: function() {
          
          if (this.uploadNeed) {
            // if(this.fileList.length == 0){
            //   this.alert("请上传图片或者压缩文件");
            //   return ;
            // }
            this.$refs.upload.submit();
          } else {
            
            this.saveData();
          }
        }
      });
    },
    //保存
    async saveData(file_path) {
      if(!String(this.item.nexam_course_id)){
        this.alert("请选择免考课程");
        return;
      }
      let cloneItem = _.cloneDeep(this.item);
      if (file_path){ 
        cloneItem.file_path = file_path;
      }else{
        if(this.uploadNeed){
          this.alert("请上传图片"); 
          return;
        }
        
      }
      let apply_ids = [];
      apply_ids.push(this.item.id);

      let course_ids = [];
      let course_names = [];
      let course_scores = [];

      for (let i = 0; i < this.selectedCourseList.length; i++) {
        const element = this.selectedCourseList[i];
        let course_id = element.id;
        let course_name = element.course_name_input;
        let course_score = element.course_score_input || "";

        if (course_name /*&& course_scores*/) {
           if (String(this.item.id)) apply_ids.push(this.item.id);
          course_ids.push(course_id);
          course_names.push(course_name);
          course_scores.push(course_score);
        } else if (!course_name) {
          this.alert("请填写第" + (i + 1) + "行已考名称!");
          return;
        }
      }

      // this.courseList.forEach((element, index) => {
      //   let course_id = element.id;
      //   let course_name = element.course_name_input;
      //   let course_score = element.course_score_input;

      //   if (course_name /*&& course_scores*/) {
      //     if (this.item.id + "") apply_ids.push(this.item.id);
      //     course_ids.push(course_id);
      //     course_names.push(course_name);
      //     course_scores.push(course_score);
      //   } else if (!course_name) {
      //     this.alert("请填写第" + (index + 1) + "行已考名称!");
      //     return;
      //   }
      //   // else if (!course_scores) {
      //   //   this.alert("请填写第" + (index + 1) + "已考分数!");
      //   //   return;
      //   // }
      // });

      cloneItem.apply_ids = apply_ids.join();
      cloneItem.course_ids = course_ids.join();
      cloneItem.course_names = course_names.join();
      cloneItem.course_scores = course_scores.join();
      let { data } = await this.$http.post(
        "mk/mkCertEduApply/apply.htm",
        this.Qs.stringify(cloneItem),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.alert("提交成功");
        this.init();
        this.$nextTick(() => {
          this.applyDialogVisible = false;
          this.init();
        });
      } else {
        this.alert(data.errorMsg);
      }
    },
    async back(row){
       let { data } = await this.$http.post(
        "mk/mkCertEduApply/back.htm",
        this.Qs.stringify({ id: row.id }),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.init();
      } else {
        this.alert(data.errorMsg);
      }

    },

    async goEdit(row) {
      let { data } = await this.$http.post(
        "mk/mkCertEduApply/get.htm",
        this.Qs.stringify({ id: row.id }),
        this.$http.headers.FORM
      );
      if (data.success) {
        let item = await this.goApply();
        this.item = data.entity;
        this.ready = false;
        await this.major_change(item.major_id);
        this.courseList = _.filter(this.courseList, {
          id: this.item.cert_course_id
        });
        this.item.major_id = item.major_id;
        if (this.courseList[0]) {
          this.item.nexam_course_id = this.courseList[0].id;
          this.courseList[0].course_name_input = this.item.done_course_name;
          this.courseList[0].course_score_input = this.item.done_course_score;
        }

        this.courseList = this.courseList;
        this.selectedCourseList = this.courseList;

        //处理附件的初始化

        this.fileList = [{name:`${this.item.file_path}`,url:`${window.uploadServerUrl}${this.item.file_path}`}]
        this.item.file = this.item.file_path;
        this.uploadNeed = false;
        this.$nextTick(() => {
          this.ready = true;
          this.applyDialogVisible = true;
        });
      } else {
        this.alert(data.errorMsg);
      }
    },

    handleRemove(file, fileList) {
      this.item.file = null;
      this.uploadNeed = true;
    },
    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 isZIP = file.type === "application/x-zip-compressed";
      // const isRAR = file.type === "application/x-rar-compressed";//暂时不用
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isLt10M = file.size / 1024 / 1024 < 10;

      let rtn = true;
      /*
      if(isZIP){
        if(!isLt10M){
          this.alert("上传压缩文件大小不能超过 10MB!");
          rtn = false;
        }
      }else{
        if (!isJPG && !isJPEG && !isPNG ) {
          this.alert("上传图片必须是JPG/JPEG/PNG格式或者ZIP打包文件");
          rtn = false;
          return rtn;
        }
        if (!isLt2M) {
          this.alert("上传图片大小不能超过 2MB!");
          rtn = false;
        }
      }
      */
     
      return rtn;
    },
    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/mkCertEduApply/upload.htm",
        headers: { "Content-Type": "multipart/form-data" },
        data: param
      });
    },
    handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

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