<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" class="el-alert el-alert--warning" v-if="timeLimit && timeLimit.start_time && timeLimit.end_time ">
            <div class="el-alert__content">
              <span class="el-alert__title">前置学历在线申请时间：{{timeLimit.start_time}} 到 {{timeLimit.end_time}}</span>
             
            </div>
          </div>
        </div>
        <div v-if="timeLimit && timeLimit.in_time">
          <el-button type="primary" @click="goApply()">申请</el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="applyList"
          style="width: 100%">
          <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            prop="std_name"
            label="姓名"
            width="80">
          </el-table-column>
          <el-table-column
            prop="std_cert_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="source_unit"
            label="毕业学校"
            width="140"
            >
          </el-table-column>
          <el-table-column
            prop="out_school_date"
            label="毕业时间 "
            width="120">
          </el-table-column>
          <el-table-column
            prop="status_text"
            label="状态"
            width="100">
          </el-table-column>
          <el-table-column
            prop="apply_time"
            label="申请时间"
            width="100">
          </el-table-column>
           <el-table-column
            prop="remark"
            label="备注"
            width="150">
          </el-table-column>
           <el-table-column
            prop=""
            label="操作"
            width="100">
            <template slot-scope="scope">
                <div v-if="scope.row.status == 0"> 
                  <el-button @click="goEdit(scope.row)">修改申请信息</el-button>
                </div>
              </template>
          </el-table-column>

        </el-table>
        <el-dialog title="前置学历申请" width="800px" :visible.sync="applyDialogVisible">
            <el-form ref="itemForm" :model="item" :rules="itemRules" label-width="200px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="考生姓名" prop="std_name">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.std_name" disabled readonly></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item label="考生身份证号" prop="std_cert_no">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.std_cert_no" disabled readonly></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item label="准考证号" prop="ticket_no">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.ticket_no" disabled readonly></el-input>
                    </div>
                  </el-form-item>
                 
                  <el-form-item label="学历层次" prop="edu_level">
                    <div style="width:200px">
                       <el-select size="medium" v-model="item.edu_level" filterable clearable placeholder="请选择学历证书分类" >
                          <el-option v-for="item in certLevelArray" :key="item.dict_value" :label="item.dict_text" :value="item.dict_value"></el-option>
                      </el-select>
                    </div>
                  </el-form-item>
                  <!-- <el-form-item label="学历证书分类" prop="cert_type">
                    <div style="width:200px">
                       <el-select size="medium" v-model="item.cert_type" filterable clearable placeholder="请选择学历证书分类" >
                          <el-option v-for="item in certTypeCatalogArray" :key="item.dict_value" :label="item.dict_text" :value="item.dict_value"></el-option>
                      </el-select>
                    </div>
                  </el-form-item> -->
                  <el-form-item label="学历证书" prop="cert_type_id">
                    <div style="width:200px">
                       <el-select size="medium" v-model="item.cert_type_id" filterable clearable placeholder="请选择学历证书分类" >
                          <el-option v-for="item in certTypeArray" :key="item.id" :label="item.cert_code + '-'+item.cert_name" :value="item.id"></el-option>
                      </el-select>
                    </div>
                  </el-form-item>
                  <el-form-item label="学历证件号" prop="cert_no">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.cert_no"></el-input>
                    </div>
                  </el-form-item>
                  <!-- <el-form-item label="外省准考证" prop="input_cert_no">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.input_cert_no"></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item label="外省考生姓名" prop="input_std_name">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.input_std_name"></el-input>
                    </div>
                  </el-form-item> -->
                  <el-form-item label="毕业学校" prop="source_unit">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.source_unit"></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item label="专业名称" prop="major_name">
                    <div style="width:200px">
                      <el-input size="medium" v-model="item.major_name"></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item label="入学日期" prop="in_school_date">
                    <div style="width:200px">
                      <el-date-picker
                        v-model="item.in_school_date"
                        type="date"
                        placeholder="选择入学日期">
                      </el-date-picker>
                    </div>
                  </el-form-item>
                  
                  <el-form-item label="毕业日期" prop="out_school_date">
                    <div style="width:200px">
                      <el-date-picker
                        v-model="item.out_school_date"
                        type="date"
                        placeholder="选择毕业日期">
                      </el-date-picker>
                    </div>
                  </el-form-item>

                  <el-form-item label="附件(2张)" prop="files">
                    <el-upload
                        :http-request = "customUpload"
                        class="upload-demo"
                        ref="upload"
                        action=""
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :before-upload="beforeUpload"
                        :before-remove="beforeRemove"
                        multiple
                        :limit="2"
                        :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">说明：上传【学历证书】和【身份证】原件照片，<br>只能上传jpg/jpeg/png文件，且不超过2MB</div>
                      </el-upload>
                  </el-form-item>

                 <el-form-item label="备注" prop="files">
                   <el-input
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 4}"
                      maxlength="100"
                      v-model="item.remark">
                    </el-input>
                 </el-form-item>


                
                </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,
      applyList: null,

      std: null,

      certLevelArray: null,
      certTypeArray: null,
      certTypeCatalogArray: null,

      uploadNeed:false,
      fileList: [],
      item: {
        std_name: "",
        std_cert_no: "",
        ticket_no: "",
        cert_no: "",
        cert_type_id: "",
        edu_level: "",
        edu_type: "",
        input_cert_no: "",
        input_std_name: "",
        in_school_date: "",
        out_school_date: "",
        source_unit: "",
        major_name: "",
        time_config_id: "",

        files: null,
        edu_cert_file_path: "",
        edu_verify_rep_file_path: "",
        fam_reg_file_path: "",
        pub_verify_file_path: "",
        std_cert_file_path: ""
      },
      itemRules: {
        std_name: [
          { required: true, message: "请输入考生姓名", trigger: "blur" }
        ],
        std_cert_no: [
          { required: true, message: "请输入考生身份证", trigger: "blur" }
        ],
        ticket_no: [
          { required: true, message: "请输入本省准考证", trigger: "blur" }
        ],
        cert_no: [
          { required: true, message: "请输入证件编号", trigger: "blur" }
        ],
        cert_type_id: [
          { required: true, message: "请输入证件类型", trigger: "blur" }
        ],
        edu_level: [
          { required: true, message: "请输入学历层次", trigger: "blur" }
        ],
        edu_type: [
          { required: true, message: "请输入学历分类", trigger: "blur" }
        ],
        // input_cert_no: [
        //   { required: true, message: "请输入外省准考证", trigger: "blur" }
        // ],
        // input_std_name: [
        //   { required: true, message: "请输入外省准考证", trigger: "blur" }
        // ],
        source_unit: [
          { required: true, message: "请输入毕业学校", trigger: "blur" }
        ],
        major_name: [
          { required: true, message: "请输入专业", trigger: "blur" }
        ],
        in_school_date: [
          { required: true, message: "请输入入学日期", trigger: "blur" }
        ],
        out_school_date: [
          { required: true, message: "请输入毕业日期", trigger: "blur" }
        ],
        // files: [
        //   { required: true, message: "请上传学历证书和身份证", trigger: "blur" }
        // ],
        edu_cert_file_path: [
          { required: true, message: "请上传学历证书", trigger: "blur" }
        ],
        std_cert_file_path: [
          { required: true, message: "请上传身份证", trigger: "blur" }
        ]
      }
    };
  },

  async mounted() {
    this.loading = true;
    this.init();
    this.loading = false;
  },
  methods: {
    //初始化列表查询
    async init() {
      let res = await this.$http.post(
        "/mk/mkPreEduApply/listByStd.htm",
        {},
        this.$http.headers.FORM
      );
      this.timeLimit = res.data.map.timeLimit;
      this.applyList = res.data.map.applyList;
      this.item.time_config_id = this.timeLimit.id;
    },

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

      this.fileList = [];
      this.item.std_name = this.stdReg.std_name;
      this.item.ticket_no = this.stdReg.ticket_no;
      this.item.std_cert_no = this.stdReg.cert_no;
      this.loading = true;
      let { data } = await this.$http.post(
        "/mk/mkPreEduApply/toApply.htm",
        {},
        this.$http.headers.FORM
      );
      this.certLevelArray = data.map.certLevelArray;
      this.certTypeArray = data.map.certTypeArray;
      this.certTypeCatalogArray = data.map.certTypeCatalogArray;

      this.loading = false;
      this.applyDialogVisible = true;
    },

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

    //   // 上传-->customUpload-->fileUpload-->上传成功-->返回上传附件路径 调用saveDate保存数据
    //   if (this.uploadNeed) {
    //     this.$refs.upload.submit(); 
    //   }else{
    //     this.saveData();
    //   }
    // },
    async goEdit(row){
      alert("TODO---");
      let { data } = await this.$http.post(
        "mk/mkPreEduApply/get.htm",
        this.Qs.stringify({id:row.id}),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.certLevelArray = data.map.certLevelArray;
        this.certTypeArray = data.map.certTypeArray;
        this.certTypeCatalogArray = data.map.certTypeCatalogArray;

        this.item = data.map.entity;

        //图片处理
        this.fileList = [];
        this.fileList.push({name:`学历证件照片`,url:`${window.uploadServerUrl}${this.item.edu_cert_file_path}`});
        this.fileList.push({name:`考生身份证件照片`,url:`${window.uploadServerUrl}${this.item.std_cert_file_path}`});
        this.applyDialogVisible = true;

      }
      else{
        this.alert(data.errorMsg);
      }

    },
    
    async submit() {
      let startTime = new Date(Date.parse(this.item.in_school_date));
      let endTime = new Date(Date.parse(this.item.out_school_date));
      if( startTime >=endTime ){
        this.alert("入学时间必须小于毕业时间");
        return;
      }
      this.$refs["itemForm"].validate(valid => {
        if (valid) {
          if (this.uploadNeed) {
            this.$refs.upload.submit(); 
        }else{
          this.saveData();
        }
          return true;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //保存
    async saveData() {
      var cloneItem = JSON.parse(JSON.stringify(this.item));
      delete cloneItem['files'];
      let { data } = await this.$http.post(
        "mk/mkPreEduApply/apply.htm",
        this.Qs.stringify(cloneItem),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.alert("提交成功");
        this.init();
        this.$nextTick(() => {
          this.applyDialogVisible = false;
        });
      } else {
        this.alert(data.errorMsg);
      }
    },
   
    customUpload(file) {
      //  std_cert_file: [],
      // edu_cert_file: [],
      let this_ = this;
       this.$refs["itemForm"].validate(valid => {
        if (valid) {
          this.fileUpload(file).then(response => {
            //上传成功提交表单
            if (response.data.success) {
              let filePath = response.data.entity;
              for (let i = 0; i < this_.item.files.length; i++) {
                const element = this_.item.files[i];
                if(element.uid == file.file.uid ){
                   if(i == 0){
                      this_.item.edu_cert_file_path = filePath;
                    }else if(i == 1){
                      this_.item.std_cert_file_path = filePath;
                    }
                  //最后一个图片
                  if(this_.item.files.length == (i+1)){
                      this_.uploaded = true;
                      setTimeout(() => {
                        this_.saveData(filePath);
                      }, 500);
                  }
                }
                
              }
              
            } 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/mkPreEduApply/upload.htm",
        headers: { "Content-Type": "multipart/form-data" },
        data: param
      });
    },
     handleRemove(file, fileList) {
      if (fileList.length == 0) {
        this.item.files = null;
      }
      this.fileList = [];
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          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.files = fileList;
        this.uploadNeed = true;
 
      }else{
        this.item.files = [];
        this.uploadNeed = false;
 
      }
    },
 
  }
};
</script>

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