<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 头部内容 -->
      <div class="top-content">
        <div class="title" :title="currentRow.trainingName">培训主题名称：{{ currentRow.trainingName | truncate(25) }}
        </div>
        <div class="lf-line"></div>
        <div class="title">培训对象：{{ currentRow.studyObject }}</div>
        <div class="lf-line"></div>
        <div class="title">培训级别：{{ currentRow.trainingLevel }}</div>
        <div class="lf-line"></div>
        <div class="title">培训日期：{{ currentRow.trainingDate }}</div>
        <div class="lf-line"></div>
        <div class="title">应到人数：{{ shouldNumber }}人</div>
        <div class="lf-line"></div>
        <div class="title">实到人数：{{ actualNumber }}人</div>
      </div>
    </el-card>
    <el-row :gutter="20">
      <el-col :span="24" :offset="0">
        <el-form ref="form" :model="form" :rules="rules"
                 label-width="80px"
        >
          <el-card class="box-card" header="现场照片:">
            <el-button type="primary" size="mini" @click="submitForm" style="margin-bottom: 10px;" v-preventReClick="5000">确 定</el-button>
            <uploadFile :limit="5" :accept="`.png, .jpg, .jpeg`" :uploadList.sync="form.scenePhotoList"
                        @picturePreview="picturePreview"
                        multiple
                        ref="uploadFile"
                        :on-exceed="handleExceed"
                        v-on:delFile="delFile"
            ></uploadFile>
          </el-card>
        </el-form>
      </el-col>
    </el-row>

    <!-- 表单  -->
    <el-form :model="queryParams" inline size="mini">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入姓名"  v-no-whitespace/>
      </el-form-item>
      <el-form-item style="width: 30%">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        <el-button icon="el-icon-download" @click="handleExport">导出数据</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table :data="tableData" fit highlight-current-row style="width: 100%">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="item in taskTableHeader"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 图片查看弹窗 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" height="650px" :src="dialogImageUrl" alt />
    </el-dialog>
    <!-- 文件预览弹窗 -->
    <el-dialog title="文件预览" :visible.sync="viewOpen" width="90%" append-to-body>
      <div style="width: 100%;height:720px">
        <bns-kkFile-preview :items="filePreview" look-type="minio"></bns-kkFile-preview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selectScenePhoto, selectTrainingDataHeader,
  selectTrainingDataList,
  uploadScenePhoto
} from '@/api/educationalTraining/resourceAdministration'
import uploadFile from '@/views/pro/admissionRequest/uploadFile.vue'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'
import { getFileData } from '@/utils/bonus'

export default {
  components: { bnsKkFilePreview, uploadFile },
  data() {
    return {
      showSearch: true,
      currentRow: {}, // 当前行数据
      trainTopicName: '歇息', // 培训主题名称
      trainObject: '外委单位', // 学习对象
      trainLevel: '公司级', // 培训级别
      trainDate: '2021-08-01', // 培训日期
      shouldNumber: '30', // 应到人数
      actualNumber: '30', // 实到人数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        id: ''
      },
      total: 0, // 总条数
      // 列表-表格头
      taskTableHeader: [
        { prop: 'name', label: '姓名' },
        { prop: 'sex', label: '性别' },
        { prop: 'idCard', label: '身份证号码' },
        { prop: 'phone', label: '联系方式' },
        { prop: 'proName', label: '工程名称' },
        { prop: 'consName', label: '承包商名称' },
        { prop: 'post', label: '岗位' },
        { prop: 'workType', label: '工种' },
        { prop: 'isSign', label: '是否签到' },
        { prop: 'signTime', label: '签到时间' },
        { prop: 'score', label: '考试成绩' }
      ],
      // 列表-数据
      tableData: [],
      fileList: [], // 上传图片列表
      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      viewOpen: false,
      filePreview: {},
      form: {
        id: '',
        scenePhotoList: []
      },
      rules: {
        fileList: [
          { required: true, message: '请上传现场照片', trigger: 'blur' }
        ]
      },
      delFileIds: []
    }
  },
  created() {
    // 获取路由query 传递过来 JSON.parse(this.$route.query.data)
    this.currentRow = this.$route.query
    console.log('学习任务数据', this.currentRow)
    if (this.currentRow.studyObject && this.currentRow.studyObject == '内部人员') {
      this.taskTableHeader.splice(4, 4)
    }
    this.getList()
    this.selectScenePhoto()
    this.selectTrainingDataHeader()
  },
  filters: {
    truncate(value, length) {
      if (!value) return ''
      if (value.length <= length) return value
      return value.substring(0, length) + '...'
    }
  },
  methods: {
    getFileData,
    selectTrainingDataHeader() {
      selectTrainingDataHeader({id: this.currentRow.id}).then(response => {
        this.shouldNumber = response.totalNum
        this.actualNumber = response.notSign
        console.log('表头', response)
      })
    },
    // 查询
    handleQuery() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.name = ''
      this.getList()
    },
    // 导出
    handleExport() {
      console.log('导出')
    },
    // 获取列表
    getList() {
      try {
        console.log('查询参数-列表', this.queryParams)
        this.queryParams.id = this.currentRow.id
        selectTrainingDataList(this.queryParams).then((res) => {
          console.log('获取列表', res)
          this.tableData = res.rows
          this.total = res.total
        })
      } catch (error) {
        console.log('获取列表失败', error)
      }
    },
    // 上传图片超出限制
    handleExceed(files, fileList) {
      // 提示先删除再上传
      this.$message.error('最多上传5张照片')
    },
    //上传组件-图片查看
    picturePreview(file) {
      console.log(file)
      //判断文件类型图片显示
      if (file.fileType === 'image') {
        this.dialogImageUrl = file.fileUrl
        this.viewOpen = false
        this.dialogVisible = true
      } else {
        this.filePreview = file
        this.dialogVisible = false
        this.viewOpen = true
      }
    },
    selectScenePhoto() {
      this.form.scenePhotoList = []
      selectScenePhoto({id:this.currentRow.id}).then(response => {
        console.log('现场照片', response)
        this.form.scenePhotoList = response.data
      })
    },
    delFile(e) {
      console.log(e)
      if (!this.delFileIds.includes(e)) {
        this.delFileIds.push(e)
      }
      console.log(this.delFileIds)
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const reqData = new FormData()
          this.form.id = this.currentRow.id
          this.form.delFileIds = this.delFileIds.join(",");
          reqData.append('params', JSON.stringify(this.form))
          Promise.all([
            this.getFileData(this.form.scenePhotoList)
          ]).then(([scenePhotoList]) => {
            if (!scenePhotoList || scenePhotoList.length === 0) {
              reqData.append('scenePhotoList', new Blob())
            } else {
              scenePhotoList.forEach(item => reqData.append('scenePhotoList', item))
            }
            uploadScenePhoto(reqData).then(async response => {
              this.$modal.msgSuccess('上传成功')
              this.fileList = []
              await this.selectScenePhoto()
              await this.$refs.uploadFile.assign()
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}

.top-content {
  display: flex;
  justify-content: space-evenly;;
  padding: 10px;

  .title {
    font-size: 15px;
    font-weight: bold;
  }

  .lf-line {
    width: 2px;
    height: 20px;
    background-color: #ccc;
    margin: 0 20px;
  }
}
</style>
