<template>
  <div style="width: 100%; height: 100vh; overflow: hidden" v-loading="loading">
    <div class="open" @click="drawer = true">
      <div class="icon"></div>
    </div>
    <el-drawer
      v-model="drawer"
      :with-header="false"
      :close-on-click-modal="true"
      direction="ttb"
      size="240"
      ref="drawerRef"
    >
      <div class="divCenter" v-loading="loading">
        <div class="printTemplateList" v-for=" i in printTemplateList">
          <el-card @click="setNodes(i)" class="moduleCard" shadow="never"
                   :style="{display:'inline-block',margin:'0 4px 4px 0'}"
                   :body-style="{padding:'4px 0'}">
            <template #header>
              <el-image style="width: 100px" :src="doc" fit="contain" />
            </template>
            <div class="moduleText">{{ i.templateName }}</div>
          </el-card>
        </div>
      </div>
    </el-drawer>
    <div class="left">
    </div>
    <div class="center">
      <div id="printInfo" ref="printRef">
        <div
          class="content"
          v-for="(pageData,k) in pageDatas"
          :style="{ pageBreakAfter: 'always', width: cmToPx(pageWidth) + 'px', height: cmToPx(pageHeight) + 'px', marginBottom: '4px' ,transform: `scale(${zoom})`}"
        >
          <div v-for="i in nodes" class="node" :style="{ left: i.position?.x + 'px', top: i.position?.y + 'px' }">
            <template v-if="i.type === 'text'">
              <TextNode
                v-bind="i"
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                :pageSize="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
              ></TextNode>
            </template>
            <template v-if="i.type === 'image'">
              <ImageNode
                v-bind="i"
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                :page-size="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
              ></ImageNode>
            </template>
            <template v-if="i.type === 'barCode'">
              <BarCodeNode
                v-bind="i"
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                :pageSize="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
              ></BarCodeNode>
            </template>
            <template v-if="i.type === 'QRCode'">
              <QRCodeNode
                v-bind="i"
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                :pageSize="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
              ></QRCodeNode>
            </template>
            <template v-if="i.type === 'dateTime'">
              <TimeNode
                v-bind="i"
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                :pageSize="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
              ></TimeNode>
            </template>
            <template v-if="i.type === 'select'">
              <SelectNode
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                @update="setValue($event,i.data.options.field,k)"
                :pageSize="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
                v-bind="i"
              ></SelectNode>
            </template>
            <template v-if="i.type === 'inputNode'">
              <InputNode
                :isView="true"
                :isPrint="isPrint"
                :pageData="pageData"
                @update="setValue($event,i.data.options.field,k)"
                :pageSize="{ width: cmToPx(pageWidth), height: cmToPx(pageHeight) }"
                v-bind="i"
              ></InputNode>
            </template>
          </div>
        </div>
      </div>
    </div>
    <!--    <div class="right">-->
    <!--      <el-dropdown split-button type="primary" @click="printFun" @command="switchPrinter" style="margin-right: 8px">-->
    <!--        {{ printName() }}-->
    <!--        <template #dropdown>-->
    <!--          <el-dropdown-menu>-->
    <!--            <el-dropdown-item :command="-1">导出PDF</el-dropdown-item>-->
    <!--            <el-dropdown-item divided :command="0">本地打印</el-dropdown-item>-->
    <!--            <el-dropdown-item :divided="k === 0" :command="i.id" v-for="(i, k) in printers">{{ i.name }}-->
    <!--            </el-dropdown-item>-->
    <!--          </el-dropdown-menu>-->
    <!--        </template>-->
    <!--      </el-dropdown>-->
    <!--    </div>-->
  </div>
  <div id="printArea" v-if="printPngList.length > 0">
    <div v-for="(url, index) in printPngList" :key="index" class="print-page">
      <img :src="url" class="print-image" />
    </div>
  </div>
</template>
<script setup>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { ElMessageBox } from 'element-plus';
import { options } from '@/views/print/tool.js';
import TextNode from '@/views/print/nodes/textNode.vue';
import ImageNode from '@/views/print/nodes/image.vue';
import BarCodeNode from './nodes/barCodeNode.vue';
import QRCodeNode from './nodes/QRCodeNode.vue';
import TimeNode from './nodes/timeNode.vue';
import SelectNode from './nodes/selectNode.vue';
import InputNode from './nodes/inputNode.vue';
import { useRoute } from 'vue-router';
import { isJSON } from '@/utils/scrin.js';
import { listPrintTemplateList } from '@/api/system/printTemplateList/index';
import doc from '@/assets/images/doc.png';
import { getSysPrintTemplateNodeList } from '@/api/system/printTemplateNode/index';
import { listPrintTemplateInfo } from '@/api/system/printTemplateInfo/index';

const handleClose = (done) => {
  ElMessageBox.confirm('Are you sure you want to close this?')
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
const drawer = ref(false);
const loading = ref(false);
const drawerRef = ref();
const printTemplateList = ref([]);
const route = useRoute();
const printType = ref(0);
const printers = ref([
  {
    id: 1,
    name: '网络打印机1'
  },
  {
    id: 2,
    name: '网络打印机2'
  },
  {
    id: 3,
    name: '网络打印机3'
  }
]);
const printPngList = ref([]);
const isView = ref(true);

const jsonData = ref('');
const isPrint = ref(false);
const printRef = ref();
const pageWidth = ref(21);
const pageHeight = ref(29.7);
const pageDatas = ref([]);
const zoom = ref(1);
const { cmToPx } = options;
const nodes = ref([]);
const messageFun = (event) => {
  // if (isJSON(event.data)) {
  // let data = JSON.parse(event.data);
  let data = event.data;
  if (data.type === 'print') {
    let zoomEl = zoom.value
    zoom.value = 5
    nextTick(() => {
      setTimeout(()=>{
        printFun()
        setTimeout(()=>{
          zoom.value = zoomEl
        },200)
      },500)
    })
    // printFun();
  }
  if (data.type === 'return') {
    window.chrome?.webview?.postMessage(JSON.stringify({ value: pageDatas.value, type: 'return' }));
  }
  if (data.type === 'JSONDATA') {
    if (typeof data.message === 'object' && data.message !== null && !Array.isArray(data.message)) {
      pageDatas.value = [data.message];
      // window.chrome?.webview?.postMessage('setDataFinally');
    } else if (Array.isArray(data.message)) {
      pageDatas.value = data.message;
      // window.chrome?.webview?.postMessage('setDataFinally');
    } else {
      // window.chrome?.webview?.postMessage('setDataFail');
    }
  }
  if (data.type === 'updateData') {
    let data = [];
    if (typeof data.message === 'object' && data.message !== null && !Array.isArray(data.message)) {
      data = [data.message];
      // window.chrome?.webview?.postMessage('setDataFinally');
    } else if (Array.isArray(data.message)) {
      data = data.message;
      // window.chrome?.webview?.postMessage('setDataFinally');
    } else {
      // window.chrome?.webview?.postMessage('setDataFail');
    }
    data.forEach((item, index) => {
      Object.keys(item).forEach(key => {
        pageDatas.value[index][key] = item[key];
      });
    });
  }
  // }
};
const setNodes = (data) => {
  loading.value = true;
  listPrintTemplateInfo({ templateListId: data.templateListId }).then(e => {
    let templateInfoId = e.rows?.[0]?.templateInfoId;
    getSysPrintTemplateNodeList({ templateInfoId }).then(v => {
      nodes.value = v.data.map(vv => {
        return {
          id: vv.id,
          type: vv.type,
          name: vv.name,
          dimensions: {
            width: vv.width,
            height: vv.height
          },
          handleBounds: {
            source: null,
            target: null
          },
          position: {
            x: vv.x,
            y: vv.y
          },
          data: JSON.parse(vv.data)
        };
      });
      nextTick(() => {
        zoom.value = ((printRef.value.offsetWidth) / 793);
      });
      drawer.value = false;
      loading.value = false;
    });
  });
};
const setValue = (value, field, index) => {
  pageDatas.value[index][field] = value;
};
const test = () =>{
  let json1 = {
    'PlanCode': '20260112100528PL0001',
    'CardRecordCode': '20260112NC001010001',
    'ClassesName': '\u65E9',
    'TeamName': '\u7532\u73ED',
    'MaterialSpec': 'NL821/832/833/840/841/844/848/849/106',
    'MachineName': '\u5185\u5B58\u5C421#',
    'UserList': ['\u674E\u5185\u886C\u5C42', '\u738B\u5185\u886C\u5C42', '\u5F20\u5185\u886C\u5C42'],
    'UserListSel': null,
    'ResultList': ['\u5408\u683C', '\u4E0D\u5408\u683C'],
    'ResultListSel': null,
    'ValidDate': '30',
    'ToolingCode': '',
    'Width': '1000',
    'RealBeginTime': '2026-01-12 10:54:35',
    'RealEndTime': '2026-01-12 14:34:12',
    'CompleteAmount': '0',
    'UnitList': ['\u7C73'],
    'UnitListSel': null,
    'Batch': '0',
    'ContinueTime': '0',
    'Remark': '',
    'StationList': ['\u5185\u5B58\u5C421#\u4EA7\u51FA\u5DE5\u4F4D1', '\u5185\u5B58\u5C421#\u4EA7\u51FA\u5DE5\u4F4D2'],
    'StationListSel': '\u5185\u5B58\u5C421#',
    'BarCode': null
  };
  pageDatas.value = [json1];
  setTimeout(() => {
    console.log(123);
    let data = [{ Batch: '123' }];
    data.forEach((item, index) => {
      Object.keys(item).forEach(key => {
        pageDatas.value[index][key] = item[key];
      });
    });
  }, 1000 * 5);
}
onMounted(() => {
  // test()
  window.addEventListener('afterprint', () => {
    isPrint.value = false;
  });
  window.chrome?.webview?.addEventListener('message', messageFun);
  window.chrome?.webview?.postMessage('onMounted');
  const param = route.query.data;
  if (param) {
    let code = decodeURIComponent(param);
    if (!code) return;
    let data = JSON.parse(code);
    if (Array.isArray(data)) {
      pageDatas.value = data;
    }
    if (data !== null && typeof data === 'object' && !Array.isArray(data)) {
      pageDatas.value = [data];
    }
  }
  listPrintTemplateList().then(data => {
    printTemplateList.value = data.rows;
  });
  nextTick(() => {
    zoom.value = ((printRef.value.offsetWidth) / 793);
  });
});

const switchPrinter = (e) => {
  printType.value = e;
};
const printFun = (e) => {
  if (printType.value === -1) {
    isPrint.value = true;
    nextTick(() => {
      const element = printRef.value;
      let eles = element.querySelectorAll('.content');
      const pros = [];

      eles.forEach((ele, index) => {
        pros.push(
          html2canvas(ele).then((canvas) => {
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(imgData, 'PNG', 0, 0);
            pdf.save(`${new Date().getTime()}-${index}.pdf`);
          })
        );
      });
      Promise.all(pros).then((values) => {
        isPrint.value = false;
      });
    });
  } else if (printType.value === 0) {
    isPrint.value = true;
    printPngList.value = [];
    nextTick(() => {
      const element = printRef.value;
      let eles = element.querySelectorAll('.content');
      const pros = [];

      eles.forEach((ele, index) => {
        pros.push(
          html2canvas(ele).then((canvas) => {
            const imgData = canvas.toDataURL('image/png');
            printPngList.value.push(imgData);
          })
        );
      });
      Promise.all(pros).then((values) => {

        window.print();
        // window.chrome?.webview?.postMessage('completed');
        isPrint.value = false;
        printPngList.value = [];
      });
    });
  } else {
  }
};
const closePrint = () => {
  isView.value = false;
};
const openPrint = (pages, templateId) => {
  isView.value = false;
  nextTick(() => {
    nodes.value = JSON.parse(localStorage.getItem('printNodes') || '[]');
    isView.value = true;
    let pageData = [];
    if (Array.isArray(pages)) {
      pageData = pages;
    }
    if (typeof pages !== 'object' || pages === null) {
      pageData = [pages];
    }
    pageDatas.value = pageData || [];
  });
};
const printName = () => {
  if (printType.value === -1) {
    return '导出PDF';
  } else if (printType.value === 0) {
    return '本地打印';
  } else {
    let name = printers?.value?.find((e) => e.id === printType?.value)?.name;
    return name || '';
  }
};
defineExpose({
  openPrint
  // closePrint
});
</script>
<style scoped>

.content {
  position: relative;
  width: 100%;
  //overflow: hidden;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  border-top: 1px solid #ccc;
  transform-origin: top left;
}

.node {
  position: absolute;
}

.left {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 8;
  display: inline-block;
  width: 100%;
  overflow: auto;
  margin-right: 50px;
}

.divCenter {
  text-align: center;
}

.center {
  display: inline-block;
  width: calc(100%);
  height: 100vh;
  overflow: auto;
  padding-top: 40px;

  &::-webkit-scrollbar {
    display: none;
  }
}

.right {
  vertical-align: top;
  display: inline-block;
  width: 140px;
  position: absolute;
  right: 0;
  top: 0;
}

.printTemplateList {
  width: 150px;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  min-width: 50px;
}

.open {
  position: fixed;
  top: 0;
  left: 50%;
  width: 100px;
  height: 30px;
  background-color: #ddd;
  border-bottom-left-radius: 30px;
  border-bottom-right-radius: 30px;

  .icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-image: url("@/assets/icons/down.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 12px;
    height: 12px;
  }
}
</style>
<style>
.print-page {
  page-break-after: always;
  text-align: center;
  padding: 20px;
  background: white;
}

.print-image {
  max-width: 100%;
  height: auto;
}

/* 打印样式：仅显示图片区域 */
@media print {
  body * {
    visibility: hidden !important;
  }

  #printArea,
  #printArea * {
    visibility: visible !important;
  }

  #printArea {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
  }

  .print-page {
    page-break-after: always;
  }
}

</style>
