import store from '@/store'
import moment from 'moment'
/**
 * @param{string} printJs 打印模版
 * @param{boolean} isLog 是否带审批
 * @param{object} form data数据
 * @param{string} [logContent] 审批表格html
 * @return{void}
**/
export async function print(printJs, isLog, form, logContent) {
  const staticMap = new Map([
    ['apply_name', `<span>${form.creator?.name}</span>`],
    ['apply_department_name', `<span>${form.creator_department?.name}</span>`],
    ['apply_sign', form.creator?.sign_file ? `<img src="${form.creator?.sign_file?.url}" alt="${form.creator?.name}" style="max-height: 80px;max-width: 120px;">` : `<span>${form.creator?.name}</span>`],
    ['created_at', `<span>${moment(form.created_at).format('YYYY年MM月DD日')}</span>`],
  ])

  let printStr = printJs
  const regexField = /<field[^>]*>(.*?)<\/field>/g;
  let fieldMaths = []
  let match;

  while ((match = regexField.exec(printJs)) !== null) {
    fieldMaths.push(match[0]); // 提取 <field> 之间的内容
  }
  for (let i = 0;i < fieldMaths.length; i++) {
    let fieldMath = fieldMaths[i]
    const matchName = fieldMath.match(/name="([^"]+)"/);
    if (matchName) {
      const nameValue = matchName[1];
      if (Array.from(staticMap.keys()).indexOf(nameValue) !== -1) {
        printStr = printStr.replace(fieldMath, staticMap.get(nameValue))
      } else {
        let value = store.getters.device === 'desktop' ? (document.querySelector(`[for="${nameValue}"]+div`) ? document.querySelector(`[for="${nameValue}"]+div`).innerHTML : '') : (document.querySelector(`[for="${nameValue}"] > div:nth-child(2)`) ? document.querySelector(`[for="${nameValue}"] > div:nth-child(2)`).innerHTML : '')
        if (/<table/g.test(value)) {
          let subForm = await this.$refs['desktopForm'].$refs[`subForm-${nameValue}`].exportData({
            type: 'html',
            download: false,
          })
          let subFormBody = subForm.content.match(/<table(.*?)<\/table>/g)[0]
          let subFormStyle = subForm.content.match(/<style>(.*?)<\/style>/g)[0]
          printStr = printStr.replace('</style>',`</style>${subFormStyle}`)
          printStr = printStr.replace(fieldMath,subFormBody)
          console.log(fieldMath, printStr)
        } else {
          printStr = printStr.replace(fieldMath,`<span>${value}</span>`)
        }
      }
    } else {
      console.log('未找到name属性');
    }
  }
  printStr = printStr.replace('</style>',`.vxe-table { width: 100%;border-top: 1px solid;border-left: 1px solid; } .vxe-table * { width: auto !important;white-space: initial; }.vxe-table:not(.is--print) .col--ellipsis > div { word-break: break-all;white-space: normal;overflow: initial; }.tblPrint .vxe-table td,.tblPrint .vxe-table th { font-size: 20px;padding: 0; }.el-image__inner{width:100%;height:100%}</style>`)
  if(isLog) {
    const logStyle = logContent.match(/<style>(.*?)<\/style>/g)
    let totalLogStyle= ''
    logStyle.forEach(item => {
      totalLogStyle += item
    })
    printStr = printStr.replace('</style>',`</style>${totalLogStyle}<style>.vxe-table { width: 100%; } .vxe-table * { width: auto !important;white-space: initial; }.vxe-table:not(.is--print) .col--ellipsis > div { word-break: break-all;white-space: normal;overflow: initial; }.tblPrint .vxe-table td,.tblPrint .vxe-table th { font-size: 20px;padding: 0; }.el-image__inner{width:100%;height:100%}</style>`)
    const logBody = logContent.match(/<table(.*?)<\/table>/g)[0]
    printStr = printStr.replace('</table>\n<style>',`</talbe>${logBody}<style>`)
  }
  console.log(printStr)
  let printWindow = window.open('', '_blank');
  printWindow.document.write(printStr);
  printWindow.focus();
}
