<template>
  <div class="home-container">
    <head-bar @back="back" style="z-index: 999;">
      <template #title>
        <div class="navTitle">填写问卷</div>
      </template>
    </head-bar>
    <div class="step_box">
      <topicVue
        :cJson.sync="cJson"
        :title="title"
        :brief="brief"
        ref="topicVue"
        @getTestWorkByCid="getTestWorkByCid"
        @publish2="publish2"
        :tid="tid"
      ></topicVue>
    </div>
    <div class="edit_top">
      <div class="op_btn">
        <el-button type="primary" size="small" @click="publish">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getTestCourseDetail } from '@/api/testDetail'
import { addTestWorks } from '@/api/testDetail'
import { addTestWorks2 } from '@/api/testDetail'
import { selectTestWorksCid } from '@/api/testDetail'
// import { getTestWorks } from '@/api/testDetail'
// import { getTestWorks2 } from '@/api/testDetail'

import headBar from '@/components/headBar.vue'
import { mapGetters } from 'vuex'
import topicVue from './components/topic.vue'
// import course from './components/course.vue'

export default {
  components: {
    headBar,
    topicVue
  },
  data() {
    return {
      courseid: '',
      cid: this.$route.query.courseid,
      userid: this.$route.query.userid,
      see: false,
      tid: '',
      title: '',
      brief: '',
      look: '',
      cJson: [],
      cJson2: [],
      loading:false
    }
  },
  computed: {
    ...mapGetters(['userinfo'])
  },
  methods: {
    back() {
      this.$router.push({ path: '/test' })
    },
    getData() {
      const params = {
        cid: this.cid
      }
      getTestCourseDetail(params)
        .then(res => {
          this.cJson = JSON.parse(res[0][0].chapters)
          // console.log('getTestCourseDetail', this.cJson)

          this.cJson2 = JSON.parse(res[0][0].chapters)
          this.title = res[0][0].title
          this.brief = res[0][0].brief

          this.see = res[0][0].open == 1

          this.testType = []
          for (var i = 0; i < res[1].length; i++) {
            this.testType.push(res[1][i].typeid)
          }
          // console.log(this.testType)
          this.look = res[0][0].look
          // if (this.type == 3) {
          //   this.getTestWorks2()
          // } else {
          //   this.getTestWorks()
          // }
          this.$forceUpdate()
        })
        .catch(err => {
          console.error(err)
        })
    },
    getTestWorkByCid(courseid) {
      this.courseid = courseid
      const params = {
        cid: this.cid,
        uid: this.userinfo.userid
      }
      console.log('getTestWorkByCidparams', params)
      const _courseid = courseid
      selectTestWorksCid(params)
        .then(res => {
          console.log('selectTestWorksCid', res)
          if (res[0].length) {
            const rData = res[0]
            this.tid = ''
            // eslint-disable-next-line no-labels
            aa: for (var i = 0; i < rData.length; i++) {
              const rDataJson = this.JSONSetting(JSON.parse(rData[i].courseJson))
              const _json = JSON.parse(rData[i].courseJson)
              for (var j = 0; j < rDataJson.length; j++) {
                const _param = rDataJson[j]
                if (_param.type == 6 && _param.json.answer2 && _param.json.answer2 == _courseid) {
                  this.cJson = _json
                  console.log(this.cJson)
                  // let cJson = this.setJSON(JSON.parse(JSON.stringify(this.cJson)))
                  // let cJson2 = this.setJSON(this.setJson2(JSON.parse(JSON.stringify(this.cJson2))))
                  // if (JSON.stringify(cJson) != JSON.stringify(cJson2)) {
                  //   this.isReset = true
                  // }
                  this.tid = rData[i].id
                  this.$forceUpdate()
                  break aa
                }
              }
            }
            if (!this.tid) {
              this.cJson = this.setJSON(this.setCourseid(JSON.parse(JSON.stringify(this.cJson2))))
            }
          } else {
            this.tid = ''
            this.cJson = this.setJSON(this.setCourseid(JSON.parse(JSON.stringify(this.cJson2))))
          }
          this.$forceUpdate()
        })
        .catch(err => {
          console.error(err)
        })
    },
    setJson2(json) {
      const _json = json
      // this.type = _json[0].ttype;
      const checkArray = _json.filter(item => {
        if (item.array) {
          item.array = item.array.filter(item2 => {
            if (item2.ttype == 1 && item2.json && !item2.json.answer2) {
              item2.json.answer2 = []
            }
            if (item2.array) {
              item2.array = item2.array.filter(item3 => {
                if (item3.ttype == 1 && item3.json && !item3.json.answer2) {
                  item3.json.answer2 = []
                }
                return item3
              })
            }
            return (item2.ttype != 1 && item2.array.length > 0) || item2.ttype == 1
          })
        }
        if (item.ttype == 1 && item.json && !item.json.answer2) {
          item.json.answer2 = []
        }
        // console.log(item.array)
        return (item.ttype != 1 && item.array.length > 0) || item.ttype == 1
      })
      // console.log(checkArray)
      return checkArray
    },
    setCourseid(json) {
      const _json = json
      // this.type = _json[0].ttype;
      const checkArray = _json.filter(item => {
        if (item.array) {
          item.array = item.array.filter(item2 => {
            if (
              item2.ttype == 1 &&
              item2.json &&
              !item2.json.answer2 &&
              item2.type != 6 &&
              item2.type != 7 &&
              item2.type != 14
            ) {
              item2.json.answer2 = []
            } else if (item2.type == 6) {
              item2.json.answer2 = this.courseid ? this.courseid : ''
            } else if (item2.type == 7) {
              item2.json.answer2 = ''
            }
            if (item2.array) {
              item2.array = item2.array.filter(item3 => {
                if (
                  item3.ttype == 1 &&
                  item3.json &&
                  !item3.json.answer2 &&
                  item3.type != 6 &&
                  item3.type != 7 &&
                  item2.type != 14
                ) {
                  item3.json.answer2 = []
                } else if (item3.type == 6) {
                  item3.json.answer2 = this.courseid ? this.courseid : ''
                } else if (item3.type == 7) {
                  item3.json.answer2 = ''
                }
                return item3
              })
            }
            return (item2.ttype != 1 && item2.array.length > 0) || item2.ttype == 1
          })
        }
        if (
          item.ttype == 1 &&
          item.json &&
          !item.json.answer2 &&
          item.type != 6 &&
          item.type != 6 &&
          item.type != 7 &&
          item2.type != 14
        ) {
          item.json.answer2 = []
        } else if (item.type == 6) {
          item.json.answer2 = this.courseid ? this.courseid : ''
        } else if (item.type == 7) {
          item.json.answer2 = ''
        }
        // console.log(item.array)
        return (item.ttype != 1 && item.array.length > 0) || item.ttype == 1
      })
      console.log('checkArray', checkArray)
      return checkArray
    },
    JSONSetting(json) {
      const _json = json
      const array = []
      _json.filter(item => {
        if (item.array) {
          item.array = item.array.filter(item2 => {
            if (item2.ttype == 1 && item2.json) {
              array.push(item2)
            }
            if (item2.array) {
              item2.array = item2.array.filter(item3 => {
                if (item3.ttype == 1 && item3.json) {
                  array.push(item3)
                }
                return item3
              })
            }
            return item2
          })
        }
        if (item.ttype == 1 && item.json) {
          array.push(item)
        }
        // console.log(item.array)
        return item
      })
      // console.log(array)
      return array
    },
    setJSON(json) {
      return json.filter(item => {
        if (item.array) {
          item.array = item.array.filter(item2 => {
            if (item2.ttype == 1 && item2.json) {
              delete item2.json.answer2
              delete item2.json.score2
              delete item2.json.file
            }
            if (item2.array) {
              item2.array = item2.array.filter(item3 => {
                if (item3.ttype == 1 && item3.json) {
                  delete item3.json.answer2
                  delete item3.json.score2
                  delete item3.json.file
                }
                return item3
              })
            }
            return item2
          })
        } else if (item.ttype == 1 && item.json) {
          delete item.json.answer2
          delete item.json.score2
          delete item.json.file
        }
        return item
        console.log(item.array)
      })
    },

    panJSON(array) {
      var pan = 0
      for (var i = 0; i < array.length; i++) {
        if (array[i].type != 6) {
          const param = array[i].json
          if (array[i].type == 5 && param.file && param.file.length > 0) {
            pan++
          } else if (param.answer2.length || typeof param.answer2 === 'number') {
            pan++
          }
        }
      }
      if (pan > 0) {
        return true
      } else {
        return false
      }
    },
    publish2() {
      console.log('publish2')
      const cjson = this.$refs['topicVue'].checkArray

      for (let i = 0; i < cjson.length; i++) {
        let _item = cjson[i]
        if (_item.type == 14) {
          if (!_item.json.answer2) {
            this.$toast.fail(i + 1 + '、' + _item.json.title + '未打卡')
            return
          } else {
            if (_item.json.codeScanningTime) {
              let currentTime = new Date().getTime() // 获取当前时间戳
              let checkTime = new Date(_item.json.codeScanningTime).getTime() // 获取_valueAndTime.time的时间戳
              let minutes = parseInt(_item.json.minutes) // 获取minutes对象

              if (currentTime - checkTime > minutes * 60 * 1000) {
                // 超过指定分钟数的逻辑处理
                this.$toast.fail(i + 1 + '、' + _item.json.title+'二维码已过期，请重新扫码打卡。')
              } else {
                // 在限制时间内的逻辑处理
              }
            } else {
              this.$toast.fail(i + 1 + '、' + _item.json.title + '未打卡')
              return
            }
          }
        }
      }

      const _cjson = this.JSONSetting(JSON.parse(JSON.stringify(cjson)))
      const pan = this.panJSON(_cjson)
      if (!pan) {
        setTimeout(() => {
          this.isloading = false
        }, 500)
        return
      }
      const params = [
        {
          uid: this.tid ? this.tid : this.userinfo.userid,
          cid: this.cid,
          cjson: encodeURIComponent(JSON.stringify(cjson)),
          type: '2'
        }
      ]
      if (this.tid) {
        addTestWorks2(params)
          .then(res => {
            this.$message.success('保存成功')
          })
          .catch(err => {
            console.error(err)
          })
      } else {
        addTestWorks(params)
          .then(res => {
            this.$message.success('保存成功')
          })
          .catch(err => {
            console.error(err)
          })
      }
    },
    publish() {
      console.log('publish')

      const cjson = this.$refs['topicVue'].checkArray
      for (let i = 0; i < cjson.length; i++) {
        let _item = cjson[i]
        if (_item.type == 14) {
          if (!_item.json.answer2) {
            this.$toast.fail(i + 1 + '、' + _item.json.title + '未打卡')
            return
          } else {
            if (_item.json.codeScanningTime) {
              let currentTime = new Date().getTime() // 获取当前时间戳
              let checkTime = new Date(_item.json.codeScanningTime).getTime() // 获取_valueAndTime.time的时间戳
              let minutes = parseInt(_item.json.minutes) // 获取minutes对象

              if (currentTime - checkTime > minutes * 60 * 1000) {
                // 超过指定分钟数的逻辑处理
                this.$toast.fail(i + 1 + '、' + _item.json.title+'二维码已过期，请重新扫码打卡。')
              } else {
                // 在限制时间内的逻辑处理
              }
            } else {
              this.$toast.fail(i + 1 + '、' + _item.json.title + '未打卡')
              return
            }
          }
        }
      }

      const params = [
        {
          uid: this.tid ? this.tid : this.userinfo.userid,
          cid: this.cid,
          cjson: encodeURIComponent(JSON.stringify(cjson)),
          type: 2
        }
      ]
      // console.log(this.tid)
      // return console.log('publish发布', params)

      if(this.loading)return;
      this.loading = true;
      if (this.tid) {
        addTestWorks2(params)
          .then(res => {
            this.$message.success('提交成功')
            this.loading = false;
            this.back()
          })
          .catch(err => {
            this.loading = false;
            console.error(err)
          })
      } else {
        console.log('shangchuan')

        addTestWorks(params)
          .then(res => {
            this.$message.success('提交成功')
            this.back()
            this.loading = false;
          })
          .catch(err => {
            console.error(err)
            this.loading = false;
          })
      }
    }
  },
  mounted() {
    // console.log('userid', this.$route.query.userid)

    this.getData()
  }
}
</script>

<style lang="scss" scoped>
.navTitle {
  font-size: 16px;
  color: #fff;
}
.home-container {
  height: 100vh;
  overflow: hidden;
  .step_box {
    margin-top: 1.5rem;
    width: 100%;
    height: calc(100vh - 55px - 50px);
    overflow: auto;
    position: relative;
  }
  .edit_top {
    width: 100%;
    margin: 0 auto;
    /deep/.el-button {
      width: 100%;
      height: 50px;
      text-align: center;
      font-size: 16px;
    }
  }
}
</style>
