<template>
  <el-dialog
    v-dialogDrag
    v-loading.fullscreen.lock="fullscreenLoading"
    :before-close="cancel"
    :title="dialogTitle"
    :visible.sync="dialogShowFlag"
    append-to-body
    width="1090px"
  >
    <div id="printcontent" style="height: 600px; overflow-y: scroll; padding: 0 20px">
      <!-- <vue-easy-print tableShow ref="printRef"> -->
      <div id="checkId2">
        <div style="text-align: center; font-weight: 600; font-size: 16px">机具设备退料单</div>
        <div class="info" style="margin-top: 10px; display: flex; align-items: center">
          <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
            <div>
              <span>工程名称：</span>
              <span>{{ rowObj.proName }}</span>
            </div>
            <div>
              <span>退料时间：</span>
              <span>{{ rowObj.createTime }}</span>
            </div>
          </div>
          <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px; text-align: right">
            <div>
              <span>退料单位：</span>
              <span>{{ rowObj.unitName }}</span>
            </div>
            <div>
              <span>单号：</span>
              <span>{{ rowObj.code }}</span>
            </div>
          </div>
        </div>

        <table border="1.5" cellspacing="0" cellpadding="8" style="width: 100%; border-collapse: collapse">
          <thead>
            <tr>
              <th style="width: 60px; text-align: center">编号</th>
              <th style="width: 120px; text-align: center">物资类型</th>
              <th style="text-align: center">物资名称</th>
              <th style="text-align: center">规格型号</th>
              <th style="text-align: center">计量单位</th>
              <th style="width: 200px; text-align: center">退料数量</th>
              <th style="width: 200px; text-align: center">编号</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in tableData" :key="index">
              <!-- 序号 -->
              <td style="text-align: center">{{ index + 1 }}</td>

              <!-- 物资类型 -->
              <td style="text-align: center" :title="row.materialType">{{ row.materialType }}</td>

              <!-- 物资名称 -->
              <td style="text-align: center" :title="row.typeName">{{ row.typeName }}</td>

              <!-- 规格型号 -->
              <td style="text-align: center" :title="row.typeModel">{{ row.typeModel }}</td>

              <!-- 计量单位 -->
              <td style="text-align: center" :title="row.unitName">{{ row.unitName }}</td>

              <!-- 退料数量 -->
              <td style="text-align: center">{{ row.preNum }}</td>

              <!-- 编号 -->
              <td style="text-align: center">
                <span v-if="row.manageType == 1">无编码</span>
                <span
                  v-if="row.manageType == 0"
                  style="color: rgb(2, 167, 240); cursor: pointer"
                  @click="checkDetail(row)"
                >
                  查看明细
                </span>
              </td>
            </tr>
          </tbody>
        </table>

        <div class="order_footer">
          <!-- <div>审核人：</div> -->
          <div class="item" style="width: 28%; display: flex; align-items: center; flex-wrap: wrap">
            <div style="width: 30%">审核人：</div>
            <div
              style="width: 70%; display: flex; align-items: center; flex-wrap: wrap"
              v-if="backApplyInfo.approveSignList && backApplyInfo.approveSignList.length > 0"
            >
              <div
                style="width: 80%; margin-left: 20px; height: 40px; transform: translateY(-30px)"
                v-for="(item, index) in backApplyInfo.approveSignList"
                :key="index"
              >
                <img
                  :src="item.outSignUrl"
                  style="width: 40px; height: 90px; max-width: 100%"
                  :style="{ transform: item.outSignType == 0 ? 'rotate(-90deg)' : '' }"
                  alt=""
                />
              </div>
            </div>
          </div>
          <div class="item" style="width: 28%; display: flex; align-items: center; flex-wrap: wrap">
            <div style="width: 30%">退料人：</div>
            <div
              style="width: 70%; display: flex; align-items: center; flex-wrap: wrap"
              v-if="backApplyInfo.backSignUrl"
            >
              <div style="width: 80%; margin-left: 20px">
                <img
                  :src="backApplyInfo.backSignUrl"
                  style="width: 40px; height: 100px; max-width: 100%"
                  :class="{ 'is-rotate': backApplyInfo.backSignType == 0 }"
                  alt=""
                />
              </div>
            </div>
          </div>
          <div class="item" style="width: 28%; display: flex; align-items: center; flex-wrap: wrap">
            <div style="width: 30%">制单：</div>
            <div style="width: 70%; display: flex; align-items: center; flex-wrap: wrap" v-if="backApplyInfo.signUrl">
              <div style="width: 80%; margin-left: 20px">
                <img
                  :src="backApplyInfo.signUrl"
                  style="width: 40px; height: 100px; max-width: 100%"
                  :class="{ 'is-rotate': backApplyInfo.signType == 0 }"
                  alt=""
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- </vue-easy-print> -->
    </div>
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="height: 500px; overflow-y: scroll; padding: 0 20px">
        <!-- <vue-easy-print tableShow ref="remarksPrintRef"> -->
        <div id="checkIdTwo">
          <div class="remarks_box">
            <div class="remarks_box_title">退料编码明细</div>
          </div>
          <div class="info" style="margin-top: 10px; display: flex; align-items: center">
            <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
              <div>
                <span>工程名称：</span>
                <span>{{ rowObj.proName }}</span>
              </div>
              <div>
                <span>退料时间：</span>
                <span>{{ rowObj.createTime }}</span>
              </div>
            </div>
            <div
              class="item"
              style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px; text-align: right"
            >
              <div>
                <span>退料单位：</span>
                <span>{{ rowObj.unitName }}</span>
              </div>
              <div>
                <span>单号：</span>
                <span>{{ rowObj.code }}</span>
              </div>
            </div>
          </div>

          <table border="1.5" cellspacing="0" cellpadding="8" style="width: 100%; border-collapse: collapse">
            <thead>
              <tr>
                <th style="width: 60px; text-align: center">序号</th>
                <th style="text-align: center">物资类型</th>
                <th style="text-align: center">物资名称</th>
                <th style="text-align: center">规格型号</th>
                <th style="text-align: center">设备编号</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in tableSubData" :key="index">
                <!-- 序号 -->
                <td style="text-align: center">{{ index + 1 }}</td>

                <!-- 物资类型 -->
                <td style="text-align: center">{{ row.materialType }}</td>

                <!-- 物资名称 -->
                <td style="text-align: center">{{ row.typeName }}</td>

                <!-- 规格型号 -->
                <td style="text-align: center">{{ row.materialName }}</td>

                <!-- 设备编号 -->
                <td style="text-align: center">{{ row.maCode }}</td>
              </tr>
            </tbody>
          </table>

          <div class="order_footer">
            <!-- <div>审核人：</div> -->
            <div class="item" style="width: 28%; display: flex; align-items: center; flex-wrap: wrap">
              <div style="width: 30%">审核人：</div>
              <div
                style="width: 70%; display: flex; align-items: center; flex-wrap: wrap"
                v-if="backApplyInfo.approveSignList && backApplyInfo.approveSignList.length > 0"
              >
                <div
                  style="width: 80%; margin-left: 20px; height: 40px; transform: translateY(-30px)"
                  v-for="(item, index) in backApplyInfo.approveSignList"
                  :key="index"
                >
                  <img
                    :src="item.outSignUrl"
                    style="width: 40px; height: 90px; max-width: 100%"
                    :style="{ transform: item.outSignType == 0 ? 'rotate(-90deg)' : '' }"
                    alt=""
                  />
                </div>
              </div>
            </div>
            <div class="item" style="width: 28%; display: flex; align-items: center; flex-wrap: wrap">
              <div style="width: 30%">退料人：</div>
              <div
                style="width: 70%; display: flex; align-items: center; flex-wrap: wrap"
                v-if="backApplyInfo.backSignUrl"
              >
                <div style="width: 80%; margin-left: 20px">
                  <img
                    :src="backApplyInfo.backSignUrl"
                    style="width: 40px; height: 100px; max-width: 100%"
                    :class="{ 'is-rotate': backApplyInfo.backSignType == 0 }"
                    alt=""
                  />
                </div>
              </div>
            </div>
            <div class="item" style="width: 28%; display: flex; align-items: center; flex-wrap: wrap">
              <div style="width: 30%">制单：</div>
              <div style="width: 70%; display: flex; align-items: center; flex-wrap: wrap" v-if="backApplyInfo.signUrl">
                <div style="width: 80%; margin-left: 20px">
                  <img
                    :src="backApplyInfo.signUrl"
                    style="width: 40px; height: 100px; max-width: 100%"
                    :class="{ 'is-rotate': backApplyInfo.signType == 0 }"
                    alt=""
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- </vue-easy-print> -->
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="remarksPrint">打印</el-button>
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button type="primary" @click="print">打印</el-button>
      <el-button @click="dialogShowFlag = false">关 闭</el-button>
    </div>
  </el-dialog>
</template>
<script>
import vueEasyPrint from 'vue-easy-print'
import { getBackApplyInfo, updatePrintStatus } from '@/api/back/index.js'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import printJS from 'print-js'
import request from '@/utils/request'
// import { getViewByApply,materialReturnNoteByApply } from "@/api/claimAndRefund/return.js"
export default {
  components: { vueEasyPrint },
  props: {
    // 弹窗是否显示
    isShowFlag: {
      type: Boolean,
      default: false
    },
    // 对应操作数据键值
    priKey: {
      type: [String, Number],
      default: ''
    },
    //弹窗标题
    dialogTitle: {
      type: String,
      default: ''
    },
    rowObj: {
      type: Object,
      default: {}
    }
  },
  watch: {
    isShowFlag(val) {
      if (val) {
        this.init()
      }
    }
  },
  computed: {
    dialogShowFlag: {
      get() {
        return this.isShowFlag
      },
      set(v) {
        this.$emit('update:isShowFlag', v)
      }
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      tableData: [],
      tableSubData: [],
      open: false,
      title: '',
      backApplyInfo: {}
    }
  },
  methods: {
    init() {
      // let params = {
      //   id: this.rowObj.id,
      // }

      getBackApplyInfo(this.rowObj.id).then(res => {
        console.log(res)
        this.tableData = res.data.backApplyDetailsList
        this.backApplyInfo = res.data.backApplyInfo
        console.log('🚀 ~ init ~ this.backApplyInfo:', this.backApplyInfo)
      })
    },
    // 取消按钮
    cancel() {
      this.dialogShowFlag = false
    },

    print() {
      const element = document.getElementById('checkId2')

      // 确保元素存在
      if (!element) {
        this.$message.error('未找到要打印的元素')
        return
      }

      this.$modal.loading('正在生成单据，请稍候...')

      // 查找页面中所有图片并预加载
      const images = element.querySelectorAll('img')
      const imagePromises = []

      // 为每个图片创建加载或错误处理的Promise
      images.forEach(img => {
        // 如果图片已经加载完成，不需要处理
        if (img.complete) return

        const promise = new Promise(resolve => {
          const originalSrc = img.src

          // 图片加载成功
          img.onload = function () {
            resolve()
          }

          // 图片加载失败，使用空白图片替代
          img.onerror = function () {
            console.log('图片加载失败，使用空白图片替代:', originalSrc)
            img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' // 透明1x1像素图片
            resolve()
          }
        })

        imagePromises.push(promise)
      })

      // 等待所有图片加载完成或失败后再生成PDF
      Promise.all(imagePromises)
        .then(() => {
          // 使用html2canvas将DOM元素转换为canvas
          html2canvas(element, {
            scale: 2, // 提高清晰度
            useCORS: true, // 允许加载跨域图片
            allowTaint: true,
            ignoreElements: element => {
              // 忽略所有图片加载错误
              return element.nodeName === 'IMG' && !element.complete
            },
            logging: false, // 关闭日志记录
            imageTimeout: 3000, // 图片加载超时时间
            backgroundColor: '#ffffff'
          })
            .then(canvas => {
              // 创建PDF文档
              const pdf = new jsPDF('p', 'mm', 'a4')

              // 获取canvas的宽度和高度
              const imgWidth = 210 // A4纸的宽度(mm)
              const pageHeight = 297 // A4纸的高度(mm)
              const imgHeight = (canvas.height * imgWidth) / canvas.width

              // 将canvas转换为图片
              const imgData = canvas.toDataURL('image/jpeg', 1.0)

              // 添加图片到PDF
              pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight)

              // 生成PDF文件名
              const fileName = `退料单_${this.rowObj.code || '未命名'}_${new Date().getTime()}.pdf`

              // 将PDF转换为Blob对象
              const pdfBlob = pdf.output('blob')

              // 创建FormData对象用于上传
              const formData = new FormData()
              formData.append('file', pdfBlob, fileName)
              formData.append('id', this.rowObj.proId)

              // 上传到服务器
              this.$modal.closeLoading()

              // 调用上传API - 使用request
              request
                .post('/material/back_apply_info/uploadPdf', formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                })
                .then(response => {
                  if (response.code === 200) {
                    this.$modal.msgSuccess('单据文件已保存到服务器')

                    // 上传成功后执行打印
                    const images = element.querySelectorAll('img')
                    images.forEach(img => {
                      if (!img.complete || img.naturalWidth === 0) {
                        console.warn('图片加载失败，替换为透明图:', img.src)
                        img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' // 透明1x1
                      }
                    })
                    printJS({
                      printable: 'checkId2',
                      type: 'html',
                      targetStyles: ['*'],
                      maxWidth: '1400'
                    })

                    // 更新打印状态
                    updatePrintStatus(this.rowObj.id)
                      .then(response => {
                        if (response.code === 200) {
                          // 如果需要刷新列表
                          this.$emit('refresh')
                        }
                      })
                      .catch(() => {
                        this.$modal.msgError('打印状态更新失败')
                      })
                  } else {
                    this.$modal.msgError('保存单据文件失败')
                  }
                })
                .catch(() => {
                  this.$modal.msgError('上传单据文件时发生错误')

                  // 即使上传失败也执行打印
                  const images = element.querySelectorAll('img')
                  images.forEach(img => {
                    if (!img.complete || img.naturalWidth === 0) {
                      console.warn('图片加载失败，替换为透明图:', img.src)
                      img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' // 透明1x1
                    }
                  })
                  printJS({
                    printable: 'checkId2',
                    type: 'html',
                    targetStyles: ['*'],
                    maxWidth: '1400'
                  })

                  // 更新打印状态
                  updatePrintStatus(this.rowObj.id)
                    .then(response => {
                      if (response.code === 200) {
                        // 如果需要刷新列表
                        this.$emit('refresh')
                      }
                    })
                    .catch(() => {
                      this.$modal.msgError('打印状态更新失败')
                    })
                })
            })
            .catch(error => {
              this.$modal.closeLoading()
              this.$modal.msgError('生成单据时发生错误')
              console.error('生成单据错误:', error)
            })
        })
        .catch(error => {
          this.$modal.closeLoading()
          this.$modal.msgError('处理图片时发生错误')
          console.error('处理图片错误:', error)
        })
    },
    checkDetail(row) {
      this.title = '查看'
      this.tableSubData = row.maCodeList
      this.open = true
    },
    remarksPrint() {
      const element = document.getElementById('checkIdTwo')

      // 确保元素存在
      if (!element) {
        this.$message.error('未找到要打印的元素')
        return
      }

      this.$modal.loading('正在生成单据，请稍候...')

      // 查找页面中所有图片并预加载
      const images = element.querySelectorAll('img')
      const imagePromises = []

      // 为每个图片创建加载或错误处理的Promise
      images.forEach(img => {
        // 如果图片已经加载完成，不需要处理
        if (img.complete) return

        const promise = new Promise(resolve => {
          const originalSrc = img.src

          // 图片加载成功
          img.onload = function () {
            resolve()
          }

          // 图片加载失败，使用空白图片替代
          img.onerror = function () {
            console.log('图片加载失败，使用空白图片替代:', originalSrc)
            img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' // 透明1x1像素图片
            resolve()
          }
        })

        imagePromises.push(promise)
      })

      // 等待所有图片加载完成或失败后再生成PDF
      Promise.all(imagePromises)
        .then(() => {
          // 使用html2canvas将DOM元素转换为canvas
          html2canvas(element, {
            scale: 2, // 提高清晰度
            useCORS: true, // 允许加载跨域图片
            allowTaint: true,
            ignoreElements: element => {
              // 忽略所有图片加载错误
              return element.nodeName === 'IMG' && !element.complete
            },
            logging: false, // 关闭日志记录
            imageTimeout: 3000, // 图片加载超时时间
            backgroundColor: '#ffffff'
          })
            .then(canvas => {
              // 创建PDF文档
              const pdf = new jsPDF('p', 'mm', 'a4')

              // 获取canvas的宽度和高度
              const imgWidth = 210 // A4纸的宽度(mm)
              const pageHeight = 297 // A4纸的高度(mm)
              const imgHeight = (canvas.height * imgWidth) / canvas.width

              // 将canvas转换为图片
              const imgData = canvas.toDataURL('image/jpeg', 1.0)

              // 添加图片到PDF
              pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight)

              // 生成PDF文件名
              const fileName = `退料编码明细_${this.rowObj.code || '未命名'}_${new Date().getTime()}.pdf`

              // 将PDF转换为Blob对象
              const pdfBlob = pdf.output('blob')

              // 创建FormData对象用于上传
              const formData = new FormData()
              formData.append('file', pdfBlob, fileName)
              formData.append('id', this.rowObj.proId)

              // 上传到服务器
              this.$modal.closeLoading()

              // 调用上传API - 使用request
              request
                .post('/material/back_apply_info/uploadPdf', formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                })
                .then(response => {
                  if (response.code === 200) {
                    this.$modal.msgSuccess('单据PDF文件已保存到服务器')

                    // 上传成功后执行打印
                    const images = element.querySelectorAll('img')
                    images.forEach(img => {
                      if (!img.complete || img.naturalWidth === 0) {
                        console.warn('图片加载失败，替换为透明图:', img.src)
                        img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' // 透明1x1
                      }
                    })
                    printJS({
                      printable: 'checkIdTwo',
                      type: 'html',
                      targetStyles: ['*'],
                      maxWidth: '1400'
                    })
                  } else {
                    this.$modal.msgError('保存明细单据文件失败')
                  }
                })
                .catch(() => {
                  this.$modal.msgError('上传明细单据文件时发生错误')

                  // 即使上传失败也执行打印
                  const images = element.querySelectorAll('img')
                  images.forEach(img => {
                    if (!img.complete || img.naturalWidth === 0) {
                      console.warn('图片加载失败，替换为透明图:', img.src)
                      img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' // 透明1x1
                    }
                  })
                  printJS({
                    printable: 'checkIdTwo',
                    type: 'html',
                    targetStyles: ['*'],
                    maxWidth: '1400'
                  })
                })
            })
            .catch(error => {
              this.$modal.closeLoading()
              this.$modal.msgError('生成单据时发生错误')
              console.error('生成单据错误:', error)
            })
        })
        .catch(error => {
          this.$modal.closeLoading()
          this.$modal.msgError('处理图片时发生错误')
          console.error('处理图片错误:', error)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
// .order_box {
//   display: flex;
//   flex-direction: column;
//   .order_box_one {
//     width: 100%;
//     display: flex;
//     align-content: center;
//     justify-content: space-between;
//     margin-bottom: 10px;
//     :last-child {
//       margin-right: 20px;
//     }
//   }
// }
.is-rotate {
  transform: rotate(-90deg);
}
.order_footer {
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.remarks_box {
  display: flex;
  // align-items: center;
  justify-content: center;
  .remarks_box_title {
    margin-bottom: 10px;

    font-size: 18px;
  }
}
@media screen {
  body {
    font-family: 'Microsoft YaHei', sans-serif;
    background-color: #f5f5f5;
    padding: 20px;
  }

  .print-container {
    max-width: 1000px;
    margin: 0 auto;
    background: white;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .action-buttons {
    text-align: center;
    margin: 20px 0;
  }

  button {
    padding: 10px 20px;
    margin: 0 10px;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
  }

  button:hover {
    background: #66b1ff;
  }
}

/* 通用样式 */
.text-center {
  text-align: center;
}

.text-bold {
  font-weight: bold;
}

.title {
  font-size: 20px;
  font-weight: bold;
  margin: 15px 0;
  text-align: center;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

.info-item {
  flex: 1;
}

.signature-area {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.signature-box {
  width: 30%;
  min-height: 100px;
  border-bottom: 1px solid #000;
  text-align: center;
  padding-top: 60px;
}

.is-rotate {
  transform: rotate(-90deg);
  transform-origin: center center;
}
</style>
