<script name="stamp" setup>
import * as PdfJs from 'pdfjs-dist/legacy/build/pdf.js'
// import * as workerSrc from 'pdfjs-dist/build/pdf.worker.entry'
import { ref, onMounted, nextTick, getCurrentInstance } from 'vue'
// import { sealList } from '@/http/apis/unitSet/sealConfiguration'
import { useRoute, useRouter } from 'vue-router'
// import base from './base64'
import { handler, notSealedPdf, projectDetail, saveAuditOpinoin, signSeal } from '@/http/apis/toDoCenter/todoList'
// import { findUrlById } from '@/http/apis/commonApi'
import { storeToRefs } from 'pinia'
// import store from '@/store'
import SEAL from '@/assets/images/seal.png'
import store from '@/store'
import { fileFormatVerification, handleFileSuccess, handleFilePreview, handleFileError, fileDesc, fileTypes } from '@/utils/uploadAction.js'
import { downFileById } from '@/http/apis/commonApi'
const workerSrc = import('pdfjs-dist/build/pdf.worker.entry')
const
  userInfo = storeToRefs(store.userStore).userInfo,
  { proxy } = getCurrentInstance(),
  route = useRoute(),
  router = useRouter(),
  uploadUrl = store.dictStore.uploadUrl,
  // 印章列表
  sealLists = ref([{ src: SEAL }]),
  // 盖章文件
  numPages = ref(0),
  docsData = ref({
    loadType: 'url',
    title: route.query.filename,
    docValue: ''
  }),
  isSureSign = ref(false),
  isCommit = ref(false), // 是否提交意见
  notSealedFileId = ref(),
  // 获取盖章文件
  getSealView = async () => {
    const res = await notSealedPdf({
      projectId: route.query.projectId,
      auditOpinion: form.value?.comment || undefined
    })
    isCommit.value = res.data?.isCommit || false
    const data = await downFileById({ fileId: res.data.fileId })
    notSealedFileId.value = res.data.fileId
    const url = URL.createObjectURL(data)
    docsData.value.docValue = url
    renderPdf(docsData.value)
  },
  // 渲染pdf
  renderPdf = (docs) => {
    // 设定pdfjs的 workerSrc 参数
    // NOTE: 这一步要特别注意，网上很多关于pdfjs的使用教程里漏了这一步，会出现workerSrc未定义的错误
    PdfJs.GlobalWorkerOptions.workerSrc = workerSrc
    // 获取文档方式
    const loadType = docs.loadType
    // 获取文档值
    const docValue = docs.docValue
    // PDF文件
    let pdfValue = null
    if (loadType === 'byBase64') {
      // 通过文档编号从服务端获取PDF的Base64字符串
      // var pdfBase64 = getPDFBase64ByAjax(docValue);
      // 通过Base64获取PDF
      var pdfBase64 = docValue
      var pdfFileBinary = convertDataURIToBinary(pdfBase64)
      pdfValue = pdfFileBinary
    } else {
      pdfValue = docValue
    }

    // Asynchronous download of PDF
    var loadingTask = PdfJs.getDocument(pdfValue)
    // 解析pdf
    loadingTask.promise.then(
      function (pdf) {
        numPages.value = pdf.numPages
        // 遍历 pdf.numPages， 调用 renderer(pdf, n) 获取多文档展示
        // Fetch the first page
        // const pageNumber = 1;
        nextTick(() => {
          renderer(pdf, 1)
        })
        // for (let index = 1; index <= pdf.numPages; index++) {
        //   // nextTick(() => {
        //   //   renderer(pdf, index)
        //   // })
        // }
      },
      function (reason) {
        // PDF loading error
        console.error(reason)
      }
    )
  },
  renderer = (pdf, pageNumber) => {
    pdf && pdf.getPage(pageNumber).then(function (page) {
      // pdf 解析的比例， 获取原始文档尺寸 scale = 1; 如果文档放大，印章x y 需要同比例缩放
      const scale = 2
      const viewport = page.getViewport({ scale })
      // Prepare canvas using PDF page dimensions
      // 遍历 pdf.numPages， 传递 不同的 Canvas ID
      const canvas = document.getElementById('pageCanvas_' + pageNumber)
      const context = canvas.getContext('2d')
      // 设置 canvas
      canvas.width = 2380
      canvas.height = 3368
      canvas.style.width = 1190 + 'px'
      // canvas.style.height = viewport.heigh + 'px';

      // 设置外层大小
      var pageView = document.getElementById('pageView_' + pageNumber)
      pageView.style.height = viewport.height / scale + 'px'
      pageView.style.width = viewport.width / scale + 'px'

      // Render PDF page into canvas context
      page.render({
        canvasContext: context,
        viewport: viewport
      })

      if (pageNumber < numPages.value) {
        renderer(pdf, pageNumber + 1)
      }
    })
  },
  // 将encodeBase64解码
  convertDataURIToBinary = (dataURI) => {
    dataURI = dataURI.replace(/[\r\n]/g, '')
    var raw = window.atob(dataURI) // window.atob()解码使用 base-64 编码的字符串
    var rawLength = raw.length
    // 转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068
    var array = new Uint8Array(new ArrayBuffer(rawLength))
    for (let i = 0; i < rawLength; i++) {
      array[i] = raw.charCodeAt(i) // charCodeAt() 方法可返回指定位置的字符的 Unicode 编码
    }
    return array
  },
  // 删除印章
  delSealItem = (index) => {
    posBean.value.splice(index, 1)
  },
  // 拖拽印章
  // 拖拽事件
  // 触发源
  posBean = ref([]),
  _ondragstart = (event, sealData, type) => {
    console.log('start')
    if (isSureSign.value || (posBean.value?.length && type)) {
      proxy.$message.warning('请勿重复盖章！')
    } else {
      const pos = {
        posX: 0, // 签署位置横坐标
        posY: 0 // 签署位置纵坐标
      }
      const dragData = Object.assign(pos, sealData)
      event.dataTransfer.setData('Text', JSON.stringify(dragData)) // dataTransfer存储拖放时要携带的数据
      //  IE下没有 setDragImage 这个属性
      if (event.dataTransfer.setDragImage) {
        // 设置鼠标位置
        event.dataTransfer.setDragImage(event.target, 62, 62) // 发生拖动时，从拖动目标(dragstart事件触发的元素)生成半透明图像，并在拖动过程中跟随鼠标指针
      }
    }
  },
  _ondragend = (event, index) => {
    console.log('end')
    if (index >= 0) {
      delSealItem(index)
    }
  },

  // 目标源
  _ondragenter = (event) => {
    console.log('enter')
  },

  _ondragover = (event) => {
    event.preventDefault()
    event.stopPropagation()
    console.log('over')
  },

  _ondragleave = (event) => {
    console.log('leave')
  },

  _ondrop = (event, page) => {
    event.preventDefault()
    event.stopPropagation()
    console.log('drop')
    if (event.dataTransfer.getData('Text')) {
      const dragData = JSON.parse(event.dataTransfer.getData('Text'))
      // const pdf = document.getElementById('signContainer')
      // const scrollbar = document.getElementsByClassName('el-scrollbar')
      // const pageView = document.getElementById('pageView_' + page)
      // dragData.posX = event.pageX - pdf.offsetLeft - pageView.offsetLeft
      // dragData.posY =
      //   pageView.offsetHeight -
      //   (event.pageY - (pdf.offsetTop + pageView.offsetTop - pdf.scrollTop))
      dragData.posX = event.offsetX
      dragData.posY = 842 - event.offsetY
      // dragData.posY = 842 - (event.offsetY + pdf.scrollTop - ((page - 1) * 852))
      // 存储提交印章
      dragData.posPage = page
      dragData.width = dragData.width || 124
      dragData.height = dragData.height || 124
      dragData.id = 'seal_' + Date.parse(new Date())
      dragData.left = event.offsetX - dragData.width / 2
      dragData.top = event.offsetY - dragData.height / 2
      // dragData.left = dragData.posX - dragData.width / 2
      // dragData.top =
      //   pageView.offsetHeight - dragData.height / 2 - dragData.posY
      dragData.fileUrl = '222'
      posBean.value.push(dragData)
      console.log(dragData, '印章签署相关信息')
    }
  },

  // 确认签署
  // submitSign = async (formEl) => {
  //   if (!posBean.value?.length) {
  //     proxy.$message.warning('请先签署')
  //   }
  //   console.log(posBean)
  //   if (!formEl) {
  //     return
  //   }
  //   await formEl.validate(async valid => {
  //     if (valid) {
  //       loading.value = true
  //       console.log(posBean)
  //       const postData = posBean.value[0]
  //       try {
  //         await signSeal({
  //           posPage: postData.posPage,
  //           posX: postData.posX,
  //           posY: postData.posY,
  //           // sealCode: postData.sealCode,
  //           projectId: route.query.projectId * 1,
  //           signType: 1
  //           // instName: route.query.instName,
  //           // taskId: route.query.taskId
  //         })
  //         try {
  //           const res = await handler({
  //             instanceId: route.query.instanceId,
  //             projectId: route.query.projectId,
  //             taskId: route.query.taskId,
  //             action: 'PASS',
  //             auditInfo: {
  //               text: form.value.comment,
  //               attachments: form.value.attachments.map((i) => ({
  //                 fileId: i.response.data.id,
  //                 fileName: i.response.data.originalFileName
  //               }))
  //             }
  //           })
  //           isSureSign.value = true
  //           loading.value = false
  //           if (res.data === 'TASKID_ERROR') {
  //             proxy.$message.warning('当前审批任务有变动，请返回待我处理列表！')
  //             router.push({ name: 'waitMeToHandle' })
  //           } else {
  //             proxy.$message.success('签署成功！')
  //             if (res.data) {
  //               router.push({
  //                 name: 'handleDuringExamine',
  //                 query: {
  //                   ...route.query,
  //                   taskId: res.data
  //                 }
  //               })
  //             }
  //           }
  //         } catch (e) {
  //           loading.value = false
  //         }
  //       } catch (e) {
  //         loading.value = false
  //       }
  //     }
  //   })
  // },
  // 意见表单
  formRef = ref(),
  form = ref({
    attachments: []
  }),
  rules = {
    comment: [{ required: true, message: '请输入意见', trigger: 'blur' }]
  },
  loading = ref(false),
  // 审核意见提交
  visible = ref(false),
  submit = async formEl => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        const postData = {
          instanceId: route.query.instanceId,
          projectId: route.query.projectId,
          taskId: route.query.taskId,
          action: 'PASS',
          auditInfo: {
            text: form.value.comment,
            attachments: form.value.attachments.map((i) => ({
              fileId: i.response.data.id,
              fileName: i.response.data.originalFileName
            }))
          }
        }
        const res = await saveAuditOpinoin(postData)
        if (res.data === 'TASKID_ERROR') {
          proxy.$message.warning('当前审批任务有变动，请返回待我处理列表！')
          router.push({ name: 'waitMeToHandle' })
        } else {
          getSealView()
          proxy.$message.success('提交成功！')
          visible.value = false
        }
      }
    })
  },
  // 盖章
  signLoaing = ref(false),
  submitSign = async () => {
    signLoaing.value = true
    let postData = {
      posPage: 6,
      posX: 487,
      posY: 540
    }
    if (route.query.instName === '项目预审审批流程') {
      if (userInfo.value.empPosUnitCode === orgCodeOne.value) {
        postData = {
          posPage: 6,
          posX: 487,
          posY: 540
        }
      } else if (userInfo.value.empPosUnitCode === orgCodeTwo.value) {
        postData = {
          posPage: 6,
          posX: 487,
          posY: 380
        }
      }
    }
    console.log(userInfo.value.empPosUnitCode)
    console.log(orgCodeTwo.value)
    console.log(userInfo.value.empPosUnitCode === orgCodeTwo.value)
    console.log(postData)
    if (route.query.instName === '项目预审审批流程' && userInfo.value.empPosUnitCode !== orgCodeOne.value && !detailData.value.isHigherSuperOrg) {
      const res1 = await handler({
        instanceId: route.query.instanceId,
        projectId: route.query.projectId,
        projectCode: route.query.projectCode,
        taskId: route.query.taskId,
        action: 'PASS'
      })
      if (res1.data === 'TASKID_ERROR') {
        proxy.$message.warning('当前审批任务有变动，请返回待我处理列表！')
        router.push({ name: 'waitMeToHandle' })
      } else {
        proxy.$message.success('签署成功！')
        router.go(-1)
      }
    } else {
      const res = await signSeal({
        ...postData,
        notSealedFileId: notSealedFileId.value,
        projectId: route.query.projectId * 1,
        signType: 1
      })
      const data = await downFileById({ fileId: res.data })
      const url = URL.createObjectURL(data)
      docsData.value.docValue = url
      renderPdf(docsData.value)
      signLoaing.value = false
      isSureSign.value = true
      const res1 = await handler({
        instanceId: route.query.instanceId,
        projectId: route.query.projectId,
        projectCode: route.query.projectCode,
        taskId: route.query.taskId,
        action: 'PASS'
      })
      if (res1.data === 'TASKID_ERROR') {
        proxy.$message.warning('当前审批任务有变动，请返回待我处理列表！')
        router.push({ name: 'waitMeToHandle' })
      }
    }
  },
  // 项目详情
  detailData = ref({}),
  orgCodeOne = ref(), // 预审第一个章的code
  orgCodeTwo = ref(),
  getDetail = async () => {
    const res = await projectDetail(route.query.projectId)
    detailData.value = res.data
    orgCodeOne.value = detailData.value.isSuperOrg ? detailData.value.superOrgCode : detailData.value.buildOrgCode
    orgCodeTwo.value = detailData.value.isHigherSuperOrg ? detailData.value.higherSuperOrgCode : ''
  }
onMounted(() => {
  getSealView()
  getDetail()
})
</script>

<template>
  <div class="footerPage">
    <el-row :gutter="8" :class="`h-full overflow-hidden ${!isSureSign?'':''}`">
      <el-col :span="24" class="h-full">
        <div id="signContainer" class="sign_content h-full">
          <div
            v-for="i in numPages"
            :id="`pageView_${i}`"
            :key="i"
            class="pageView"
            @dragenter="_ondragenter($event)"
            @dragover="_ondragover($event)"
            @dragleave="_ondragleave($event)"
            @drop="_ondrop($event, i)"
          >
            <canvas :id="`pageCanvas_${i}`" class="pageCanvas"></canvas>
            <div v-if="!isSureSign">
              <template v-if="posBean.length > 0">
                <div
                  v-for="(item, index) in posBean"
                  :key="index"
                >
                  <div
                    v-if="item.posPage === i"
                    :id="`drag${item.id}`"
                    class="sealView"
                    draggable="true"
                    :style="
                      `
                width: ${item.width}px;
                height: ${item.height}px;
                left: ${item.left}px;
                top: ${item.top}px;`
                    "
                    @dragstart="_ondragstart($event, item, 0)"
                    @dragend="_ondragend($event, index)"
                  >
                    <img
                      :src="item.src"
                      style="width: 100%; height: 100%"
                    />
                    <p class="sealDel" @click="delSealItem(index)">
                      <el-icon><CircleClose /></el-icon>
                    </p>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </el-col>
      <el-col v-if="false" :span="6">
        <el-card>
          <template #header>
            <el-popover
              placement="top-start"
              :width="100"
              trigger="hover"
              content="将印章拖入文件完成盖章"
            >
              <template #reference>
                <span> 我的印章</span>
              </template>
            </el-popover>
          </template>
          <div
            v-for="(item,index) in sealLists"
            :key="index"
            class="sealItems"
            sealCode="签署人标识"
            draggable="true"
            @dragstart="_ondragstart($event, item, 1)"
            @dragend="_ondragend($event)"
          >
            <img :src="item.src" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card
      v-if="false"
      shadow="never"
      style="height: auto"
      class="footer"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        label-suffix=":"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="`意见`"
              prop="comment"
            >
              <el-input
                v-model="form.comment"
                maxlength="200"
                placeholder="请输入"
                show-word-limit
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="附件"
              prop="files"
            >
              <el-upload
                v-model:file-list="form.attachments"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, form.attachments)"
                :on-error="handleFileError"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                multiple
                :limit="10"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" class="mr-4">上传附件</el-button>
                <template #tip>
                  <div class="el-upload__tip">支持{{ fileDesc }}文件</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-button type="primary" :loading="loading" @click="submitSign(formRef)">确认签署</el-button>
          <el-button @click="router.go(-1)">取消签署</el-button>
        </el-row>
      </el-form>
    </el-card>
    <div class="footer">
      <el-button
        v-if="!isSureSign"
        type="primary"
        :loading="signLoaing"
        @click="submitSign"
      >
        确认盖章
      </el-button>
      <el-button @click="router.go(-1)">返回</el-button>
    </div>
    <el-dialog
      :model-value="!isCommit"
      title="填写审核意见"
      width="600px"
      destroy-on-close
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        label-suffix=":"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="审核意见"
              prop="comment"
            >
              <el-input
                v-model="form.comment"
                maxlength="200"
                placeholder="请输入"
                show-word-limit
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="附件"
              prop="files"
            >
              <el-upload
                v-model:file-list="form.attachments"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, form.attachments)"
                :on-error="handleFileError"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                multiple
                :limit="10"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" class="mr-4">上传附件</el-button>
                <template #tip>
                  <div class="el-upload__tip">支持{{ fileDesc }}文件</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="flex justify-center">
          <el-button
            class="ml-22"
            type="primary"
            @click="submit(formRef)"
          >
            提交
          </el-button>
          <el-button
            @click="$router.go(-1)"
          >
            返回
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less">
.pageView,
.sign_content {
  position: relative;
  line-height: 0em;
}
.pageView {
  overflow: hidden;
  margin:0 auto;
  position: relative;
}
.sign_content {
  flex: 1;
  overflow-y: scroll;
  border-radius: 8px 8px 0 0;
  margin: 0 auto;
  width: 652px;
}
.pageCanvas {
  position: absolute;
  left: 0;
  top: 0;
}
.sealView {
  position: absolute;
  background-size: cover;
}
.pageView {
  margin: 10px auto;
  &#pageView_1 {
    margin-top: 0;
  }
}
/* 必要end */
.sign_warp {
  background: #f0f2f5;
  position: absolute;
  width: 100%;
  display: flex;
  top: 0;
  bottom: 57px;
  height: 100vh;
  overflow: hidden;
  padding: 24px 160px 57px;
  &.sureSignWrap {
    padding: 24px 160px 10px;
    .sign_left,
    .sign_right,
    .sign_content {
      height: calc(100vh - 34px);
    }
  }
}
.sealItems {
  width: 124px;
  height: 124px;
  margin: 10px;
  margin: 15px auto;
  img {
    width: 100%;
    height: 100%;
  }
}
.sealDel {
  position: absolute;
  top: -10px;
  right: -10px;
  background-color: #fff;
  color: #000;
  line-height: 16px;
  font-size: 14px;
  cursor: pointer;
  border: 0;
}
</style>
