<!-- 单据执行 -->
<template>
  <view class="content-wrap">
    <view class="exe-item">
      <view class="exe-item-top">
        <text class="clo6">要求执行日期</text>
		  <uni-datetime-picker
		    class="item-right"
		    type="date"  
			:hide-second="true"
		  	:model-value="exeDate"
		  	@change="(e) => onConfirm(e)"  
		    :border="false"
		  />
      </view>
	  <view class="exe-item-bottom">
		<view class="scroll-container">
          <van-space size="8">
          <van-badge
            v-for="(item, index) in exeTypes"
            :key="index"
            :dot="item.dot">
            <van-button
              class="badge-btn"
              :type="item.type"
			   @click="handleButtonClick(item, index)"
              >{{ item.label }}</van-button>
          </van-badge>
        </van-space>
		</view>
	  </view>
    </view>

    <!-- 新增滚动容器 -->
    <view class="table-scroll-container">
      <view
		v-if="tableData.length > 0"
        class="exe-item flex"
        v-for="(item, index) in tableData"
        :key="index">
        <view class="exe-left">
          <van-checkbox
            shape="square"
            v-model="item.checked"></van-checkbox>
        </view>
        <view class="exe-right">
          <view
            class="exe-item-top"
            v-for="(medical, index) in item.exeMedications"
            :key="index">
            <text class="item-name"> {{ medical.name }}</text>
            <view
              v-if="index == 0"
              class="item-right-li mini">
              {{ item.exeDateTime }}
            </view>
			<view class="tag-container">
            <view class="top-btns" v-for="(type, index) in medical.useArr">
				<uni-tag :inverted="index === 0 || index === 5 ? false : true" :text="type.label"  :type="type.type" />
			  </view>
            </view>
          </view>
          <view class="exe-item-time-view">
            <van-space class="exe-item-time" >
				<view v-for="(time, index) in item.exeTimes">
					<uni-tag :text="time.time" size="mini"  type="primary"
					 :inverted="time.state == 'disabled'"/>
				  </view>
            </van-space>
            <view
              class="item-right-li mini"
              @tap="showDetail(item)">
              {{item.showNum}}
              <van-icon name="arrow" />
            </view>
          </view>
        </view>
      </view>
	  
	  <!-- 暂无数据组件：默认样式 -->
	  <no-data v-if="tableData.length === 0"></no-data>
    </view>

    <view class="bottom-btns">
      <van-button
        class="bottom-btn"
        plain
        type="default"
        @tap="selectAll"
        >全选</van-button>
      <van-button
        class="bottom-btn"
        type="primary"
        @tap="exeConfirm"
        >执行</van-button>
    </view>
    <DetailList
      :visibleDetail="visibleDetail"
      :close="() => (visibleDetail = false)"
      :detailData="detailData" />
  </view>
</template>

<script setup>
  // 原有脚本逻辑保持不变
  import { ref, watch, onMounted, nextTick } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import { $http } from '../../../config/https';
  import NoData from './NoData.vue';
  import Util from '../../../utils/util.js';
  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 exeDate = ref(''); // 执行日期
  // 执行类型
  const exeTypes = ref([]);
  //当前选中的类型
  const exeTypesItem = ref('');
  // 执行列表数据
  const tableData = ref([]);
  
  onShow(() => {
  	
  });
  
  const formatDateTime = () => {
    const date = new Date();
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  };
  
  // 处理接口数据的方法
  const handleSheetData = (sheetList) => {
    if (!Array.isArray(sheetList)) return [];
    return sheetList.map((item, index) => {
      return {
        // 去除descripts中的*、制表符、空格等多余字符
        label: item.descripts?.replace(/[\t*]/g, '').trim() || '',
        // 选中为primary，默认不选中
        type: index === 0 ? 'primary' : 'default',
        // 红点
        dot: false,
		// code
		code: item.code
      };
    });
  };
  
  //初始化
  const initData = () =>{
	  let exeDateNow = formatDateTime();
	  exeDate.value = exeDateNow;
  	$http.post('urlDeault',this, {
  	    code: '04220024',
  	    data: {
  	      params: [{
	  		"hospID": userData.value.hospID,
	  		"locID": userData.value.locID,
	  		"stDate": exeDate.value,
	  		"stTime": "00:00:00",
	  		"endDate": exeDate.value,
	  		"endTime": "23:59:59",
	  		"patients": [props.patNo]
	  	  }]
  	    },
  	    success: function(res) {
  	      if (+res.errorCode === 0) {
  	       exeTypes.value = handleSheetData(res.result.sheet);
		   exeTypesItem.value = exeTypes.value[0].code;
		   getPatYZInfo();
  	      }
  	    },
  	});
  }
  
  //获取医嘱列表数据
  const getPatYZInfo = () => {
	  $http.post('urlDeault',this, {
	      code: '04220025',
	      data: {
	        params: [{
	  		"hospID": userData.value.hospID,
	  		"sheetCode": exeTypesItem.value || "QBYZ",
	  		"locID": userData.value.locID,
	  		"stDate": exeDate.value,
	  		"stTime": "00:00:00",
	  		"endDate": exeDate.value,
	  		"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 === '未执行') 
              : [];
          const exeTimes = unExecutedInfos.map((execInfo, index) => {
              // 提取execSttTime中的时间部分（如"12-15 15:02" -> "15:02"）
              const time = (execInfo.execSttTime || '').split(' ')[1] || '';
              return {
                  time,
                  // 第一个元素state为空，其余为disabled
                  state: index === 0 ? '' : 'disabled'
              };
          });
          // 4. 组装最终对象
          return {
              checked: true, // 默认选中，可根据需求调整
              exeDateTime: item.execTime || '', // execTime赋值给exeDateTime
              showNum,
              exeMedications,
              exeTimes,
			  execInfos: item.execInfos,
			  startDeteTime: item.ordStartDateTime.slice(5, 16),
			  endDeteTime: item.ordStopDateTime.slice(5, 16),
			  ordID: item.ordID
          };
      });
  }
  
  //不同医嘱类型点击事件
  const handleButtonClick = (item, index) => {
	if(item.type === 'primary'){
		exeTypes.value[index].type = 'default';
		exeTypesItem.value = '';
		getPatYZInfo();
	}else{
		exeTypes.value.forEach((itm, idx) => itm.type = idx === index ? 'primary' : 'default');
		exeTypesItem.value = item.code;
		getPatYZInfo();
	}
  };

  watch(
    () => props.activeTab,
    (newVal) => {
      if (newVal != 0) return;
	  initData();
    },
    { immediate: true, deep: true },
  );

  // 确定选择日期
  const onConfirm = (value) => {
	exeDate.value = value;
	exeTypes.value.map(item => {
		if(item.type === "primary"){
			// 选择日期后刷新数据
			exeTypesItem.value = item.code;
			getPatYZInfo();
		}
	})
  };
  // 全选
  const selectAll = () => {
    const allChecked = tableData.value.every((item) => item.checked);
    tableData.value.forEach((item) => {
      item.checked = !allChecked;
    });
  };
  // 执行
  const exeConfirm = () => {
    const selectedItems = tableData.value.filter((item) => item.checked);
    if (selectedItems.length === 0) {
      uni.showToast({
        title: '请至少选择一项进行执行',
        icon: 'none',
      });
      return;
    }
	const idArr = selectedItems.map(item => item.execInfos[0].execID);
	$http.post('urlDeault',this, {
	    code: '04220026',
	    data: {
	      params: [{
			"hospID": userData.value.hospID,
			"locID": userData.value.locID,
			"userID": userData.value.userID,
			"code": "F",
			"ordIDs": idArr
		  }]
	    },
	    success: function(res) {
	      if (+res.errorCode === 0) {
			uni.showToast({
			  title: '执行成功',
			  icon: 'success',
			});
			getPatYZInfo();
	      }
	    }
	});
  };
  // 查看详情
  const showDetail = (data) => {
    visibleDetail.value = true;
    detailData.value = data;
  };
</script>
<style scoped>
  @import url(../common.css);
</style>