<template>
  <div class="sb-container" v-if="chapInfo && chapInfo.chapterInfo">
    <div class="steps-box" v-for="(step, stepI) in toolChoose()" :key="stepI">
      <div class="step-title">
        <div class="step">
          <span>步骤{{ stepI + 1 }}</span>
        </div>
        <div
          class="do"
          v-if="isCloseList[stepI] && worksStudent[stepI] && worksStudent[stepI].length > 4"
          @click="contract(stepI)"
          :class="{ close: isCloseList[stepI] && isCloseList[stepI].isClose == '1' }"
        >
          {{ isCloseList[stepI].isClose == '1' ? '展开' : '收缩' }}
        </div>
      </div>
      <div class="tool-box" v-if="tools[step.tool[0]] && canWork.indexOf(step.tool[0]) !== -1" @click="addImg($event)">
        <div class="tool-img"><img :src="tools[step.tool[0]].img" /></div>
        <div class="tool-name">{{ tools[step.tool[0]].name }}</div>
        <input
          type="file"
          accept="video/mp4, video/quicktime, video/x-msvideo,image/*"
          style="display: none"
          multiple
          @change="beforeUpload($event, step.tool[0], stepI)"
          v-if="step.tool[0] === 50"
        />
        <input
          type="file"
          accept="video/mp4, video/quicktime, video/x-msvideo,image/*"
          style="display: none"
          @change="beforeUpload($event, step.tool[0], stepI)"
          v-else
        />
      </div>
      <div
        class="tool-box"
        v-else-if="tools[step.tool[0]] && canWork2.indexOf(step.tool[0]) !== -1"
        @click="addWork(step.tool[0], stepI, step)"
      >
        <div class="tool-img"><img :src="tools[step.tool[0]].img" /></div>
        <div class="tool-name">{{ tools[step.tool[0]].name }}</div>
      </div>
      <div class="tool-box" v-else-if="tools[step.tool[0]]">
        <div class="tool-img"><img :src="tools[step.tool[0]].img" /></div>
        <div class="tool-name">{{ tools[step.tool[0]].name }}</div>
      </div>
      <div
        class="works-box"
        v-if="isWorkTool.indexOf(step.tool[0]) !== -1 && worksStudent[stepI] && worksStudent[stepI].length"
      >
        <div class="title">作业预览</div>
        <div class="works">
          <Works
            class="work"
            v-for="(work, workI) in isCloseList[stepI].isClose == 0
              ? worksStudent[stepI]
              : worksStudent[stepI].slice(0, 4)"
            :key="stepI + '-' + workI"
            :work="work"
          >
          </Works>
        </div>
      </div>
      <div
        class="no-works-box"
        v-if="isWorkTool.indexOf(step.tool[0]) !== -1 && noWorksS[stepI] && noWorksS[stepI].length"
      >
        <div class="title">未提交</div>
        <div class="no-works-box-students">
          <div
            v-for="(student, noI) in noWorksS[stepI]"
            :key="stepI + '-' + noI"
            class="student"
            @click="teacherSubmit(step.tool[0], student, $event, step)"
          >
            {{ student.student }}
            <input
              v-if="canWork.indexOf(step.tool[0]) !== -1"
              type="file"
              accept="video/mp4, video/quicktime, video/x-msvideo,image/*"
              style="display: none"
              @change="beforeUpload2($event, stepI)"
            />
          </div>
        </div>
      </div>
    </div>
    <div v-if="!toolChoose().length" class="noMssage">
      <img src="@/assets/images/course/isNoMessage.png" />
    </div>
    <div v-if="proVisible" class="mask">
      <div class="progressBox">
        <div class="lbox"><img src="@/assets/images/loading.gif" />上传中，请稍后</div>
        <div style="margin-bottom: 10px" v-if="pVisible">
          <span>{{ isFinishSize }}M</span> / <span>{{ isAllSize }}M</span>
        </div>
        <el-progress
          :text-inside="true"
          :stroke-width="20"
          :percentage="progress"
          style="width: 80%"
          v-if="pVisible"
        ></el-progress>
      </div>
    </div>
    <answerPanel
      v-if="answerPanelVisible"
      @setPanelVisible="setPanelVisible"
      :panelVisible="answerPanelVisible"
      :courseid="courseid"
      :courseType="courseType"
      :taskCount="taskCount"
      :toolindex="toolindex"
      :isTeacher="isTeacher"
      :answerQ="answerQ"
      :sStudent="sStudent"
    ></answerPanel>
    <askPanel
      v-if="askPanelVisible"
      @setAskPanelVisible="setAskPanelVisible"
      :panelVisible="askPanelVisible"
      :courseid="courseid"
      :courseType="courseType"
      :taskCount="taskCount"
      :toolindex="toolindex"
      :isTeacher="isTeacher"
      :askJson="askJson"
      :sStudent="sStudent"
    ></askPanel>
    <choosePanel
      v-if="choosePanelVisible"
      @setChoosePanelVisible="setChoosePanelVisible"
      :panelVisible="choosePanelVisible"
      :courseid="courseid"
      :courseType="courseType"
      :taskCount="taskCount"
      :toolindex="toolindex"
      :isTeacher="isTeacher"
      :chooseJson="chooseJson"
      :sStudent="sStudent"
    ></choosePanel>
  </div>
</template>

<script>
import '@/assets/js/aws-sdk-2.235.1.min.js'
import * as imageConversion from 'image-conversion'
import {
  getCourseWorks,
  getCourseWorksStudentJuri,
  addCourseWorksR,
  addCourseWorksTeacher,
  addCourseWorks5,
  addCourseWorksPl
} from '@/api/course'
import { tools } from '@/const/index'
import Works from './works.vue'
import { mapGetters } from 'vuex'
import answerPanel from './answerPanel.vue'
import askPanel from './askPanel.vue'
import choosePanel from './choosePanel.vue'

export default {
  props: {
    chapInfo: {
      type: Object,
      default: () => {}
    },
    courseDetail: {
      type: Object,
      default: () => {}
    },
    courseType: {
      type: Number,
      default: 0
    },
    taskCount: {
      type: Number,
      default: 0
    },
    courseid: {
      type: String,
      default: ''
    },
    tcid: {
      type: String,
      default: ''
    },
    oid: {
      type: String,
      default: ''
    },
    isLoading: {
      type: Boolean
    },
    answerPanelVisible: {
      type: Boolean
    },
    askPanelVisible: {
      type: Boolean
    },
    choosePanelVisible: {
      type: Boolean
    }
  },
  components: {
    Works,
    answerPanel,
    askPanel,
    choosePanel
  },
  data() {
    return {
      worksStudent: [],
      isWorksS: [],
      isCloseList: [],
      noWorksS: [],
      isWorkTool: [16, 32, 57, 4, 45, 15, 1, 3, 6, 7, 26, 41, 47, 48, 52, 50, 40, 63], //, 49
      canWork: [16, 50], //, 49
      canWork2: [15, 4, 45],
      fileType: 0,
      tools: tools,
      proVisible: false,
      pVisible: false,
      progress: 0,
      isFinishSize: 0,
      isAllSize: 0,
      sTool: 0,
      sStudent: {},
      isTeacher: false,
      toolindex: 0,
      answerQ: '',
      askJson: {},
      chooseJson: {}
    }
  },
  watch: {
    courseid(newValue, oldValue) {
      this.getWorks()
    },
    courseType(newValue, oldValue) {
      this.getWorks()
    },
    taskCount(newValue, oldValue) {
      this.getWorks()
    },
    isLoading(newValue) {
      if (newValue) {
        this.getWorks()
      }
    },
    answerPanelVisible(newValue) {
      if (!newValue) {
        this.getWorks()
      }
    },
    askPanelVisible(newValue) {
      if (!newValue) {
        this.getWorks()
      }
    },
    choosePanelVisible(newValue) {
      if (!newValue) {
        this.getWorks()
      }
    },
    chapInfo: {
      deep: true,
      handler(newValue) {
        if (Object.keys(newValue).length !== 0) {
          this.getWorks()
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userinfo']),
    toolChoose() {
      return () => {
        let toolchoose = this.chapInfo.chapterInfo[0].taskJson[this.taskCount].toolChoose
        toolchoose = toolchoose.filter(el => {
          return el.tool.length
        })
        return toolchoose
      }
    }
  },
  methods: {
    setPanelVisible(bool) {
      this.$emit('update:answerPanelVisible', bool)
    },
    setAskPanelVisible(bool) {
      this.$emit('update:askPanelVisible', bool)
    },
    setChoosePanelVisible(bool) {
      this.$emit('update:choosePanelVisible', bool)
    },
    arrayToArray(arrayo, arrayt) {
      const array1 = arrayo
      const array2 = arrayt

      const commonElements = []

      for (let i = 0; i < array1.length; i++) {
        for (let j = 0; j < array2.length; j++) {
          if (array1[i] === array2[j]) {
            commonElements.push(array1[i])
          }
        }
      }
      return commonElements
    },
    getWorks() {
      // 教师查看全部作业
      const params = {
        cid: this.courseid,
        s: this.courseType,
        t: this.taskCount
      }
      getCourseWorks(params)
        .then(res => {
          const works = res[0]
          const f = res[3]
          const steps = this.chapInfo.chapterInfo[0].taskJson[this.taskCount].toolChoose
          const worksStudent = []
          const isCloseList = []
          const groupStudent = []
          const groupStudentUid = []
          const isWorksS = []
          const wordPan = ['PDF', 'DOC', 'DOCX', 'PPT', 'PPTX', 'XLSX', 'XLS']
          const videoPan = [
            'AVI',
            'NAVI',
            'MPEG',
            'ASF',
            'MOV',
            'WMV',
            '3GP',
            'RM',
            'RMVB',
            'FLV',
            'F4V',
            'H.264',
            'H.265',
            'REAL VIDEO',
            'MKV',
            'WebM',
            'HDDVD',
            'MP4',
            'MPG',
            'M4V',
            'MGV',
            'OGV',
            'QTM',
            'STR',
            'AMC',
            'DVX',
            'EVO',
            'DAT',
            'OGG',
            'OGM'
          ]
          console.log(works)
          for (var step = 0; step < steps.length; step++) {
            worksStudent[step] = []
            if (!isCloseList[step] || isCloseList[step].isClose === undefined) {
              isCloseList[step] = { isClose: 0 }
            }
            groupStudent[step] = []
            isWorksS[step] = []
            groupStudentUid[step] = []
            if (steps[step].tool[0] === 49) {
              for (var gA = 0; gA < steps[step].groupJson.group.length; gA++) {
                groupStudent[step][gA] = []
                groupStudentUid[step][gA] = []
                worksStudent[step][gA] = []
                isCloseList[step][gA] = []

                for (var g = 0; g < f.length; g++) {
                  if (
                    f[g].ttype === 2 &&
                    this.tcid &&
                    this.arrayToArray(f[g].classid.split(','), this.tcid.split(',')).length === 0
                  ) {
                    continue
                  }
                  if (gA === f[g].group && f[g].tool === step) {
                    this.groupStudent[step][gA].push(f[g])
                    this.groupStudentUid[step][gA].push(f[g].userid)
                  }
                }
              }
              this.$forceUpdate()
            }
            for (var j = 0; j < works.length; j++) {
              if (
                works[j].ttype === 2 &&
                this.tcid &&
                this.arrayToArray(works[j].classid.split(','), this.tcid.split(',')).length === 0
              ) {
                continue
              }
              var likesCount = 0
              var commentCount = 0
              var isLikes = false
              var commentJson = []

              if (step === works[j].tool) {
                if (
                  (works[j].type === 1 ||
                    works[j].type === 4 ||
                    works[j].type === 5 ||
                    works[j].type === 6 ||
                    works[j].type === 12 ||
                    works[j].type === 7) &&
                  steps[step].tool[0] !== 15 &&
                  steps[step].tool[0] !== 4 &&
                  steps[step].tool[0] !== 45 &&
                  steps[step].tool[0] !== 50 &&
                  steps[step].tool[0] !== 32 &&
                  steps[step].tool[0] !== 57 &&
                  steps[step].tool[0] !== 52
                ) {
                  if (
                    wordPan.indexOf(
                      works[j].content.split('.')[works[j].content.split('.').length - 1].toLocaleUpperCase()
                    ) !== -1 &&
                    steps[step].tool[0] === 16 &&
                    (works[j].atool ? parseInt(works[j].atool) : '') !== 50
                  ) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 1,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }
                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  } else if (
                    videoPan.indexOf(
                      works[j].content.split('.')[works[j].content.split('.').length - 1].toLocaleUpperCase()
                    ) !== -1 &&
                    steps[step].tool[0] === 16 &&
                    (works[j].atool ? parseInt(works[j].atool) : '') !== 50
                  ) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 3,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }

                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  } else if (works[j].type === 6 && (works[j].atool ? parseInt(works[j].atool) : '') !== 50) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 4,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }

                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  } else if (works[j].type === 7 && (works[j].atool ? parseInt(works[j].atool) : '') !== 50) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 5,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }

                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  } else if (
                    works[j].type === 12 &&
                    steps[step].tool[0] === (works[j].atool ? parseInt(works[j].atool) : '')
                  ) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 12,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }

                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  } else if (
                    works[j].type === 1 &&
                    steps[step].tool[0] === (works[j].atool ? parseInt(works[j].atool) : '')
                  ) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 0,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }

                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  } else if (works[j].type === 1 && !parseInt(works[j].atool ? parseInt(works[j].atool) : '')) {
                    const _works = {
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: works[j].content,
                      sName: works[j].name,
                      type: 0,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    }

                    worksStudent[step].push(_works)
                    isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                  }
                } else if (works[j].type === 3 && steps[step].tool[0] === 15) {
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name,
                    type: 2,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (works[j].type === 2 && steps[step].tool[0] === 4) {
                  // 问卷
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name,
                    type: 4,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (works[j].type === 8 && steps[step].tool[0] === 45) {
                  // 选择题
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name,
                    type: 8,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (works[j].type === 9 && steps[step].tool[0] === 47) {
                  // 选择题
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name,
                    type: 9,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (works[j].type === 10 && steps[step].tool[0] === 48) {
                  // 选择题
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name,
                    type: 10,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (works[j].type === 13 && steps[step].tool[0] === 52) {
                  // 选择题
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name,
                    type: 13,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (works[j].type === 11 && steps[step].tool[0] === 49) {
                  const _gindex = JSON.parse(works[j].content)
                  if (groupStudentUid[step][_gindex.groupIndex].indexOf(works[j].userid) !== -1) {
                    worksStudent[step][_gindex.groupIndex].push({
                      userid: works[j].userid,
                      ateacher: works[j].ateacher,
                      wid: works[j].id,
                      works: _gindex.url,
                      sName: works[j].name,
                      type: _gindex.type,
                      time: works[j].time,
                      score: works[j].score,
                      img: works[j].img,
                      likesCount: likesCount,
                      commentCount: commentCount,
                      isLikes: isLikes,
                      commentJson: commentJson
                    })
                  }
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (steps[step].tool[0] === 50 && (works[j].atool ? parseInt(works[j].atool) : '') === 50) {
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name ? works[j].name : works[j].userid,
                    type: works[j].type === 1 ? 0 : works[j].type === 4 ? 1 : 3,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (steps[step].tool[0] === 32 && (works[j].atool ? parseInt(works[j].atool) : '') === 32) {
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name ? works[j].name : works[j].userid,
                    type: 12,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                } else if (steps[step].tool[0] === 57 && (works[j].atool ? parseInt(works[j].atool) : '') === 57) {
                  const _works = {
                    userid: works[j].userid,
                    ateacher: works[j].ateacher,
                    wid: works[j].id,
                    works: works[j].content,
                    sName: works[j].name ? works[j].name : works[j].userid,
                    type: 12,
                    time: works[j].time,
                    score: works[j].score,
                    img: works[j].img,
                    likesCount: likesCount,
                    commentCount: commentCount,
                    isLikes: isLikes,
                    commentJson: commentJson
                  }

                  worksStudent[step].push(_works)
                  isWorksS[step].push({ uid: works[j].userid, sName: works[j].name })
                }
              }
            }
          }
          // if (worksStudent[step] && worksStudent[step].length) {
          //   worksStudent[step] = worksStudent[step].sort(function(a, b) {
          //     const jscoreA = a.score ? JSON.parse(a.score).wScore : 0
          //     const jscoreB = b.score ? JSON.parse(b.score).wScore : 0
          //     var scoreA = parseFloat(jscoreA)
          //     var scoreB = parseFloat(jscoreB)
          //     if (scoreA === scoreB) {
          //       return b.likesCount - a.likesCount
          //     }
          //     return scoreB - scoreA
          //   })
          // }
          this.worksStudent = worksStudent
          this.isCloseList = isCloseList
          this.groupStudent = groupStudent
          this.groupStudentUid = groupStudentUid
          this.isWorksS = isWorksS
          this.$forceUpdate()
          this.selectWorksStudent()
        })
        .catch(err => {
          console.error(err)
        })
    },
    selectWorksStudent() {
      const params = {
        oid: this.oid,
        cid: this.courseDetail.juri
      }
      getCourseWorksStudentJuri(params)
        .then(res => {
          var a = res[0]
          for (var i = 0; i < this.isWorksS.length; i++) {
            this.noWorksS[i] = []
            var studentK = []
            for (var z = 0; z < this.isWorksS[i].length; z++) {
              studentK.push(this.isWorksS[i][z].uid)
            }
            studentK = studentK.join(',')
            for (var j = 0; j < a.length; j++) {
              if (studentK.indexOf(a[j].userid) === -1) {
                if (this.tcid) {
                  if (this.arrayToArray(a[j].classid.split(','), this.tcid.split(',')).length) {
                    this.noWorksS[i].push({
                      student: a[j].name,
                      userid: a[j].userid
                    })
                  }
                } else {
                  this.noWorksS[i].push({
                    student: a[j].name,
                    userid: a[j].userid
                  })
                }
              }
            }
          }
          this.$forceUpdate()
        })
        .catch(err => {
          console.log(err)
        })
    },
    contract(i) {
      if (this.isCloseList[i].isClose === 0) {
        this.isCloseList[i].isClose = 1
      } else {
        this.isCloseList[i].isClose = 0
      }
      this.$forceUpdate()
    },
    addImg(e) {
      var el = e.currentTarget
      el.getElementsByTagName('input')[0].click()
      e.target.value = ''
    },
    pngToWhiteBg(file) {
      const _file = file
      const read = new FileReader()
      read.readAsDataURL(file) // 文件转base64
      return new Promise((resolve, reject) => {
        read.onload = e => {
          const img = new Image()
          img.src = e.target.result
          // eslint-disable-next-line space-before-function-paren
          img.onload = async () => {
            // 生成canvas
            const canvas = document.createElement('canvas')
            const context = canvas.getContext('2d')
            // 绘制图片到canvas上
            canvas.width = img.width
            canvas.height = img.height

            // 在canvas绘制前填充白色背景
            context.fillStyle = '#fff'
            context.fillRect(0, 0, canvas.width, canvas.height)
            context.drawImage(img, 0, 0)
            const base64 = canvas.toDataURL(file['type'], 1)
            const newFile = this.dataUrlToFile(base64, _file)
            resolve(newFile)
          }
        }
      })
    },
    dataUrlToFile(dataurl, file) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      // return new Blob([u8arr], { type: mime });
      return new File([new Blob([u8arr], { type: mime })], file.name, {
        type: mime
      })
    },
    async beforeUpload(event, type, i) {
      // this.$message.success('进入上传')
      var file = ''
      const files = event.target.files
      const plfile = []
      for (let cfindex2 = 0; cfindex2 < files.length; cfindex2++) {
        if (files.length > 1) {
          this.pVisible = false
        } else {
          this.pVisible = true
        }
        file = files[cfindex2]
        var credentials = {
          accessKeyId: 'AKIATLPEDU37QV5CHLMH',
          secretAccessKey: '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'
        } // 秘钥形式的登录上传
        window.AWS.config.update(credentials)
        window.AWS.config.region = 'cn-northwest-1' // 设置区域

        // eslint-disable-next-line prettier/prettier
        var bucket = new window.AWS.S3({ params: { Bucket: 'ccrb' }}) // 选择桶
        var _this = this
        _this.progress = 0
        _this.proVisible = true
        _this.isFinishSize = 0
        _this.isAllSize = (file.size / 1024 / 1024).toFixed(2)
        var photoA = ['BMP', 'GIF', 'PNG', 'JPGE', 'JPEG', 'JPG', 'TIF', 'PCX', 'TGA', 'EXIF', 'FPX', 'SVG', 'APNG']

        if (
          photoA.indexOf(file.name.split('.')[file.name.split('.').length - 1].toLocaleUpperCase()) !== -1 &&
          type !== 4
        ) {
          file = await this.pngToWhiteBg(file)
          const blob = await imageConversion.compressAccurately(file, 256)
          file = new File([blob], file.name, { type: file.type })
        }

        if (file) {
          var params = {
            Key:
              file.name.split('.')[0] +
              new Date().getTime() +
              '.' +
              file.name.split('.')[file.name.split('.').length - 1],
            ContentType: file.type,
            Body: file,
            'Access-Control-Allow-Credentials': '*',
            ACL: 'public-read'
          } // key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
          var options = {
            // partSize: 2048 * 1024 * 1024,
            partSize: 1024 * 1024 * 1024,
            queueSize: 2,
            leavePartsOnError: true
          }
          bucket
            .upload(params, options)
            .on('httpUploadProgress', function(evt) {
              // 这里可以写进度条
              // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
              _this.progress = parseInt((evt.loaded / evt.total) * 100)
              _this.isFinishSize = (evt.loaded / 1024 / 1024).toFixed(2)
            })
            .send(function(err, data) {
              _this.progress = 100
              _this.isFinishSize = _this.isAllSize
              if (cfindex2 === files.length - 1 || cfindex2 > files.length - 1) {
                setTimeout(() => {
                  _this.proVisible = false
                }, 1000)
              }
              if (err) {
                var a = _this.$refs.upload1.uploadFiles
                a.splice(a.length - 1, a.length)
                _this.$message.error('上传失败')
              } else {
                var b = ['PDF', 'DOC', 'DOCX', 'PPT', 'PPTX', 'XLSX', 'XLS']
                var c = [
                  'AVI',
                  'NAVI',
                  'MPEG',
                  'ASF',
                  'MOV',
                  'WMV',
                  '3GP',
                  'RM',
                  'RMVB',
                  'FLV',
                  'F4V',
                  'H.264',
                  'H.265',
                  'REAL VIDEO',
                  'MKV',
                  'WebM',
                  'HDDVD',
                  'MP4',
                  'MPG',
                  'M4V',
                  'MGV',
                  'OGV',
                  'QTM',
                  'STR',
                  'AMC',
                  'DVX',
                  'EVO',
                  'DAT',
                  'OGG',
                  'OGM'
                ]
                if (type === 16) {
                  if (
                    c.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !== -1
                  ) {
                    _this.fileType = 2
                  } else if (
                    b.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !== -1
                  ) {
                    _this.fileType = 1
                  } else if (
                    photoA.indexOf(
                      data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()
                    ) !== -1
                  ) {
                    _this.fileType = 0
                  } else {
                    _this.fileType = 3
                  }
                  _this.addCourseWorks(data.Location, i)
                } else if (type === 50) {
                  var _ftype = 1
                  if (
                    c.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !== -1
                  ) {
                    _ftype = 5
                  } else if (
                    b.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !== -1
                  ) {
                    _ftype = 4
                  } else {
                    _ftype = 1
                  }
                  plfile.push({
                    fileType: _ftype,
                    url: data.Location,
                    username: _this.userinfo.userid
                  })
                  if (cfindex2 === files.length - 1 || cfindex2 > files.length - 1) {
                    _this.addCourseWorksPl(plfile, i)
                  }
                }
                console.log(type)
                console.log(data.Location)
              }
            })
        }
      }
    },
    async beforeUpload2(event, i) {
      // this.$message.success('进入上传')
      var file = ''

      file = event.target.files[0]
      var credentials = {
        accessKeyId: 'AKIATLPEDU37QV5CHLMH',
        secretAccessKey: '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'
      } // 秘钥形式的登录上传
      window.AWS.config.update(credentials)
      window.AWS.config.region = 'cn-northwest-1' // 设置区域

      // eslint-disable-next-line prettier/prettier
      var bucket = new window.AWS.S3({ params: { Bucket: 'ccrb' }}) // 选择桶
      var _this = this
      _this.progress = 0
      _this.proVisible = true
      _this.isFinishSize = 0
      _this.isAllSize = (file.size / 1024 / 1024).toFixed(2)
      var photoA = ['BMP', 'GIF', 'PNG', 'JPGE', 'JPEG', 'JPG', 'TIF', 'PCX', 'TGA', 'EXIF', 'FPX', 'SVG', 'APNG']

      if (photoA.indexOf(file.name.split('.')[file.name.split('.').length - 1].toLocaleUpperCase()) !== -1) {
        file = await this.pngToWhiteBg(file)
        const blob = await imageConversion.compressAccurately(file, 256)
        file = new File([blob], file.name, { type: file.type })
      }

      if (file) {
        var params = {
          Key:
            file.name.split('.')[0] +
            new Date().getTime() +
            '.' +
            file.name.split('.')[file.name.split('.').length - 1],
          ContentType: file.type,
          Body: file,
          'Access-Control-Allow-Credentials': '*',
          ACL: 'public-read'
        } // key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          // partSize: 2048 * 1024 * 1024,
          partSize: 1024 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true
        }
        bucket
          .upload(params, options)
          .on('httpUploadProgress', function(evt) {
            // 这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
            _this.progress = parseInt((evt.loaded / evt.total) * 100)
            _this.isFinishSize = (evt.loaded / 1024 / 1024).toFixed(2)
          })
          .send(function(err, data) {
            _this.progress = 100
            _this.isFinishSize = _this.isAllSize
            setTimeout(() => {
              _this.proVisible = false
            }, 1000)
            if (err) {
              var a = _this.$refs.upload1.uploadFiles
              a.splice(a.length - 1, a.length)
              _this.$message.error('上传失败')
            } else {
              var b = ['PDF', 'DOC', 'DOCX', 'PPT', 'PPTX', 'XLSX', 'XLS']
              var c = [
                'AVI',
                'NAVI',
                'MPEG',
                'ASF',
                'MOV',
                'WMV',
                '3GP',
                'RM',
                'RMVB',
                'FLV',
                'F4V',
                'H.264',
                'H.265',
                'REAL VIDEO',
                'MKV',
                'WebM',
                'HDDVD',
                'MP4',
                'MPG',
                'M4V',
                'MGV',
                'OGV',
                'QTM',
                'STR',
                'AMC',
                'DVX',
                'EVO',
                'DAT',
                'OGG',
                'OGM'
              ]
              if (_this.sTool === 16 || _this.sTool === 50) {
                if (
                  c.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !== -1
                ) {
                  _this.fileType = 2
                } else if (
                  b.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !== -1
                ) {
                  _this.fileType = 1
                } else if (
                  photoA.indexOf(data.Location.split('.')[data.Location.split('.').length - 1].toLocaleUpperCase()) !==
                  -1
                ) {
                  _this.fileType = 0
                } else {
                  _this.fileType = 3
                }
                _this.addCourseWorksTeacher(data.Location, i)
              }
              console.log(data.Location)
            }
          })
      }
    },
    addCourseWorks(data, toolindex) {
      var typesql
      if (this.fileType === 0) {
        typesql = 1
      } else if (this.fileType === 1) {
        typesql = 4
      } else if (this.fileType === 2) {
        typesql = 5
      } else if (this.fileType === 3) {
        typesql = 12
      }

      const params = [
        {
          uid: this.userinfo.userid,
          cid: this.courseid,
          stage: this.courseType,
          task: this.taskCount,
          tool: toolindex,
          content: data,
          type: typesql
        }
      ]
      addCourseWorksR(params)
        .then(res => {
          this.$toast({
            message: '添加成功',
            type: 'success'
          })
          setTimeout(() => {
            this.getWorks()
          }, 2000)
        })
        .catch(err => {
          console.error(err)
        })
    },
    addCourseWorks5(data, toolindex, tool, typesql) {
      const params = [
        {
          uid: this.userinfo.userid,
          cid: this.courseid,
          stage: this.courseType,
          task: this.taskCount,
          tool: toolindex,
          content: data,
          type: typesql,
          atool: tool,
          text: ''
        }
      ]
      addCourseWorks5(params)
        .then(res => {
          this.$toast({
            message: '添加成功',
            type: 'success'
          })
          setTimeout(() => {
            this.getWorks()
          }, 2000)
        })
        .catch(err => {
          console.error(err)
        })
    },
    addCourseWorksTeacher(data, toolindex) {
      var typesql
      if (this.sTool === 32 || this.sTool === 57) {
        this.addCourseWorksGongTeacher(this.toolindex, data, this.sTool)
        return
      }
      if (this.fileType === 0) {
        typesql = 1
      } else if (this.fileType === 1) {
        typesql = 4
      } else if (this.fileType === 2) {
        typesql = 5
      } else if (this.fileType === 3) {
        typesql = 12
      }

      if (this.sTool === 50) {
        this.addCourseWorks5(data, toolindex, this.sTool, typesql)
        return
      }

      if (!data) {
        this.$message.error('请上传文件')
        return
      }
      const params = [
        {
          uid: this.sStudent.userid,
          cid: this.courseid,
          stage: this.courseType,
          task: this.taskCount,
          tool: toolindex,
          content: data,
          type: typesql,
          ateacher: this.userinfo.userid
        }
      ]
      addCourseWorksTeacher(params)
        .then(res => {
          this.$toast({
            message: '添加成功',
            type: 'success'
          })
          setTimeout(() => {
            this.getWorks()
          }, 2000)
        })
        .catch(err => {
          this.$message.error('提交失败')
          console.error(err)
        })
    },
    addCourseWorksPl(files, toolindex) {
      const _files = files

      const params = [
        {
          ateacher: this.userinfo.userid,
          cid: this.courseid,
          stage: this.courseType,
          task: this.taskCount,
          tool: toolindex,
          content: JSON.stringify(_files).replaceAll(/%/g, '%25')
        }
      ]
      addCourseWorksPl(params)
        .then(res => {
          this.$toast({
            message: '添加成功',
            type: 'success'
          })
          setTimeout(() => {
            this.getWorks()
          }, 2000)
        })
        .catch(err => {
          this.$message.error('提交失败')
          console.error(err)
        })
    },
    teacherSubmit(tool, studnet, e, content) {
      this.sStudent = studnet
      this.sTool = tool
      if (this.userinfo.type === 1) {
        if (tool === 16 || tool === 50) {
          var el = e.currentTarget
          el.getElementsByTagName('input')[0].click()
          e.target.value = ''
        } else if (tool === 15) {
          this.isTeacher = false
          this.answerQ = content.answerQ
          this.setPanelVisible(true)
        }
      }
    },
    addWork(tool, toolindex, content) {
      this.sStudent = {}
      this.toolindex = toolindex
      if (tool === 15) {
        this.isTeacher = true
        this.answerQ = content.answerQ
        this.setPanelVisible(true)
      } else if (tool === 4) {
        this.isTeacher = true
        this.askJson = content
        this.setAskPanelVisible(true)
      } else if (tool == 45) {
        this.isTeacher = true
        this.chooseJson = content
        this.setChoosePanelVisible(true)
      }
    }
  },
  mounted() {}
}
</script>

<style lang="scss" scoped>
.sb-container {
  width: 100%;
  box-sizing: border-box;
  padding: 0 15px 60px;
  .steps-box {
    width: 100%;
    border-bottom: 1px solid rgb(239, 239, 239);
    padding: 15px 0;
    .step-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 0.8rem;
      .step {
        font-size: 18px;
        font-weight: bold;
        display: flex;
        height: 100%;
        align-items: center;
        &::before {
          content: '';
          height: 100%;
          width: 3px;
          display: block;
          margin-right: 0.2rem;
          background-image: linear-gradient(180deg, #2c5cbd, #a1cff4);
        }
      }
      .do {
        font-size: 14px;
        color: #b9b9b9;
        display: flex;
        align-items: center;
        cursor: pointer;
        &::after {
          content: '';
          width: 5px;
          height: 5px;
          border-top: 2px solid #b9b9b9;
          border-left: 2px solid #b9b9b9;
          transform: rotate(-135deg);
          transition: all 0.5s;
          margin-left: 5px;
        }
        &.close {
          &::after {
            transform: rotate(-45deg);
          }
        }
      }
    }
  }
  .tool-box {
    margin: 10px 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 1.5rem;
    .tool-img {
      width: 1.5rem;
      border-radius: 15px;
      box-shadow: 0 1px 8px 0 #14141424;
      > img {
        width: 100%;
        height: auto;
        object-fit: cover;
      }
    }
    .tool-name {
      font-size: 14px;
      margin-top: 5px;
      white-space: nowrap;
    }
  }

  .works-box {
    .title {
      font-size: 14px;
      color: #858585;
    }
    .works {
      margin: 10px 0 0;
      display: flex;
      flex-wrap: wrap;
      .work {
      }
    }
  }
  .no-works-box {
    margin-top: 10px;
    .title {
      font-size: 14px;
      color: #858585;
    }
    .no-works-box-students {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      margin: 10px 0 0;
      .student {
        background: #7cbcf1;
        color: #fff;
        width: 70px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        border-radius: 5px;
        margin: 0 15px 10px 0;
        padding: 5px;
        font-size: 14px;
        cursor: pointer;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-word;
        max-width: 70px;
        // @include textoverflow();
      }
    }
  }

  .noMssage {
    width: 100%;
    height: 5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    > img {
      width: 3rem;
    }
  }
}
</style>
