<template>
  <page-layer>
    <template #header>
      <el-select v-model="queryParams.wardCode" style="width: 88px" @change="handleWardChange">
        <el-option v-for="item in userWards" :value="item.value" :label="item.label"></el-option>
      </el-select>
      <span class="ml12">
        执行日期：<el-date-picker v-model="queryParams.executeDate" :clearable="false" style="width: 102px"></el-date-picker>
      </span>
      <span class="ml12">床位范围：
        <el-select v-model="queryParams.bedNoStart" style="width: 70px" value-key="bedNo"
          @change="handleStartBedChange">
          <el-option v-for="item in patientBedList" :key="item.bedNo" :value="item">
            {{ item.bedNoLabel }}
            <el-divider direction="vertical"></el-divider>
            <span class="green-text">{{ item.patNo }}</span>
            <el-divider direction="vertical"></el-divider>
            <span class="blue-text">{{ item.patName }}</span>
          </el-option>
        </el-select>
        <span style="margin: 0 4px; font-size: 11px">至</span>
        <el-select v-model="queryParams.bedNoEnd" style="width: 70px" value-key="bedNo" @change="handleEndBedChange">
          <el-option v-for="item in patientBedList" :key="item.bedNo" :value="item"
            :disabled="item.sortNo < queryParams.sortNoStart">
            {{ item.bedNoLabel }}
            <el-divider direction="vertical"></el-divider>
            <span :class="item.sortNo < queryParams.sortNoStart ? 'is-disabled' : 'green-text'">{{ item.patNo }}</span>
            <el-divider direction="vertical"></el-divider>
            <span :class="item.sortNo < queryParams.sortNoStart ? 'is-disabled' : 'blue-text'">{{ item.patName }}</span>
          </el-option>
        </el-select>
      </span>
      <span class="ml12">
        频率：
        <el-select v-model="queryParams.frequency" style="width: 60px">
          <el-option value="ALL" label="全部"></el-option>
          <el-option value="ALWAYS" label="长期"></el-option>
          <el-option value="ONCE" label="临时"></el-option>
        </el-select>
      </span>
      <span class="ml12">
        打印范围：
        <el-select v-model="queryParams.printRange" style="width: 76px">
          <el-option value="ALL" label="全部"></el-option>
          <el-option value="UNPRINTED" label="新增"></el-option>
          <el-option value="PRINTED" label="已打印"></el-option>
        </el-select>
      </span>
      <span class="ml12">
        类型：
        <el-select v-model="queryParams.cardType" @change="handleTypeChange" style="width: 76px">
          <el-option value="INFUSION_CARD" label="输液卡"></el-option>
          <el-option value="BOTTLE_CARD" label="瓶贴"></el-option>
        </el-select>
      </span>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Search" @click="executeQuery">检索</el-button>
      <el-button type="primary" icon="Printer" @click="execPrint">打印</el-button>
    </template>
    <template #main>
      <div style="display: flex; flex-wrap: wrap" id="infusion_list">
        <div v-if="queryParams.cardType === 'INFUSION_CARD'">

          <div v-for="(item, index) in patientInfusionInfos" :id="item.patInfo.patNo">
            <div class="crad-area"
              style="width: 90%; margin: 8px 12px; padding: 4px; border: 1px solid red ;display: flex;justify-content: center; align-items: center;">
              <infusion-card :drug-groups="item.drugGroups" :pat-info="item.patInfo" :yz-date="queryParams.executeDate"
                :print-date="printDate">
              </infusion-card>
            </div>
          </div>
        </div>
        <div v-else id="print-test">
          <div class="crad-area" v-for="(item, index) in patientInfusionInfos" :id="item.patInfo.patNo + '-' + index"
            style="width: 230px;display: inline-block;margin-right: 20px">
            <bottle-card :drugs="item.bottleCardDrugs" :pat-info="item.patInfo" :yz-date="queryParams.executeDate"
              :bottle-group="item.bottleGroup" style="margin-bottom: 10px;">
            </bottle-card>
          </div>
        </div>
        <!-- <div class="print-hiden-area" style="margin: 0px 12px">
          <div class="print-bottle-card-area" style="display: flex;margin: 0px;">
            <div v-for="(item, index) in printPatientBottleInfos" :id="item.patInfo.patNo + '-' + index" style="width: 240px;margin-right: 10px;">
              <bottle-card :drugs="item.bottleCardDrugs" :pat-info="item.patInfo" :yz-date="queryParams.executeDate"
                :bottle-group="item.bottleGroup" style="margin-bottom: 10px;">
              </bottle-card>
            </div>
            <div v-if="printPatientBottleInfos.length != 0 && printPatientBottleInfos.length % 2 != 0"
              style="width: 230px;">
            </div>
          </div>
        </div> -->
      </div>
    </template>
  </page-layer>
</template>

<script setup>
import PageLayer from "@/layout/PageLayer.vue";
import { formatDate, getDatetime, getDate } from "@/utils/date";
import {
  getPatientBeds,
  queryInfusionCardOrBottleCard,
  updatePrintStatus
} from '@/api/inpatient/nurse-module/print-infusion-card'
import InfusionCard from "@/components/inpatient/nurse-module/InfusionCard.vue";
import { ElMessage } from "element-plus";
import { getLodop, initLodop } from "@/utils/c-lodop";
import BottleCard from "@/components/inpatient/nurse-module/BottleCard.vue";
import { getWardsApi } from "@/api/login";

const userWards = ref([])

const patientBedList = ref([])
const printDate = ref(null)

const handleWardChange = (wardCode) => {
  getPatientBeds(wardCode).then(res => {
    patientBedList.value = res
    if (res.length > 0) {
      queryParams.bedNoStart = res[0].bedNoLabel
      queryParams.sortNoStart = res[0].sortNo
      queryParams.bedNoEnd = res[res.length - 1].bedNoLabel
      queryParams.sortNoEnd = res[res.length - 1].sortNo
    } else {
      queryParams.bedNoStart = null
      queryParams.sortNoStart = null
      queryParams.bedNoEnd = null
      queryParams.sortNoEnd = null
    }
  })
}

const queryParams = reactive({
  executeDate: getDate(),
  wardCode: null,
  bedNoStart: null,
  bedNoEnd: null,
  sortNoStart: null,
  sortNoEnd: null,
  frequency: 'ALWAYS',
  printRange: 'UNPRINTED',
  cardType: 'INFUSION_CARD',
  bedNos: []
})

const patientInfusionInfos = ref([])
const printPatientBottleInfos = ref([])

const handleStartBedChange = (bed) => {
  queryParams.bedNoStart = bed.bedNoLabel
  queryParams.sortNoStart = bed.sortNo
}

const handleEndBedChange = (bed) => {
  queryParams.bedNoEnd = bed.bedNoLabel
  queryParams.sortNoEnd = bed.sortNo
}

const handleTypeChange = () => {
  patientInfusionInfos.value = []
}

const executeQuery = () => {
  queryParams.executeDate = formatDate(queryParams.executeDate)
  queryParams.bedNos = []
  patientBedList.value.forEach(bed => {
    if (bed.sortNo >= queryParams.sortNoStart && bed.sortNo <= queryParams.sortNoEnd) {
      queryParams.bedNos.push(bed.bedNo)
    }
  })
  queryInfusionCardOrBottleCard(queryParams).then(res => {
    patientInfusionInfos.value = res
    if (queryParams.cardType !== 'INFUSION_CARD' && patientInfusionInfos.value.length > 0) {
      //瓶贴分配药品组号
      patientInfusionInfos.value.forEach(item => {
        let group = patientInfusionInfos.value.filter(citem => citem.patInfo.patNo === item.patInfo.patNo)
        group.forEach((v, vindex) => {
          let target = patientInfusionInfos.value.find(citem => citem.bottleCardDrugs[0].actOrderNo === v.bottleCardDrugs[0].actOrderNo)
          target.bottleGroup = vindex + 1 + "/" + group.length
          // console.log("target",target)
        })
        // console.log("group",group)
        // console.log("index")
      })
      // console.log("patientInfusionInfo  s",patientInfusionInfos.value)
    }
    // for (let i = 0; i < 2; i++) {
    //   patientInfusionInfos.value = [...patientInfusionInfos.value, ...res]
    // }
    // printPatientBottleInfos.value = res
    printDate.value = getDatetime()
  }).catch(() => {
    patientInfusionInfos.value = []
  })
}

const execPrint = () => {
  const type = queryParams.cardType === 'INFUSION_CARD' ? '输液卡' : '瓶贴卡'
  if (patientInfusionInfos.value.length === 0) {
    ElMessage({
      message: `请先检索${type}。`,
      type: 'warning',
      duration: 2500,
      showClose: true
    })
    return
  }
  let LODOP = getLodop();
  if (queryParams.cardType == 'INFUSION_CARD') {
    let prntContent = document.getElementById("infusion_list").innerHTML
    // console.log("prntContent",prntContent)
    let printHTML = ""
    const prntStyle = `<style>td{border: 1px solid black;
    font-size: 12px;padding: 2px;}</style>`
    if (patientInfusionInfos.value.length == 1) {
      let id = queryParams.cardType === 'INFUSION_CARD'
        ? patientInfusionInfos.value[0].patInfo.patNo : patientInfusionInfos.value[0].patInfo.patNo + '-' + i
      printHTML = document.getElementById(id).innerHTML
      LODOP.PRINT_INIT('infusionCard')
      LODOP.SET_PRINT_PAGESIZE(1, '210mm', '297mm', '')
      LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', prntStyle + '<body style:"display: flex;justify-content: center;align-items: center;">' + printHTML + '</body>')
      LODOP.SET_PRINT_STYLE('ItemType', 3)
      LODOP.PREVIEW();
    } else {
      for (let i = 0; i < patientInfusionInfos.value.length; i++) {
        let info = patientInfusionInfos.value[i]
        let id = queryParams.cardType === 'INFUSION_CARD'
          ? info.patInfo.patNo : info.patInfo.patNo + '-' + i
        let printCount = queryParams.cardType === 'INFUSION_CARD'
          ? 3 : 6
        // console.log("printCount",printCount)
        if (i !== 0 && ((i + 1) % printCount == 0 || i == patientInfusionInfos.value.length - 1)) {
          // console.log("printIndex",i)
          printHTML = document.getElementById(id).innerHTML + printHTML
          let printFinal = prntStyle + '<body><div style:"width:600px;display: flex;justify-content: center;align-items: center;flex-wrap: wrap;">' + printHTML + '</div></body>';
          console.log("printFinal", printFinal)
          LODOP.PRINT_INIT('infusionCard')
          LODOP.SET_PRINT_PAGESIZE(1, '210mm', '297mm', '')
          // LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm',prntStyle + '<body style:"width:800px;display: flex;justify-content: center;align-items: center;flex-wrap: wrap;">' + printHTML + '</body>' )
          LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', printFinal)
          LODOP.SET_PRINT_STYLE('ItemType', 3)
          // LODOP.PREVIEW();  
          LODOP.PRINT()
          printHTML = ""
        } else {
          printHTML += document.getElementById(id).innerHTML
        }
      }
    }
    updatePrintState()
  } else {
    printPatientBottleInfos.value = [...patientInfusionInfos.value]
    // console.log("patientInfusionInfos",patientInfusionInfos.value)
    // console.log("printPatientBottleInfos",printPatientBottleInfos.value)
    nextTick(() => {
      LODOP.PRINT_INIT('infusionCard');
      LODOP.SET_PRINT_PAGESIZE(1, '210mm', '297mm', '');

      const prntStyle = `<style>
  .card-container { display: inline-block;  } /* 一行3个，预留间距 */
  td { border: 1px solid black; font-size: 12px; padding: 2px; }
</style>`;

      const PAGE_MAX_HEIGHT = 1100; // 页面最大高度阈值（px）
      let currentPageHTML = prntStyle; // 当前页内容
      let currentPageTotalHeight = 0; // 当前页累计高度（px）
      let currentRowElements = []; // 当前行的元素
      let currentRowMaxHeight = 0; // 当前行最高元素高度（px）

      patientInfusionInfos.value.forEach((item, index) => {
        const printTarget = document.getElementById(`${item.patInfo.patNo}-${index}`);
        if (!printTarget) return;

        // 获取当前元素高度（px）
        const itemHeight = printTarget.offsetHeight;

        // 1. 处理当前行：添加元素并更新行最高高度
        currentRowElements.push(printTarget);
        currentRowMaxHeight = Math.max(currentRowMaxHeight, itemHeight);

        // 2. 当行内元素满3个时，计算行高并判断是否分页
        if (currentRowElements.length === 3) {
          // 计算当前行加入后，页面的总高度
          const totalHeightAfterAdd = currentPageTotalHeight + currentRowMaxHeight;

          // 3. 判断是否需要分页
          if (totalHeightAfterAdd > PAGE_MAX_HEIGHT) {
            // 先打印当前页已有的内容
            LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', currentPageHTML);
            LODOP.NewPage(); // 开启新页

            // 新页初始化：当前行作为新页的第一行
            currentPageHTML = prntStyle;
            currentPageTotalHeight = currentRowMaxHeight;
          } else {
            // 不需要分页，累加当前行高度
            currentPageTotalHeight = totalHeightAfterAdd;
          }

          // 4. 将当前行的3个元素添加到页面HTML
          currentRowElements.forEach(el => {
            currentPageHTML += `<div class="card-container">${el.outerHTML}</div>`;
          });

          // 5. 重置行状态，准备下一行
          currentRowElements = [];
          currentRowMaxHeight = 0;
        }
      });

      // 6. 处理最后一行未填满3个元素的情况
      if (currentRowElements.length > 0) {
        // 计算剩余行加入后的总高度
        const totalHeightAfterAdd = currentPageTotalHeight + currentRowMaxHeight;

        // 如果超出页面高度，单独分页
        if (totalHeightAfterAdd > PAGE_MAX_HEIGHT) {
          LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', currentPageHTML);
          LODOP.NewPage();
          currentPageHTML = prntStyle;
          currentPageTotalHeight = currentRowMaxHeight;
        } else {
          currentPageTotalHeight = totalHeightAfterAdd;
        }

        // 添加剩余元素到页面
        currentRowElements.forEach(el => {
          currentPageHTML += `<div class="card-container">${el.outerHTML}</div>`;
        });
      }

      // 7. 添加最后一页内容
      if (currentPageHTML) {
        LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', currentPageHTML);
      }

      LODOP.PREVIEW();

      // LODOP.PRINT_INIT('infusionCard')
      // LODOP.SET_PRINT_PAGESIZE(1, '210mm', '297mm', '')
      // let printHTML = "";
      // let pageHeightNow = 0;
      // let pageHeighInRow = 0;
      // let rowCount = 0;
      // let isWarp = false;
      // let isRowHeightNew = true
      // const prntStyle = `<style>td{border: 1px solid black;
      //   font-size: 12px;padding: 2px;}</style>`
      // patientInfusionInfos.value.forEach((item, index) => {
      //   let printTarget = document.getElementById(item.patInfo.patNo + '-' + index);
      //   console.log("printTarget", printTarget.offsetHeight)
      //   if (printTarget.offsetHeight > pageHeighInRow) {
      //     pageHeighInRow = printTarget.offsetHeight;
      //     isRowHeightNew = true;
      //   }
      //   // console.log("pageHeighInRow", pageHeighInRow)
      //   // console.log("pageHeightNow", pageHeightNow)
      //   // console.log("HeightAll", pageHeighInRow + pageHeightNow)
      //   if (isWarp) {
      //     isWarp = false
      //     // if(isRowHeightNew)
      //     if (isRowHeightNew && pageHeighInRow + pageHeightNow > 900) {
      //       // console.log("11")
      //       // 此时超出一页
      //       // LODOP.PRINT()
      //       rowCount = 0
      //       LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', prntStyle + printHTML)
      //       LODOP.NewPage(); // 关键：开启新页
      //       printHTML = printTarget.outerHTML;
      //       pageHeightNow = pageHeighInRow;
      //       // isWarp = true
      //       rowCount = 1; // 重置行计数
      //     } else {
      //       // console.log("2")
      //       // pageHeightNow = pageHeighInRow + pageHeightNow;
      //       printHTML += printTarget.outerHTML;
      //     }
      //   } else {
      //     rowCount++;
      //     isRowHeightNew = false
      //     if (rowCount == 3) {
      //       // 换行
      //       isWarp = true;
      //       rowCount = 0;
      //       isRowHeightNew = true;
      //       pageHeightNow = pageHeighInRow + pageHeightNow;
      //       console.log('pageHeightNow',pageHeightNow)
      //     }
      //     printHTML += printTarget.outerHTML;
      //   }
      // });
      // if (printHTML) {
      //   LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', prntStyle + printHTML);
      // }
      // let prntContent1 = document.getElementById("print-test").innerHTML
      // let flexStyles = getStyleText('.print-bottle-card-area');
      // // const prntStyle = `<style>${flexStyles}td{border: 1px solid black;
      // // font-size: 12px;padding: 2px;}</style>`
      // // let printFinal = prntStyle + prntContent1
      // // console.log("prntContent1", prntContent1)
      // // LODOP.ADD_PRINT_HTML('0mm', '0mm', '210mm', '297mm', printFinal)
      // // LODOP.SET_PRINT_STYLE('ItemType', 3)
      // LODOP.PREVIEW();
      printPatientBottleInfos.value = []
      updatePrintState()
    });
  }
}

function updatePrintState() {
  const params = {
    cardType: queryParams.cardType,
    orderNos: []
  }

  patientInfusionInfos.value.forEach(info => {
    if (params.cardType === 'INFUSION_CARD') {
      info.drugGroups.forEach(group => {
        params.orderNos.push(group.mainDrug.actOrderNo)
      })
    } else {
      info.bottleCardDrugs.forEach(group => {
        params.orderNos.push(group.actOrderNo)
      })
    }
  })

  nextTick(() => {
    updatePrintStatus(params).then(res => {
      console.log(res)
    })
  })

}

function getStyleText(selector) {
  var sheets = document.styleSheets;
  var styleText = '';
  for (var i = 0; i < sheets.length; i++) {
    try {
      var rules = sheets[i].cssRules || sheets[i].rules;
      if (rules) {
        for (var j = 0; j < rules.length; j++) {
          if (rules[j].selectorText && rules[j].selectorText.includes(selector)) {
            styleText += rules[j].cssText + '\n';
          }
        }
      }
    } catch (e) { /* 可能跨域安全错误 */ }
  }
  return styleText;
}

// J,S,JS,SJ
// -- 小输液卡
// -- 已打印：print_comment like '%S%'
// -- 未打印：isnull(print_comment,'') not like '%S%'
//
// -- 已打印：print_comment like '%J%'
// -- 未打印：isnull(print_comment,'') not like '%J%'
onMounted(() => {
  initLodop()
  getWardsApi().then(res => {
    userWards.value = res
    if (!queryParams.wardCode) {
      queryParams.wardCode = userWards.value[0].value
    }
    handleWardChange(queryParams.wardCode)
  })
})
</script>

<style scoped>
.ml12 {
  margin-left: 12px;
}

.green-text {
  color: green;
}

.blue-text {
  color: #1146f3
}

.is-disabled {
  color: #a8abb2;
}

.crad-area {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.print-bottle-card-area {
  width: 730px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  /* float: left; */
  padding: 15px 5px;
}

.print-hiden-area {
  /* display: none; */
}

@media print {
  .your-flex-container {
    display: flex !important;
    flex-direction: row !important;
    /* 其他必要flex属性 */
  }

  .flex-item {
    flex: 1 !important;
  }

  .print-bottle-card-area {
    width: 700px;
    display: flex;
    justify-content: center;
    /* align-items: center; */
    flex-wrap: wrap;
  }
}
</style>