<template>
  <el-dialog
    title="填写表单"
    top="1vh"
    width="95%"
    :visible.sync="visible"
    fullscreen
    append-to-body
    class="intelligent-full"
    @closed="closeDialog"
  >
    <div class="dialog-container">
      <div v-loading="CRFLoading" element-loading-text="智能填充中，请稍等" class="crf-container">
        <div class="crf-content">
          <crf
            v-if="crfVisible"
            ref="crfComponent"
            :is-sign="isSign"
            :value="content"
            :height="'100%'"
            :js-arr="jsArr"
            :body-style-show="false"
          />
        </div>
      </div>
      <!-- 智能填充--暂时不让用户自己选择--先使用最新数据填充 -->
      <!-- <div v-if="dataForm.crfType!=='其它'" class="crf-data">
        <div>
          <template v-if="examData.length>0">
            <div v-for="(item,index) in examData" :key="index">
              <crf-data
                v-if="crfDataVisible && item.exams.length>0"
                v-model="item.value"
                :exam-name="item.name"
                :list="item.exams"
              />
            </div>
          </template>
          <div v-else class="nodata">
            <img src="@/assets/img/nodata.png" alt="">
          </div>
        </div>
        <el-button type="primary" class="button-full">一键填充</el-button>
      </div> -->
    </div>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="submit">{{ $t('confirm') }}</el-button>
    </template>
    <img-editor
      v-if="imgEditorVisible"
      ref="imgEditorRef"
      @fullImgBack="fullImgBack"
      @closeDialog="imgEditorVisible=false"
    />
  </el-dialog>
</template>

<script>
const Base64 = require('js-base64').Base64
import crf from './load_content.vue'
import crfData from '@/components/hm-crf/crf-data.vue'
import { formatDate } from '@/utils/index.js'
import imgEditor from './img-editor.vue'
import IntelligentFill from '@/mixins/IntelligentFill'
export default {
  components: { crf, crfData, imgEditor },
  mixins: [IntelligentFill],
  props: {
    title: {
      type: String,
      default: ''
    },
    // 是否有签字功能
    isSign: {
      type: Boolean,
      default: false
    },
    // 更新父组件哪个文件
    updataFile: {
      type: String,
      default: ''
    },
    // 是否判断签名
    isJudgeSign: {
      type: Boolean,
      default: false
    },
    patientId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      crfVisible: false,
      crfDataVisible: true,
      imgEditorVisible: false,
      jsArr: [],
      inputDate: formatDate(new Date(), 'yyyy-MM-dd'),
      // CRF内容，填充用
      content: '',
      dataForm: {
        name: '',
        description: '',
        content: '',
        formId: '',
        id: ''
      },
      // 获取的检查数据，【item.value】为v-model绑定值，即用于填充左侧iframe
      examData: [],
      operaList: [],
      surgicalSiteList: [],
      operaListInterval: null,
      surgicalSiteInterval: null
    }
  },
  mounted() {
    // this.getLXDJCJm()
  },
  methods: {
    init() {
      this.visible = true
      this.crfVisible = false
      this.$nextTick(() => {
        this.getOperaList()
        this.getSurgicalSiteList()
      })
      // iframe调取vue中的方法
      window['goBack'] = (imgUrl, imgAlt) => {
        // console.log(imgUrl)
        this.imgEditorVisible = true
        this.$nextTick(() => {
          // 获取已保存的手术列表
          if (this.$refs.imgEditorRef) {
            this.$refs.imgEditorRef.imgUrl = imgUrl
            this.$refs.imgEditorRef.imgAlt = imgAlt
            this.$refs.imgEditorRef.init()
          }
        })
      }
      // console.log(this.dataForm)
      this.$nextTick(() => {
        this.$http.get(`/quguang/from/data/${this.dataForm.formId}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            console.log(res.data)
            res.data.formId = res.data.id
            delete res.data.id
            this.dataForm = { ...res.data }
            this.content = Base64.decode(res.data.formContent)
            this.crfVisible = true
            this.dataForm.isWrite === 0 ? (this.getFirstFeedbackData('智能填充', this.dataForm.formId, this.patientId), this.setAutoDate()) : this.setAutoDate()
          }
        }).catch(() => { })
      })
    },
    // 获取术士项目列表
    async getOperaList() {
      const { data: res } = await this.$http.get('/quguang/opera/patient/getOperaList')
      if (res.code === 0) {
        res.data.forEach(item => {
          item.name = item.operaName
          item.id = item.operaId
        })
        this.operaList = res.data
        this.operaListInterval = setInterval(() => {
          if (this.$refs.crfComponent && this.$refs.crfComponent.$el.contentWindow.multipleSelect) {
            console.log(this.$refs.crfComponent.$el)
            clearInterval(this.operaListInterval)
            this.$refs.crfComponent.$el.contentWindow.multipleSelect(this.operaList, 'operationProject')
            this.getsaveOperaList(this.dataForm.formId)
          }
        }, 500)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 获取裂隙灯检查接口获取
    getLXDJCJm() {
      const ceshi = [{
        id: 1,
        name: '测试1'
      }, {
        id: 2,
        name: '测试2'
      }, {
        id: 3,
        name: '测试3'
      }]
      setTimeout(() => {
        this.$refs.crfComponent.$el.contentWindow.lxdjcInput(ceshi)
      }, 5000)
    },
    // 获取术士部位列表
    async getSurgicalSiteList() {
      // 类型 1:职位，2:手术间，3:麻醉方式,4麻醉会诊,5手术切口等级,6手术部位
      const { data: res } = await this.$http.get('/quguang/sys/param/getList', {
        params: {
          type: 6
        }
      })
      if (res.code === 0) {
        this.surgicalSiteList = res.data
        this.surgicalSiteInterval = setInterval(() => {
          if (this.$refs.crfComponent && this.$refs.crfComponent.$el.contentWindow.multipleSelect) {
            console.log(this.$refs.crfComponent.$el)
            clearInterval(this.surgicalSiteInterval)
            this.$refs.crfComponent.$el.contentWindow.multipleSelect(this.surgicalSiteList, 'surgicalSite')
          }
        }, 500)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 设置签名日期
    setAutoDate() {
      setTimeout(() => {
        if (this.$refs.crfComponent && this.$refs.crfComponent.$el.contentWindow.dataFill) {
          this.$refs.crfComponent.$el.contentWindow.autoFullDate(this.$moment().format('YYYY-MM-DD'))
        }
      }, 1000)
    },
    // 将图片填充回iframe
    fullImgBack(base64String, imgAlt) {
      this.$refs.crfComponent.$el.contentWindow.imgEditFull(base64String, imgAlt)
    },
    // 把编辑的内容保存
    submit() {
      // 如果isJudgeSign为true,需要签名后保存并且没有签名不予通过 return
      if (this.isJudgeSign && !this.$refs.crfComponent.$el.contentWindow.isSignSuccess()) {
        this.$message({
          message: '请让患者签名后再保存哦',
          type: 'warning'
        })
        return
      }
      this.saveOrderScheduled()
    },
    // 保存表单
    saveForm() {
      const ifr = this.$refs.crfComponent.$el
      const ifrDoc = ifr.contentWindow.document || ifr.contentDocument
      const body = ifrDoc.getElementsByTagName('body')[0]
      const crfContent = body.innerHTML
      this.$http.post('/quguang/from/data/saveWriteVisit', {
        formContent: Base64.encode(crfContent),
        // inputDate: this.inputDate,
        id: this.dataForm.formId
      }).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.visible = false
          }
        })
        console.log()
        this.$emit(this.updataFile, this.dataForm)
      })
    },
    // 保存预约手术信息
    async saveOrderScheduled() {
      console.log(this.$refs.crfComponent.$el.contentWindow.getFormValue())
      const FormValue = this.$refs.crfComponent.$el.contentWindow.getFormValue().hmselectmultipleValue
      console.log(FormValue)
      // return
      // 如果没选择手术不需要掉保存手术方式接口
      if (FormValue.operationProjectOD && FormValue.operationProjectOD.length <= 0 && FormValue.operationProjectOS.length <= 0 && FormValue.operationProjectOU.length <= 0) {
        this.saveForm()
      } else {
        const { data: res } = await this.$http.post('/quguang/opera/patient/save', {
          crfFormId: this.dataForm.formId,
          operaODOS: [{
            eyeType: 'OD',
            operaList: FormValue.operationProjectOD,
            operationPostionName: FormValue.operationProjectOD ? '右眼' : ''
          }, {
            eyeType: 'OS',
            operaList: FormValue.operationProjectOS,
            operationPostionName: FormValue.operationProjectOS ? '左眼' : ''
          }, {
            eyeType: 'OU',
            operaList: FormValue.operationProjectOU,
            operationPostionName: FormValue.operationProjectOU ? '双眼' : ''
          }],
          patientIdNumber: this.dataForm.patientIdNumber
        })
        if (res.code === 0) {
          this.saveForm()
        } else {
          this.$message.error(res.msg)
        }
      }
    },
    closeDialog() {
      this.visible = false
      this.imgEditorVisible = false
      this.$emit('closeDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.intelligent-full {
  .dialog-container {
    height: calc(100vh - 1vh - 54px - 70px);
    display: flex;
    .crf-container {
      display: inline-block;
      vertical-align: top;
      width: 100%;
      height: 100%;
      // background-color: aquamarine;
      border: 1px solid;

      .crf-content {
        text-align: center;
        height: 100%;
      }
    }
    .crf-data {
      position: relative;
      margin-left: 24px;
      width: 30%;
      .nodata {
        width: 300px;
        height: 100%;
        display: flex;
        align-items: center;
        img {
          width: 300px;
        }
      }
      .button-full {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 95%;
      }
    }
  }

  .btn-fill {
    margin-right: calc(100% - 960px - 160px);
  }
}
</style>
