<template>
  <div>
    <div class="tools">
      <div>
        <!--        <el-button v-print="'#printContent'" type="primary" icon="el-icon-printer" size="mini">打印</el-button>-->
        <!-- 线上考试导入成绩才有-->
        <el-button v-if="clazz.EXAMINATION == 1 && clazz.EXAMTYPE == 1" type="primary" icon="el-icon-upload2" size="mini" @click="importStuScore">导入学员成绩</el-button>
        <el-button type="primary" icon="el-icon-mic" size="mini" @click="downloadWord">导出</el-button>
      </div>
    </div>
    <div id="printContent" class="newform">
      <div class="h1">
        学员统计情况总表
      </div>
      <div class="tableFooter">
        <span></span>
        <span>报表日期:{{ formatDate(new Date()) }}</span>
      </div>
      <table class="table-dialog">
        <tr class="tab_tr">
          <td class="title">公司名称</td>
          <td class="title">任务名称</td>
        </tr>
        <tr class="tab_tr">
          <td class="title">{{ clazz.enterpriseName }}</td>
          <td class="title">{{ clazz.NAME }}</td>
        </tr>
        <tr class="tab_tr">
          <td class="title">培训时间</td>
          <td class="title">计划课时</td>
        </tr>
        <tr>
          <td class="title">{{ clazz.START_TIME? clazz.START_TIME.substring(0,10):'' }} 至 {{ clazz.END_TIME?clazz.END_TIME.substring(0,10):'' }}</td>
          <td class="title">{{ pd.SUMCLASSHOUR }}</td>
        </tr>
        <tr class="tab_tr">
          <td class="title">培训人数</td>
          <td class="title">合格人数</td>
        </tr>
        <tr>
          <td class="title">{{ students.length }}</td>
          <td class="title">{{ passStudent.length == 0 ? '0' : passStudent.length }}</td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: center">合格学员名单</td>
        </tr>
        <tr>
          <td colspan="6" style="padding:0">
            <table class="table-inside">
              <tr>
                <td class="title" style="width: 5%">序号</td>
                <td class="title" style="width: 15%">姓名</td>
                <td class="title" style="width: 20%">身份证</td>
                <td class="title" style="width: 15%">手机号</td>
                <td class="title" style="width: 10%">性别</td>
                <td class="title" style="width: 10%">完成学时</td>
                <td class="title" style="width: 10%">结业考试成绩</td>
              </tr>
              <template v-for="(item,index) in passStudent">
                <tr :key="index" >
                  <td class="title">{{ index+1 }}</td>
                  <td class="title">{{ item.NAME }}</td>
                  <td class="title">{{ item.USER_ID_CARD }}</td>
                  <td class="title">{{ item.PHONE }}</td>
                  <td class="title">{{ item.SEX_NAME }}</td>
                  <td class="title">{{ item.COMPLETE_CLASSHOUR == 0.0 ? 0 : parseFloat(item.COMPLETE_CLASSHOUR).toFixed(1) }}</td>
                  <td class="title">{{ item.STAGEEXAMSCORE>-1?item.STAGEEXAMSCORE:'不考试' }}</td>
                </tr>
              </template>
            </table>
          </td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: center">未合格学员名单</td>
        </tr>
        <tr>
          <td colspan="6" style="padding:0">
            <table class="table-inside">
              <tr>
                <td class="title" style="width: 5%">序号</td>
                <td class="title" style="width: 15%">姓名</td>
                <td class="title" style="width: 20%">身份证</td>
                <td class="title" style="width: 15%">手机号</td>
                <td class="title" style="width: 10%">性别</td>
                <td class="title" style="width: 10%">完成学时</td>
                <td class="title" style="width: 10%">结业考试成绩</td>
              </tr>
              <template v-for="(item,index) in unPassStudent">
                <tr :key="index" >
                  <td class="title">{{ index+1 }}</td>
                  <td class="title">{{ item.NAME }}</td>
                  <td class="title">{{ item.USER_ID_CARD }}</td>
                  <td class="title">{{ item.PHONE }}</td>
                  <td class="title">{{ getGenderByIdNumber( item.USER_ID_CARD ) }}</td>
                  <td class="title">{{ item.COMPLETE_CLASSHOUR == 0.0 ? 0 : parseFloat(item.COMPLETE_CLASSHOUR).toFixed(1) }}</td>
                  <template v-if="item.examnum > '0'">
                    <td class="title">{{ item.STAGEEXAMSCORE>-1?item.STAGEEXAMSCORE:'0分' }}</td>
                  </template>
                  <template v-else>
                    <td class="title">{{ item.STAGEEXAMSCORE>-1?item.STAGEEXAMSCORE:'未参加' }}</td>
                  </template>
                </tr>
              </template>
            </table>
          </td>
        </tr>
      </table>

    </div>
    <el-dialog :visible.sync="stuScoreVisible" append-to-body title="学员成绩导入" width="40%">
      <el-form ref="studentsDialogForm" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学员导入分数模板" prop="EXAMNAME">
              <el-button type="primary" @click="downloadStuScore">下载导入分数模板</el-button>
            </el-form-item>
            <el-form-item label="导入分数文件" prop="FILEP">
              <upload-file :file-list.sync="fileP" :limit="1" list-type="picture-card" accept=".xls"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="export-box">
        <h1> <span>导入结果</span></h1>
        <div class="studentNum" v-html="stuScoreResult"/>
      </div>
      <span slot="footer">
        <el-button @click="stuScoreVisible = false">关 闭</el-button>
        <el-button type="primary" @click="uploadPaperSave">上 传</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import UploadFile from '@/components/UploadFile'
import { upload } from '@/utils/upload'
import waves from '@/directive/waves' // waves directive
import dateformat from '@/utils/dateformat'
export default {
  components: { Pagination, UploadFile },
  directives: { waves },
  props: {
    id: {
      type: String,
      default() {
        return ''
      }
    },
    corpinfoId: {
      type: String,
      default() {
        return ''
      }
    },
    postId: {
      type: String,
      default() {
        return ''
      }
    },
    enterpriseName: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      clazz: {},
      stuScoreVisible: false,
      stuScoreResult: '',
      form: {},
      rules: {
        EXAMNAME: [{ required: false, message: ' ', trigger: 'blur' }],
        FILEP: [{ required: false }]
      },
      fileP: [],
      pd: {},
      students: [],
      passStudent: [],
      unPassStudent: []
    }
  },
  created() {
    this.getData()
    // this.getCurriculums()
    this.getStudents()
  },
  methods: {
    formatDate(date, column) {
      if (date) {
        return dateformat(date, 'YYYY年MM月DD日')
      } else {
        return ''
      }
    },

    uploadPaperSave() {
      this.$refs.studentsDialogForm.validate((valid) => {
        if (valid) {
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          if (!this.fileP[0]) {
            this.$message.warning('请上传文件')
            return
          }
          formData.append('FFILE', this.fileP[0].raw)
          formData.append('CLASS_ID', this.id)
          upload('/archives/stuScoreUpload', formData).then((res) => {
            if (res.code == 0) {
              this.$message.success('上传成功')
              if (res.successMsg) {
                this.stuScoreResult = res.successMsg
              }
            } else {
              this.$message.warning(res.msg)
            }
            this.getData()
          }).catch((e) => {
            console.log(e)
          })
        }
      })
    },
    /**
     * 按身份证号码获取性别
     */
    getGenderByIdNumber(idNumber) {
      if (idNumber) {
        let genderCode // 性别代码
        if (idNumber.length == 18) { // 二代身份证号码长度为18位（第17位为性别代码）
          genderCode = idNumber.charAt(16)
        } else if (idNumber.length == 15) { // 一代身份证号码长度为15位（第15位为性别代码）
          genderCode = idNumber.charAt(14)
        }
        if (genderCode && !isNaN(genderCode)) {
          if (parseInt(genderCode) % 2 == 0) {
            return '女'
          }
          return '男'
        }
      }
    },
    getData() {
      requestFN(
        '/archives/getStudentSigns',
        {
          CORPINFO_ID: this.corpinfoId,
          CLASS_ID: this.id,
          POST_ID: this.postId
        }
      ).then((data) => {
        this.passStudent = []
        this.unPassStudent = []
        this.clazz = Object.assign({ }, data.clazz)
        this.pd = Object.assign({ }, data.rpd)
        this.students = data.studentList
        this.students.map((item) => {
          // 线上考试
          if (this.clazz.EXAMINATION == 1 && this.clazz.EXAMTYPE == 0) {
            if (item.STAGEEXAMSTATE == '3') {
              this.passStudent.push(item)
            } else {
              this.unPassStudent.push(item)
            }
          }
          // 线下考试
          if (this.clazz.EXAMINATION == 1 && this.clazz.EXAMTYPE == 1) {
            if (item.STAGEEXAMSTATE == '3') {
              this.passStudent.push(item)
            } else {
              this.unPassStudent.push(item)
            }
          }
          if (this.clazz.EXAMINATION === 0) {
            this.passStudent.push(item)
          }
        })
      }).catch((e) => {
      })
    },
    importStuScore() {
      this.stuScoreVisible = true
      this.fileP = []
      this.stuScoreResult = ''
    },
    downloadStuScore() {
      this.$confirm('确定要下载模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportExcel()
      }).catch(() => {
      })
    },
    exportExcel() {
      // 导出表头
      const tableData = [['身份证号码，分数（保留一位小数），是否合格必填。注：是否合格选项：是或否'],
        ['学员姓名', '学员身份证号', '分数', '是否合格']
      ] // 表格表头
      this.students.forEach((item, index) => {
        var ISPASS = ''
        if (this.clazz.EXAMINATION == 1 && (this.clazz.EXAMTYPE == 0 || this.clazz.EXAMTYPE == 1)) {
          if (item.STAGEEXAMSTATE == '3') {
            ISPASS = '是'
          } else {
            ISPASS = '否'
          }
        }
        let rowData = []
        // 导出内容的字段
        rowData = [
          item.NAME,
          item.USER_ID_CARD,
          item.STAGEEXAMSCORE == -1 ? '0' : item.STAGEEXAMSCORE,
          ISPASS
        ]
        tableData.push(rowData)
      })
      const ws = this.XLSX.utils.aoa_to_sheet(tableData)
      const wb = this.XLSX.utils.book_new()
      this.XLSX.utils.book_append_sheet(wb, ws, '导入学员分数模版') // 工作簿名称
      this.XLSX.writeFile(wb, '导入学员分数模版.xls') // 保存的文件名
      this.$message.success('导出成功')
    },
    downloadWord() {
      this.$confirm('确定要导出pdf吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(config.httpurl + 'archives/studentsumtable?CLASS_ID=' + this.id + '&POST_ID=' + this.postId + '&CORPINFO_ID=' + this.corpinfoId)
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    }
  }
}

</script>

<style lang="scss" scoped>
  .tools {
    text-align: right;
  }
  .tableFooter {
    display: flex;
    justify-content: space-between;
    padding: 15px 0;
  }
  .dialogContent {
    .title {
      text-align: center;
    }
  }
</style>
