<template>
  <div v-loading="loading" style="min-height: 500px;">
    <el-form
      v-if="isRender"
      data-viewport-uid="lc"
      ref="questions"
      size="small"
      :model="questionForm"
      :disabled="openType === 'look'"
    >
      <template>
        <QuestionFormItem
          class="father"
          v-for="question of questions"
          :key="question.Id"
          :question="question"
          :question-form="questionForm"
          :trial-clinical-id="trialClinicalId"
          @resetFormItemData="resetFormItemData"
          @setFormItemData="setFormItemData"
        />
      </template>
    </el-form>
    <div class="base-dialog-footer" v-if="!isViewer && openType !== 'look' && [2, 3].includes(clinicalDataLevel)" style="text-align:right;margin-top:10px;">
        <!-- 取消 -->
        <el-button
          size="small"
          type="primary"
          @click="close"
          v-show="$route.path !== '/trials/trials-panel/visit/crc-upload'"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" @click="submitClinicalForm">
          {{ $t('common:button:save') }}
        </el-button>
    </div>
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span style="font-size:18px;">{{ $t('common:dialogTitle:sign') }}</span>
        <span style="font-size:12px;margin-left:5px">{{ `(${$t('common:label:sign')}${ currentUser })` }}</span>
      </div>
      <SignForm ref="signForm" :sign-code-enum="signCode" @closeDialog="closeSignDialog" />
    </el-dialog>
  </div>

</template>

<script>

import { getTrialClinicalQuestionPreview, submitClinicalForm, SubmitClinicalFormAndSign, getSystemClinicalQuestionPreview } from '@/api/trials'
import { getClinicalFormInfo } from '@/api/dictionary'
import SignForm from '@/views/trials/components/newSignForm'
import QuestionFormItem from './QuestionFormItem'
import const_ from '@/const/sign-code'
import html2canvas from "html2canvas";


export default {
  name: 'QuestionsPreview',
  components: {
    QuestionFormItem,
    SignForm
  },
  props: {
    clinicalDataLevel: {
      type: Number,
      default: () => {
        return 2
      }
    },
    openType: {
      type: String,
    },
    isViewer: {
      type: Boolean,
      default: () => true
    },
    visitId: {
      type: String,
      default: () => ''
    },
    subjectId: {
      type: String,
      default: () => ''
    },
    trialId: {
      type: String,
      default: () => ''
    },
    readingId: {
      type: String,
      default: () => ''
    },
    clinicalFormId: {
      type: String,
      default: () => ''
    },
    data: {
      type: Object,
      default: () => {}
    },
    trialClinicalId: {
      type: String,
      required: true
    },
    systemClinicalId: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      signVisible: false,
      signCode: null,
      loading: false,
      questions: [],
      questionForm: {},
      publicQuestions: [],
      isRender: false,
      activeName: 0,
      CalculationList: [],
      currentUser: zzSessionStorage.getItem('userName'),
    }
  },
  mounted() {
    if (this.openType === 'add') {
      if (this.systemClinicalId) {
        this.getSystemClinicalQuestionPreview()
      } else {
        this.getTrialClinicalQuestionPreview()
      }
    } else {
      this.getClinicalFormInfo()
    }
  },
  methods: {
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.SubmitClinicalFormAndSign(signInfo)
      } else {
        this.signVisible = false
      }
    },
    async SubmitClinicalFormAndSign(signInfo) {
      let params2 = {}
      let params = {
        QuestionAnswers: [],
        TableQuestionAnswerList: [],
      }
      params.ClinicalFormId = this.clinicalFormId
      params.VisitId = this.visitId
      params.ReadingId = this.readingId
      params.TrialId = this.trialId
      params.SubjectId = this.subjectId
      params.ClinicalDataTrialSetId = this.trialClinicalId
      Object.keys(this.questionForm).forEach(v => {
        let item = this.questionForm[v]
        if (item instanceof Array) {
          let TableQuestionAnswers = item.map(o => {
            if  (o instanceof Object) {
              return Object.keys(o).map(x => {
                return {
                  TableQuestionId: x,
                  Answer: o[x].toString()
                }
              })
            } else {
              params.QuestionAnswers.push({
                QuestionId: v,
                Answer: item.toString()
              })
            }
          })
          params.TableQuestionAnswerList.push({
            QuestionId: v,
            TableQuestionAnswers: TableQuestionAnswers
          })
        } else {
          params.QuestionAnswers.push({
            QuestionId: v,
            Answer: item.toString()
          })
        }
      })
      if (signInfo) {
        params2.signInfo = signInfo
      }
      params2.data = params
      params2.signInfo.TrialId = this.trialId
      this.loading = true
      let base64 = await this.getScreenshots()
      let imgBlob = this.convertBase64ToBlob(base64)
      let PicturePath = `/${this.trialId}/Read/${this.subjectId}/${this.visitId}/lc/${new Date().getTime()}.png`
      const result = await this.OSSclient.put(PicturePath, imgBlob)
      params2.PicturePath = this.$getObjectName(result.url)
      SubmitClinicalFormAndSign(params2).then(res => {
        this.$message.success(this.$t('trials:crcUpload:message:submittedSuccessfully'))
        this.close()
      }).catch(() => {
        console.log(this.$refs['signForm'])
        this.$refs['signForm'].btnLoading = false
      })
    },
    getClinicalFormInfo() {
      getClinicalFormInfo({
        ClinicalFormId: this.clinicalFormId
      }).then(res => {
        res.Result.map((v) => {
          if (v.ClinicalQuestionType === 'group' && v.Childrens.length === 0) return
          if (v.ClinicalQuestionType !== 'group' && v.ClinicalQuestionType !== 'table') {
            this.$set(this.questionForm, v.Id, v.Answer)
          }
          if (v.ClinicalQuestionType === 'table') {
            this.$set(this.questionForm, v.Id, v.TableAnswer)
          }
          if (v.Childrens.length > 0) {
            this.setChild(v.Childrens)
          }
        })
        console.log(this.questionForm)
        this.questions = res.Result
        this.isRender = true
        this.loading = false
      })
    },
    submitClinicalForm() {
      this.$refs.questions.validate(async valid => {
        if (!valid) return
        this.loading = true
        if ((this.data.UploadRole === 0 && [2, 3].includes(this.data.ClinicalDataLevel)) || !this.data.UploadRole || !this.data.ClinicalDataLevel) {
          let params = {
            QuestionAnswers: [],
            TableQuestionAnswerList: [],
          }
          params.ClinicalFormId = this.clinicalFormId
          params.ReadingId = this.visitId
          params.TrialId = this.trialId
          params.SubjectId = this.subjectId
          params.ClinicalDataTrialSetId = this.trialClinicalId
          Object.keys(this.questionForm).forEach(v => {
            let item = this.questionForm[v]
            if (item instanceof Array) {
              let isCheckBox = false
              let TableQuestionAnswers = item.map(o => {
                if  (o instanceof Object) {
                  return Object.keys(o).map(x => {
                    return {
                      TableQuestionId: x,
                      Answer: o[x].toString()
                    }
                  })
                } else {
                  isCheckBox = true
                }
              })
              if (isCheckBox) {
                params.QuestionAnswers.push({
                  QuestionId: v,
                  Answer: item.toString()
                })
              } else {
                params.TableQuestionAnswerList.push({
                  QuestionId: v,
                  TableQuestionAnswers: TableQuestionAnswers
                })
              }
            } else {
              params.QuestionAnswers.push({
                QuestionId: v,
                Answer: item.toString()
              })
            }
          })
          let base64 = await this.getScreenshots()
          let imgBlob = this.convertBase64ToBlob(base64)
          let PicturePath = `/${this.trialId}/Read/${this.subjectId}/${this.visitId}/lc/${new Date().getTime()}.png`
          const result = await this.OSSclient.put(PicturePath, imgBlob)
          params.PicturePath = this.$getObjectName(result.url)
          submitClinicalForm(params).then(res => {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.close()
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          const { ClinicalDataConfirmation } = const_.processSignature
          this.signCode = ClinicalDataConfirmation
          this.signVisible = true
        }
      })
    },
    convertBase64ToBlob(imageEditorBase64) {
      var base64Arr = imageEditorBase64.split(',')
      var imgtype = ''
      var base64String = ''
      if (base64Arr.length > 1) {
        // 如果是图片base64，去掉头信息
        base64String = base64Arr[1]
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(':') + 1,
          base64Arr[0].indexOf(';')
        )
      }
      // 将base64解码
      var bytes = atob(base64String)
      // var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length)
      // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode)

      // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }

      // 生成Blob对象（文件对象）
      return new Blob([bytesCode], { type: imgtype })
    },
    close() {
      this.$emit('close')
    },
    getSystemClinicalQuestionPreview() {
      getSystemClinicalQuestionPreview({
        SystemClinicalId: this.systemClinicalId
      }).then(res => {
        res.Result.map((v) => {
          if (v.ClinicalQuestionType === 'group' && v.Childrens.length === 0) return
          if (v.ClinicalQuestionType !== 'group' && v.ClinicalQuestionType !== 'table') {
            this.$set(this.questionForm, v.Id, v.Answer)
          }
          if (v.ClinicalQuestionType === 'table') {
            this.$set(this.questionForm, v.Id, [])
          }
          if (v.ClinicalQuestionType === 'checkbox') {
            this.$set(this.questionForm, v.Id, [])
          }
          if (v.Childrens.length > 0) {
            this.setChild(v.Childrens)
          }
        })
        this.questions = res.Result
        this.isRender = true
        this.loading = false
      })
    },
    getTrialClinicalQuestionPreview() {
      this.loading = true
      getTrialClinicalQuestionPreview({
        TrialClinicalId: this.trialClinicalId
      }).then(res => {
        res.Result.map((v) => {
          if (v.ClinicalQuestionType === 'group' && v.Childrens.length === 0) return
          if (v.ClinicalQuestionType !== 'group' && v.ClinicalQuestionType !== 'table') {
            this.$set(this.questionForm, v.Id, v.Answer)
          }
          if (v.ClinicalQuestionType === 'table') {
            this.$set(this.questionForm, v.Id, [])
          }
          if (v.ClinicalQuestionType === 'checkbox') {
            this.$set(this.questionForm, v.Id, [])
          }
          if (v.Childrens.length > 0) {
            this.setChild(v.Childrens)
          }
        })
        console.log(this.questionForm)
        this.questions = res.Result
        this.isRender = true
        this.loading = false
      })
    },
    setChild(obj) {
      obj.forEach(i => {
        console.log(i)
        if (i.ClinicalQuestionType !== 'group' && i.ClinicalQuestionType !== 'table') {
          this.$set(this.questionForm, i.Id, i.Answer)
        }
        if (i.ClinicalQuestionType === 'table') {
          this.$set(this.questionForm, i.Id, i.TableAnswer)
        }  else if (i.ClinicalQuestionType === 'checkbox') {
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer.split(',') : [])
          console.log(i.Answer ? i.Answer.split(',') : [])
          console.log(this.questionForm)
        }  else if (i.ClinicalQuestionType === 'number') {
          this.$set(this.questionForm, i.Id, i.Answer)
        } else if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },
    resetFormItemData(v, qs) {
      if (qs.ClinicalQuestionType === 'table') {
        this.questionForm[v] = []
      } else if (qs.ClinicalQuestionType === 'number') {
        this.questionForm[v] = 0
      } else if (qs.ClinicalQuestionType === 'checkbox') {
        this.questionForm[v] = []
      } else{
        this.questionForm[v] = ''
      }
    },
    setFormItemData(obj) {
      this.$set(this.questionForm, obj.key, JSON.parse(JSON.stringify(obj.val)))
    },
    async getScreenshots() {
      const divForDownloadViewport = document.querySelector(
        `form[data-viewport-uid="lc"]`
      )
      console.log(divForDownloadViewport)
      var canvas = await html2canvas(divForDownloadViewport)
      var pictureBaseStr = canvas.toDataURL('image/png', 1)
      return pictureBaseStr
    }
  }
}
</script>
<style lang="scss" scoped>
::-webkit-scrollbar {
    width: 7px;
    height: 7px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
  }
.tabContent{
  height:300px;
  overflow-y: auto;

}
.father:after{
  content: "";
  display: block;
  height: 0;
  clear:both;
  visibility: hidden;
}
</style>
