<!-- 全部医嘱 / 需处理 -->
<template>
<view class="table-scroll-container-OL">
  <view class="content-wrap">
    <view
	  v-if="tableData.length > 0"
      class="exe-item"
      v-for="(item, index) in tableData"
      :key="index">
      <Detailtem
        :data="item"
        v-slot="data">
        <view
          v-if="data.visible"
          @tap="showDetail(item)"
          class="item-right-li milt">
          <text class="priamry">执行明细</text>
          <van-icon name="arrow" />
        </view>
      </Detailtem>
    </view>
	<!-- 暂无数据组件：默认样式 -->
	<no-data v-if="tableData.length === 0"></no-data>
    <DetailList
      :visibleDetail="visibleDetail"
      :close="() => (visibleDetail = false)"
      :detailData="detailData" />
  </view>
</view>
</template>

<script setup>
  import { ref, watch, onMounted, nextTick } from 'vue';
  import { $http } from '../../../config/https';
  import NoData from './NoData.vue';
  import Util from '../../../utils/util.js';
  import Detailtem from './Detailtem.vue';
  import DetailList from './DetailList.vue';
  const props = defineProps({
    activeTab: {type: Number,default: 0},
	patNo:{type: String ,default: ''},
  });
  const userData = ref(uni.getStorageSync('userData') || {});
  const visibleDetail = ref(false); // 详情显示
  const detailData = ref('');
  // 执行列表数据
  const tableData = ref([]);
  
  //获取医嘱列表数据
  const getPatYZInfo = (code) => {
  	  $http.post('urlDeault',this, {
  	      code: '04220025',
  	      data: {
  	        params: [{
  	  		"hospID": userData.value.hospID,
  	  		"sheetCode": code ? code :"QBYZ",
  	  		"locID": userData.value.locID,
  	  		"stDate": '',
  	  		"stTime": "00:00:00",
  	  		"endDate": '',
  	  		"endTime": "23:59:59",
  	  		"patients": [props.patNo]
  	  	  }]
  	      },
  	      success: function(res) {
  	        if (+res.errorCode === 0) {
  				// 执行转换
  				const transformedData = transformOrderData(res.result.order);
  				tableData.value = transformedData;
  	        }
  	      },
  	  });
  }
  
  /**
   * 处理医嘱数据，转换为指定格式的数组
   * @param {Array} originalData 原始医嘱数据数组
   * @returns {Array} 转换后的格式化数组
   */
  const transformOrderData =(originalData)=> {
      // 定义type可选值，用于随机分配
      const typeOptions = ['primary', 'warning', 'default', 'success','error'];
      // 处理空数据情况
      if (!Array.isArray(originalData) || originalData.length === 0) {
          return [];
      }
	  // 封装单个item转换为exeMedications项的逻辑（复用）
	   const getMedicationItem = (item) => {
	  		  return {
	  			  name: item.medDesc || '', // 赋值medDesc
	  			  useArr: (item.ordText || '')
	  				  .split('^') // 按^拆分
	  				  // .filter(part => part.trim() !== '') // 过滤空值
	  				  .map((part,index) => ({
	  					  label: part.trim(),
	  					  type: index === 5 ? 'warning' : 'primary'
	  				  }))
	  		  };
	   };
      // 遍历原始数据进行转换
      return originalData.map(item => {
          // 1. 计算已执行数量和总数量，生成showNum
          const totalExecCount = Array.isArray(item.execInfos) ? item.execInfos.length : 0;
          const executedCount = Array.isArray(item.execInfos) 
              ? item.execInfos.filter(exec => exec.statusDesc === '已执行').length 
              : 0;
          const showNum = `${executedCount}/${totalExecCount}`;
          // 2. 处理exeMedications：先加当前item，再加children里的所有item
          const exeMedications = [];
          // 先添加当前item的medication
          exeMedications.push(getMedicationItem(item));
          // 再添加children数组中的所有item（判断children存在且为数组）
          if (Array.isArray(item.children) && item.children.length > 0) {
          			 item.children.forEach(child => {
          				 exeMedications.push(getMedicationItem(child));
          			 });
          }
          // 3. 处理exeTimes：过滤未执行的execInfos，提取时间并设置state
          const unExecutedInfos = Array.isArray(item.execInfos) 
              ? item.execInfos.filter(exec => exec.statusDesc === '未执行') 
              : [];
          // 4. 组装最终对象
          return {
              exeDateTime: item.execTime || '', // execTime赋值给exeDateTime
              showNum,
			  exeMedications,
			  execInfos: item.execInfos,
			  startDeteTime: item.ordStartDateTime.slice(5, 16),
			  endDeteTime: item.ordStopDateTime.slice(5, 16),
			  ordID: item.ordID
          };
      });
  }

  watch(
    () => props.activeTab,
    (newVal) => {
      if (newVal === 0) return;
        const currentType = +newVal === 1 ? 'QBYZ' : 'HandlerOrder';
        getPatYZInfo(currentType);
    },
    { immediate: true, deep: true },
  );
  // 查看详情
  const showDetail = (data) => {
    visibleDetail.value = true;
    detailData.value = data;
  };
</script>
<style scoped>
  @import url(../common.css);
</style>
