<template>
  <el-container>
    <el-aside width="210px">
      <PatientBaseList
        :yzType="yzType"
        @selectPatientInfo="selectPatientInfo"
      ></PatientBaseList>
    </el-aside>
    <el-container>
      <el-header style="height: 150px">
        <PatientInfo :patientInfo="patientInfo"></PatientInfo>
      </el-header>
      <div>
        <el-row>
          <el-col :span="8">
            <el-button icon="Search" type="primary" @click="queryInfo"
              >查询</el-button
            >
            <el-button icon="Printer" type="success" @click="handlePrint(false)"
              >打印预览</el-button
            >
            <el-button icon="Printer" type="success" @click="handlePrint(true)"
              >打印</el-button
            >
          </el-col>
          <el-col :span="8">
            <el-radio-group
              @change="initPageNumList"
              v-model="yzOrderParam.printType"
            >
              <el-radio :label="1">打印新增</el-radio>
              <el-radio :label="2">打印单页</el-radio>
              <el-radio :label="3">打印某页后</el-radio>
            </el-radio-group>
          </el-col>
          <el-col :span="4">
            医嘱页号:
            <el-select
              v-model="yzOrderParam.pageNum"
              placeholder="请选择"
              style="width: 60px"
            >
              <el-option
                v-for="item in pageNumList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="clearPrintPageClick"
              >清空打印页号</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-main>
        <el-scrollbar height="100%">
            <div id="cqYz">
                <table id="pageTable">
                    <thead>
                    <tr>
                        <td
                            colspan="7"
                            style="
                    width: 100%;
                    text-align: center;
                    padding: 16px 0;
                    border: none;
                    font-size: 23px;
                    font-weight: bold;
                  "
                        >
                            {{ env.VITE_HOSPITAL_NAME }}<br />临时医嘱单
                        </td>
                    </tr>
                    <tr>
                        <td colspan="7" style="border: none">
                            <div>
                                <div style="width: 15%;float: left;">姓名：{{ patientInfo.name }}</div>
                                <div style="width: 15%;float: left;">
                                    性别：{{ patientInfo.sexName }}
                                </div>
                                <div style="width: 15%;float: left;">
                                    年龄：{{ companyFunc(patientInfo.age, "岁") }}
                                </div>
                                <div style="width: 15%;float: left;">
                                    科别：{{ patientInfo.admissWardName }}
                                </div>
                                <div style="width: 18%;float: left;">
                                    床号：{{ patientInfo.bedNo }}
                                </div>
                                <div>住院号：{{ patientInfo.inpatientNo }}</div>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th style="width: 60px; height: 40px">日期</th>
                        <th style="width: 60px">时间</th>
                        <th>临时医嘱</th>
                        <th style="width: 85px">医师签名</th>
                        <th style="width: 85px">核对护士签名</th>
                        <th style="width: 120px">执行时间</th>
                        <th style="width: 85px">执行护士签名</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(item, index) in yzPrintVOList" :key="index">
                        <td
                            v-if="item.pageFlag == '1'"
                            style="border: none"
                            colspan="7"
                        >
                            第{{ item.printPageOnce }}页
                        </td>
                        <td v-if="item.pageFlag != '1'" style="height: 41px">
                            {{ item.date }}
                        </td>
                        <td v-if="item.pageFlag != '1'">{{ item.time }}</td>
                        <td v-if="item.pageFlag != '1'" style="text-align: left">
                            {{ item.orderGroupNo }} {{ item.newOrderName }}
                            {{ item.newOrderNameCode }} {{ item.frequCode }}
                        </td>
                        <td v-if="item.pageFlag != '1'" style="text-align: left">
                            <img v-if="item.doctorCode" style="width: 60px;" :src="getSign(item.doctorCode)"/>
                        </td>
                        <td v-if="item.pageFlag != '1'" style="text-align: left">
                            <img v-if="item.nurseCode" style="width: 60px;" :src="getSign(item.nurseCode)"/>
                        </td>
                        <td v-if="item.pageFlag != '1'">{{ item.execTimeStr }}</td>
                        <td v-if="item.pageFlag != '1'" style="text-align: left">
                            <img v-if="item.execId" style="width: 60px;" :src="getSign(item.execId)"/>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </el-scrollbar>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup name="lsYzPrint">
import PatientInfo from "@/components/medical-advice/PatientInfo.vue";
import PatientBaseList from "@/components/medical-advice/PatientBaseList.vue";
import {
  lsYzPrint,
  getTotalPageNUm,
  recPrint,
  clearPrintPageNo,
} from "@/api/medical-advice/medical-advice-management";
import { getLodop, initLodop } from "@/utils/c-lodop";
import { onMounted } from "vue";
import { stringNotBlank } from "@/utils/blank-utils";
import { ElMessage, ElMessageBox } from "element-plus";
import env from "../../../utils/setting";
// 基本信息
const patientInfo = ref({});
const yzType = ref("cq");
const yzPrintVOList = ref([]);
const companyFunc = (val, company) => {
  if (stringNotBlank(val)) {
    return val + company;
  } else {
    return "";
  }
};

const yzOrderParam = ref({
  patNo: "",
  times: null,
  inOutStatusFlag: "",
  type: 2,
  printType: 1,
  pageNum: "",
});

const pageNumList = ref([]);

const getSign = (code) => {
    // return env.RESOURCE_BASE_URL + "/doctorSignatureImage/" + code + ".png";
    return "http://130.150.161.72:8080" + "/doctorSignatureImage/" + code + ".png";
}

//
const initPageNumList = () => {
  yzOrderParam.value.pageNum = "";
  yzPrintVOList.value = [];
  if (yzOrderParam.value.printType === 1) {
    pageNumList.value = [];
    return;
  }
  getTotalPageNUm(yzOrderParam.value).then(res => {
    if (res.total) {
      pageNumList.value = [];
      for (let i = 0; i < res.total; i++) {
        let param = { code: i + 1 + "", name: i + 1 + "" };
        pageNumList.value.push(param);
      }
    } else {
      pageNumList.value = [];
    }
  });
};

const yzPrintCss = `
#pageTable tr td, #pageTable tr th {
border: 1px solid black;
text-align: center;
font-size: 12px;
padding: 0 0;

}
#pageTable tr td{
height: 27px;
}

#pageTable {
border-collapse: collapse;
}

`;
//清空
const clearPrintPageClick = () => {
  clearPrintPageNo(yzOrderParam.value).then(res => {
    yzPrintVOList.value = [];
    pageNumList.value = [];
  });
};

const selectPatientInfo = val => {
  if (!stringNotBlank(val.patientInfo.inpatientNo)) {
    return ElMessage.error("请选中一个病人");
  }
  yzOrderParam.value.patNo = val.patientInfo.inpatientNo;
  yzOrderParam.value.times = val.patientInfo.admissTimes;
  yzOrderParam.value.inOutStatusFlag = val.inOutStatusFlag;
  clearInfo();
};

const queryInfo = () => {
  lsYzPrint(yzOrderParam.value).then(res => {
    patientInfo.value = res.patientInfo;
    yzPrintVOList.value = res.yzPrintVOList;
  });
};

const clearInfo = () => {
  yzPrintVOList.value = [];
  yzOrderParam.value.pageNum = "";
  yzOrderParam.value.printType = 1;
  pageNumList.value = [];
};

onMounted(() => {
  initLodop();
});
const daYingClick = () => {
  let LODOP = getLodop();
  LODOP.PRINT_INIT("长期医嘱单"); // 初始化打印机 名字
  LODOP.SET_PRINT_PAGESIZE(1, "210mm", "297mm", ""); // 设置纸张大小  A4
  LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true); // 整宽不变形
  LODOP.ADD_PRINT_TABLE(
    "2mm",
    "5mm",
    "205mm",
    "220mm",
    "<style>" +
      yzPrintCss +
      "</style>" +
      "<body>" +
      document.getElementById("cqYz").innerHTML +
      "</body>"
  ); //要打印的内容
  LODOP.PREVIEW(); // 关闭
};

const printClick = () => {
  if (yzPrintVOList.value.length <= 0) {
    return ElMessage.error("没有打印数据");
  }
  if (yzOrderParam.value.printType === 1) {
    recPrint(yzOrderParam.value).then(res => {});
  }
  let LODOP = getLodop();
  LODOP.PRINT_INIT("长期医嘱单"); // 初始化打印机 名字
  LODOP.SET_PRINT_PAGESIZE(1, "210mm", "297mm", ""); // 设置纸张大小  A4
  LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true); // 整宽不变形
  LODOP.ADD_PRINT_TABLE(
    "2mm",
    "5mm",
    "205mm",
    "220mm",
    "<style>" +
      yzPrintCss +
      "</style>" +
      "<body>" +
      document.getElementById("cqYz").innerHTML +
      "</body>"
  ); //要打印的内容
  LODOP.PRINT(); // 关闭
  queryInfo();
};

const print = (type) => {
    // 获取要打印的元素
    const printContent = document.getElementById('cqYz');

    if (!printContent) {
        console.error('未找到id为cqYz的元素');
        return;
    }

    // 创建打印窗口
    const printWindow = window.open('', '_blank');

    // 复制文档头部信息（确保样式生效）
    printWindow.document.head.innerHTML = document.head.innerHTML;

    // 创建打印区域
    printWindow.document.body.innerHTML = `
    <div class="print-container">
      ${printContent.outerHTML}
    </div>
  `;

    // 等待内容加载完成后执行打印
    if(type) {
        setTimeout(() => {
            printWindow.print();
            // 打印后关闭窗口
            printWindow.close();
        }, 100);
    }

};

const handlePrint = async (type) => {
    await nextTick();
    const printContent = document.getElementById('cqYz');
    if (!printContent) {
        console.error('未找到打印容器');
        return;
    }

    // 克隆原始内容
    const clonedContent = printContent.cloneNode(true);

    // 精确控制边框显示
    adjustBorders(clonedContent);

    // 等待图片加载
    await waitForImages(clonedContent);

    const printWindow = window.open('', '_blank');
    if (!printWindow) {
        alert('请允许弹出窗口以完成打印');
        return;
    }

    // 复制原页面样式
    const stylesheets = Array.from(document.styleSheets)
        .map(style => {
            try {
                if (style.href) return `<link rel="stylesheet" href="${style.href}">`;
                const rules = Array.from(style.cssRules).map(rule => rule.cssText).join('\n');
                return `<style>${rules}</style>`;
            } catch (e) {
                return '';
            }
        })
        .join('\n');

    // 打印专用样式
    const printSpecificCss = `
        @page {
          size: auto;
          margin: 10mm;
        }

        /* 根元素背景色设置 */
        html, body {
          background-color: #fff !important;
          -webkit-print-color-adjust: exact !important;
          print-color-adjust: exact !important;
          margin: 0 !important;
          padding: 0 !important;
        }

        @media print {
          .print-btn {
            display: none !important;
          }

          #pageTable {
            border-collapse: collapse !important;
            width: 100% !important;
          }

          /* 强制打印所有背景色 */
          * {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
          }

          /* 确保表格背景为白色 */
          #pageTable {
            background-color: #fff !important;
          }
        }
      `;

    // 构建打印页面
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8">
            ${stylesheets}
            <style>${printSpecificCss}</style>
          </head>
          <body style="margin: 0; padding: 0;">
            ${clonedContent.outerHTML}
          </body>
        </html>
      `);
    printWindow.document.close();

    // 执行打印
    if(type) {
        printWindow.onload = () => {
            setTimeout(() => {
                printWindow.print();
                printWindow.onafterprint = () => printWindow.close();
            }, 300);
        };
    }

};

// 精确调整边框显示
const adjustBorders = (element) => {
    // 1. 表头处理
    const thead = element.querySelector('thead');
    if (thead) {
        // 获取表头所有行
        const theadRows = thead.querySelectorAll('tr');

        // 第一个tr（标题行）：强制无边框
        if (theadRows[0]) {
            const firstRowCells = theadRows[0].querySelectorAll('td');
            firstRowCells.forEach(cell => {
                cell.style.border = 'none !important';
                // 确保没有继承其他边框样式
                cell.style.borderTop = 'none !important';
                cell.style.borderBottom = 'none !important';
            });
        }

        // 第二个tr（患者信息行）：保持无边框
        if (theadRows[1]) {
            const infoRowCells = theadRows[1].querySelectorAll('td');
            infoRowCells.forEach(cell => {
                cell.style.border = 'none !important';
            });
        }

        // 第三个tr（列标题行）：添加边框
        if (theadRows[2]) {
            const columnHeaders = theadRows[2].querySelectorAll('th');
            columnHeaders.forEach(header => {
                header.style.border = '1px solid #000 !important';
                // 保留原有高度设置
                header.style.height = header.style.height || '40px';
            });
        }
    }

    // 2. 表体处理
    const tbody = element.querySelector('tbody');
    if (tbody) {
        const tbodyCells = tbody.querySelectorAll('td');
        tbodyCells.forEach(cell => {
            // 页码行：无边框
            if (cell.hasAttribute('colspan') && cell.colSpan >= 7) {
                cell.style.border = 'none !important';
            }
            // 数据行：有边框
            else {
                cell.style.border = '1px solid #000 !important';
            }
        });
    }
};

// 等待图片加载
const waitForImages = (element) => {
    const images = element.querySelectorAll('img');
    if (images.length === 0) return Promise.resolve();

    const promises = Array.from(images).map(img => {
        return new Promise(resolve => {
            if (img.complete) resolve();
            img.onload = resolve;
            img.onerror = resolve;
        });
    });

    return Promise.all(promises);
};


</script>

<style scoped>
.nav {
  margin: 0 auto;
  width: 100%;
}
ul {
  list-style: none;
  width: 100%;
}
.nav li {
  float: left;
  margin-left: 10px;
}
#cqYz {
  width: 753px;
    height: 100%;
  padding: 0 0px;
    background: #fff;
}

#pageTable tr td,
#pageTable tr th {
  border: 1px solid black;
  text-align: center;
  font-size: 12px;
}
#pageTable {
  border-collapse: collapse;
}

#pageTable tr td {
  height: 27px;
}


.print-btn {
    margin: 20px;
    padding: 8px 16px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

</style>
