<template>
  <view>
    <nav-bar :navbarData="navbarData"></nav-bar>
    <view :style="`margin-top: ${height * 2 - 20}rpx; height: calc(100vh - ${height * 2 - 2}rpx)`">
      <view class="userbg" :style="`background-image:url(${imgDomain}/images/icon/bg_patients_bg.png)`">
        <view class="search">
          <van-row>
            <view class="searchcontent">
			   <input
				   type="text"
				   class="search-input"
				   placeholder="输入电话，登记号，身份证，姓名，病案号搜索"
				   placeholder-style="color: #999"
				   @input="handleInput"
				 />
            </view>
            <view class="scan" @tap="scan">
              <image :src="`${imgDomain}/images/icon/ydhl_scan.png`" class="custom-icon" />
            </view>
          </van-row>
        </view>
        <view class="user" :style="`background-image:url(${imgDomain}/images/icon/bg_user.png)`">
          <view class="usericon">
            <image class="icon" :src="`${imgDomain}/images/icon/avatar_nurse.png`"></image>
          </view>
          <view class="userinfo">
            <view class="date">{{ dateStr }}</view>
            <view class="username">
              {{ userData?.userName }}
              <span class="but-span">
                <view class="userout" @tap="userOutFun">退出登录</view>
                <view class="changeloc" @tap="changeloc">切换科室</view>
              </span>
            </view>
          </view>
        </view>
        <progress :percent="percent" activeColor="#D52424" stroke-width="1"></progress>
      </view>

      <view class="wardtitle">
        <!-- <text style="padding-left: 3px">在院患者 ({{ userData.locDesc }})</text> -->
		 <view @click="togglePatientType">
		      <text style="padding-left: 3px">{{ currentType }}</text>
		      <text class="refresh-icon"> ↺切换</text>
		</view>
      </view>
      <view class="patcontent">
		  
		<!-- 在院患者列表 -->
        <view 
		  v-if="+currentTypeIndex === 0"
          class="patlist" 
          @tap="gotoPatMainPage(item)" 
          v-for="(item, index) in wardPatList" 
          :key="index">
          <van-cell
            :icon="item.patSexCode === '1' ? `${imgDomain}/images/icon/gender-male.png` : `${imgDomain}/images/icon/gender-female.png`"
            use-label-slot>
            <van-row slot="title" class="topinfo">
              <van-col span="4">{{ item.admBedCode }}</van-col>
              <van-col span="15">
                <view style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
                  {{ item.patName }}
                </view>
              </van-col>
              <van-col span="5">
                <view class="paticon">
                  <view
                    :style="`width:18px;height:18px;background:url(${imgDomain}/images/mobilenurse/bedicon.png);background-position: ${getposition(iconitem)}`"
                    v-for="(iconitem, iconindex) in item.admIcon"
                    :key="iconindex"
                  ></view>
                </view>
              </van-col>
            </van-row>
            <van-row slot="label" class="bottominfo">
              <van-col span="19">入院时间: {{ item.admDatetime }}</van-col>
              <van-col span="5">
                <view v-if="item.nurseLv === '特级'" class="nurse-lv-css-red">{{ item.nurseLv }}</view>
                <view v-if="item.nurseLv === '一级'" class="nurse-lv-css-pink">{{ item.nurseLv }}</view>
                <view v-if="item.nurseLv === '二级'" class="nurse-lv-css-blue">{{ item.nurseLv }}</view>
                <view v-if="item.nurseLv === '三级'" class="nurse-lv-css-greenyellow">{{ item.nurseLv }}</view>
              </van-col>
            </van-row>
          </van-cell>
        </view>
		
		<!-- 今日门诊手术患者列表 -->
		<view
		  v-if="+currentTypeIndex === 1"
		  class="patlist" 
		  @tap="openPatOperaModal(item)" 
		  v-for="(item, index) in wardPatList" 
		  :key="index">
		  <van-cell
		    :icon="item.patSexCode === '1' ? `${imgDomain}/images/icon/gender-male.png` : `${imgDomain}/images/icon/gender-female.png`"
		    use-label-slot>
		    <van-row slot="title" class="topinfo">
		      <van-col span="20">{{ item.admLocDesc+ ' - ' + item.patName}}</van-col>
		      <van-col span="4">
		        <view class="paticon">
		          <view
		            :style="`width:18px;height:18px;background:url(${imgDomain}/images/mobilenurse/bedicon.png);background-position: ${getposition(iconitem)}`"
		            v-for="(iconitem, iconindex) in item.admIcon"
		            :key="iconindex"
		          ></view>
		        </view>
		      </van-col>
		    </van-row>
		    <van-row slot="label" class="bottominfo">
		      <van-col span="19">就诊时间: {{ item.admDatetime }}</van-col>
		      <van-col span="5"></van-col>
		    </van-row>
		  </van-cell>
		</view>
		
      </view>
    </view>
    <van-action-sheet 
      :show="showchangeLoc" 
      title="请选择科室" 
      @close="onClose" 
      @cancel="onClose"
    >
      <van-cell
        :title="loc.logonGroupDesc"
        :label="loc.logonHospDesc"
        :value="loc.logonLocDesc"
        value-class="locclass"
        :class="curLoc === index ? 'locitemcur' : 'locitem'"
        label-class="label"
        title-class="title"
        @tap="changeToLoc(loc, index)"
        v-for="(loc, index) in locList"
        :key="index"
      ></van-cell>
    </van-action-sheet>
	
	<!-- 引入弹框组件 -->
	    <PaymentDetailPopup 
	      :show="showPopup"
	      :patientInfo="patientInfo"
	      :paymentDetails="paymentDetails"
	      @close="showPopup = false"
	    />
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { httpconfig } from '../../config/httpconfig';
import WXBizDataCrypt from '../../utils/WXBizDataCrypt';
import { onLoad ,onShow } from '@dcloudio/uni-app';
import Util from '../../utils/util.js';
import Common from '../../utils/common.js';
import { $http } from '../../config/https';
import navBar from '@/pages/components/navbar/index';
import PaymentDetailPopup from '@/pages/components/PaymentDetailPopup.vue'

// // 工具函数（替代原wxs模块）
// const getspan = (widh) => {
//   return widh.replace("px", "");
// };

// const findPat = (patinfo, searchData) => {
//   if (!searchData) return 1;
//   const searchStr = searchData.toUpperCase();
//   return (
//     patinfo.patName.includes(searchData) ||
//     patinfo.admBedCode.includes(searchData) ||
//     patinfo.patID.includes(searchData) ||
//     patinfo.patNameSpell.includes(searchStr) ||
//     patinfo.patNo.includes(searchStr) ||
//     patinfo.patMedicalNo.includes(searchStr) ||
//     patinfo.admID === searchData
//   ) ? 1 : 0;
// };

const getposition = (iconitem) => {
  return `-${(iconitem.position % 10 - 1) * 18}px -${Math.floor(iconitem.position / 10) * 18}px`;
};

// 响应式数据
const height = ref('');
const navbarData = ref({
  background: '',
  title: '普瑞眼科移动护理',
  height: '100',
  bottom: true,
  isGoBack: false,
  cleanPat: 'Y'
});

const userData = ref(uni.getStorageSync('userData') || {});
const patInfo = ref(uni.getStorageSync('patInfo') || {});
const timer = ref(null);
const dateStr = ref('2020年11月15日 14:25 星期三');
const searchData = ref('');
const countTime = ref(1500);
const searchWaiting = ref(false);
const showchangeLoc = ref(false);
const imgDomain = ref(httpconfig.imgDomain);
const locList = ref([]);
const curLoc = ref(-1);
const wardPatList = ref('');
const percent = ref(0);
const downLineShow = ref(true);
// 控制弹框显示/隐藏
const showPopup = ref(false);
// 患者信息（响应式对象）
const patientInfo = ref({name: '',department: '',doctor: '',time: ''});
// 缴费明细数组（响应式数组）
const paymentDetails = ref([]);

// 定义患者类型选项
const patientTypes = [
  { key: 'inpatient', label: `在院患者 (${userData.value.locDesc})` },
  { key: 'outpatient', label: '今日门诊手术患者' }
];
// 当前选中的类型
const currentTypeIndex = ref(0);
// 切换患者类型
const togglePatientType = () => {
  currentTypeIndex.value = (currentTypeIndex.value + 1) % patientTypes.length;
  wardPatList.value = '';
  getAuthorityApply();
};
// 当前显示的类型文本
const currentType = computed(() => {
  return patientTypes[currentTypeIndex.value].label;
});

onShow(() => {
  try {
    const pages = getCurrentPages()
    if (pages.length > 0) {
      const currentPage = pages[pages.length - 1]
      const currentRoute = currentPage.route // 当前页面路由
      // 更新全局变量
      if (uni.$appGlobal) {
        uni.$appGlobal.globalData.value.currentRoute = currentRoute
      }
    }
	
	getAuthorityApply();
	getAppVersion();
  } catch (err) {
    console.error('更新当前路由失败：', err)
  }
})

// 生命周期
onMounted(() => {
  // 页面显示时执行
  if (!imgDomain.value) {
    imgDomain.value = uni.getStorageSync('appUrlAddress');
  }
  
  const storedUserData = uni.getStorageSync('userData');
  const storedPatInfo = uni.getStorageSync('patInfo');
  if (storedUserData) {
    userData.value = storedUserData;
    patInfo.value = storedPatInfo;
  }
  
  getAuthorityApply();
  showTime();
  getAppVersion();
});

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});

// 获取应用版本
const getAppVersion = async () => {
  const appInfo = uni.getAppBaseInfo();
  const appVersion = appInfo.appVersion;
  const appVersionMessage = await getAppVersionMessage();
  $http.post('urlDeault',this, {
    code: '02010011',
    data: {
      params: [{ propId: '76||377' }]
    },
    success: (res) => {
      if (+res.errorCode === 0) {
        const setValue = res.result.rows[0].setValue;
        if (setValue > appVersion) {
          uni.showModal({
            title: `检测到新版本V${setValue}`,
            content: appVersionMessage.replace(/\\n/g, '\n'),
			confirmText: '开始下载更新',
			cancelText: '稍后更新', 
            complete: (res) => {
              if (res.confirm) {
                downAppApk(setValue);
              }
            }
          });
        }
      }
    }
  });
};
const getAppVersionMessage = () => {
  return new Promise((resolve) => {
    $http.post('urlDeault',this, {
      code: '02010011',
      data: {
        params: [{ propId: '76||400' }]
      },
      success: (res) => {
        if (+res.errorCode === 0) {
          const setMessage = res.result.rows[0].setValue;
          resolve(setMessage);
        } else {
          resolve('是否立即下载更新?');
        }
      },
      fail: () => {
        resolve('是否立即下载更新?');
      }
    });
  });
};

const downAppApk = (setValue) => {
  const appUrlAddress = uni.getStorageSync('appUrlAddress');
  const downloadTask = uni.downloadFile({
    url: `${appUrlAddress}/images/apk/ydhl-${setValue}.apk`,
    success: (downloadResult) => {
      plus.runtime.install(
        downloadResult.tempFilePath,
        { force: true },
        () => {
          uni.showToast({ title: '更新成功，重启中', icon: 'none' });
          plus.runtime.restart();
        }
      );
    },
    fail: (res) => {
      uni.showToast({ title: `download apk fail: ${res}`, icon: 'none' });
    },
    complete: () => {
      downloadTask.offProgressUpdate();
    }
  });

  downloadTask.onProgressUpdate((res) => {
    percent.value = res.progress;
  });
};

const scan = () => {
  uni.scanCode({
    success: (res) => {
      const scValue = res.result;
      if (scValue.length > 20) {
        uni.navigateTo({ url: scValue });
      } else {
        Util.getPatInfoNew(res.result, () => {
          uni.navigateTo({ url: '../patMainPage/patMainPage' });
        });
      }
    }
  });
};

const getPatInfo = (admID) => {
  $http.post('urlDeault',this, {
    code: '03030002',
    data: { params: [{ admID }] },
    success: (res) => {
      if (+res.errorCode === 0) {
        patInfo.value = res.result;
        uni.setStorage({ key: 'patInfo', data: res.result });
      }
    }
  });
};

//获取列表数据前校验是否处于登录状态
const getAuthorityApply = () => {
  const storedUserData = uni.getStorageSync('userData');
  if (storedUserData) {
    userData.value = storedUserData;
	if(+currentTypeIndex.value === 1){
		getMZOperaPatList();
	}else{
		getWardPatList();
	}
  } else {
    gotoAuthority();
  }
};

const gotoAuthority = () => {
  uni.reLaunch({ url: '../authentication/authentication' });
};

//获取住院病区患者列表数据
const getWardPatList = () => {
  const userData = uni.getStorageSync('userData');
  uni.showLoading({ title: '数据加载中...' });
  
  $http.post('urlDeault',this, {
    code: '04020025',
    data: {
      params: [{ wardID: userData.locID, patMessage: searchData.value || '' }]
    },
    success: (res) => {
      uni.hideLoading();
      if (+res.errorCode === 0) {
        wardPatList.value = res.result.patList;
        showchangeLoc.value = false;
      } else if (['01040053', '01040054', '01040055'].includes(res.errorCode)) {
        getWardPatList();
      }
    }
  });
};

//获取今日门诊手术患者列表数据
const getMZOperaPatList = () => {
  const userData = uni.getStorageSync('userData');
  uni.showLoading({ title: '数据加载中...' });
  $http.post('urlDeault',this, {
    code: '04020033',
    data: {
      params: [{ patMessage: searchData.value || '' }]
    },
    success: (res) => {
      uni.hideLoading();
      if (+res.errorCode === 0) {
        wardPatList.value = res.result.patList;
      } else {
         uni.showToast({ title: res.errorMessage, icon: 'none' });
      }
    }
  });
};

//住院患者前往患者主页
const gotoPatMainPage = (patInfoData) => {
  Util.getPatInfo(patInfoData.admID, () => {
    uni.navigateTo({ url: '../patMainPage/patMainPage' });
  });
};

//门诊患者打开缴费弹框
const openPatOperaModal = (patInfoData) => {
	patientInfo.value = {
		name: patInfoData.patName,
		department: patInfoData.admLocDesc,
		doctor: patInfoData.admDocDesc,
		time: patInfoData.admDatetime,
	};
	//获取门诊手术患者详情数据
	getMZOperaPatDetail(patInfoData.admID);
};

//门诊手术患者详情数据
const getMZOperaPatDetail = (admID) => {
  uni.showLoading({ title: '数据加载中...' });
  $http.post('urlDeault',this, {
    code: '04020034',
    data: {
      params: [{ admID: admID }]
    },
    success: (res) => {
      uni.hideLoading();
      if (+res.errorCode === 0) {
		paymentDetails.value = res.result;
        showPopup.value = true;
      } else {
         uni.showToast({ title: res.errorMessage, icon: 'none' });
      }
    }
  });
};

const changeloc = () => {
  getLocList();
};

const userOutFun = () => {
  uni.showModal({
    title: '退出登录',
    content: '您确定要退出当前登录工号吗？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('userData');
        gotoAuthority();
      }
    }
  });
};

const onClose = () => {
  showchangeLoc.value = false;
};

const showTime = () => {
  const showDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  
  timer.value = setInterval(() => {
    const time = new Date();
    const year = time.getFullYear();
    const month = time.getMonth() + 1;
    const date = time.getDate();
    const day = time.getDay();
    const hour = time.getHours().toString().padStart(2, '0');
    const minutes = time.getMinutes().toString().padStart(2, '0');
    const second = time.getSeconds().toString().padStart(2, '0');
    
    dateStr.value = `${year}年${month}月${date}日  ${hour}:${minutes}:${second} ${showDay[day]}`;
  }, 1000);
};

const handleInput = (val) => {
  let inputvalue = val.detail.value.replace(/\s+/g, '');
  if (inputvalue.length === 10) {
    searchData.value = '';
    Util.getPatInfoNew(inputvalue, () => {
      uni.navigateTo({ url: '../patMainPage/patMainPage' });
    });
  } else {
    searchData.value = inputvalue;
    if (!searchWaiting.value) {
      searchTimer();
    }
  }
};

const searchTimer = () => {
  searchWaiting.value = true;
  
  const setTimer = setInterval(() => {
    countTime.value -= 500;
    if (countTime.value <= 0) {
      countTime.value = 1500;
      searchWaiting.value = false;
      clearInterval(setTimer);
      getWardPatList();
    }
  }, 500);
};

const getLocList = () => {
  const userData = uni.getStorageSync('userData');
  const data = {
    params: [{
      currentLocFlag: 'Y',
      language: 'CN',
      userCode: userData.userCode
    }]
  };
  
  $http.post('urlDeault',this, {
    code: '01040043',
    data,
    success: (res) => {
      if (+res.errorCode === 0) {
        let currentIndex = -1;
        const logonLocAry = res.result.logonLocAry;
        
        logonLocAry.forEach((locInfo, index) => {
          if (
            locInfo.logonLocID === userData.locID &&
            locInfo.logonHospID === userData.hospID &&
            locInfo.logonGroupID === userData.groupID
          ) {
            currentIndex = index;
          }
        });
        
        locList.value = logonLocAry;
        curLoc.value = currentIndex;
        showchangeLoc.value = true;
      }
    }
  });
};

const changeToLoc = (loc) => {
  const updatedUserData = { ...userData.value };
  updatedUserData.locID = loc.logonLocID;
  updatedUserData.locDesc = loc.logonLocDesc;
  updatedUserData.groupID = loc.logonGroupID;
  updatedUserData.groupDesc = loc.logonGroupDesc;
  updatedUserData.hospID = loc.logonHospID;
  updatedUserData.hospDesc = loc.logonHospDesc;
  updatedUserData.hospCode = loc.logonHospCode;
  
  userData.value = updatedUserData;
  uni.setStorage({
    key: 'userData',
    data: updatedUserData,
    success: () => {
      uni.removeStorage({ key: 'patInfo' });
      getWardPatList();
    }
  });
};
</script>

<style>
/* 保持原样式不变 */
.pat {
    font-size: 30rpx;
    padding: 0 20rpx;
}

.patInfo {
    font-size: 26rpx;
    font-weight: 400;
}

.userbg {
    width: 100%;
    height: 340rpx;
    background-size: 100% auto;
    background-repeat: no-repeat;
}

.search {
    height: 100rpx;
    padding: 20rpx 30rpx 0;
}

.searchcontent {
    width: calc(100% - 120rpx);
    float: left;
}

.search-input {
  margin-top: 18rpx;
  height: 70rpx;
  border-radius: 40rpx;
  background-color: #ffffff;
  border: #007aff 1px solid;
  padding: 0rpx  10rpx;
}

.searchcontent .van-cell__title {
    max-width: 0 !important;
    min-width: 0 !important;
    -webkit-flex: 0;
    flex: 0;
}

.scan {
    width: 100rpx;
    padding-left: 16rpx;
    float: left;
    color: #fff;
    text-align: center;
}

.user {
    width: calc(100% - 30rpx);
    height: 200rpx;
    background-size: 100% auto;
    background-repeat: no-repeat;
    padding: 0 18rpx 20rpx;
    margin-top: -8rpx !important;
}

.usericon {
    border-radius: 50%;
    margin-left: 12rpx;
    background: #e3e4fc;
    height: 120rpx;
    width: 120rpx;
    text-align: center;
    line-height: 120rpx;
    float: left;
    margin: 40rpx 20rpx;
}

.userinfo {
    float: left;
    width: calc(100% - 190rpx);
    height: 120rpx;
    margin: 40rpx 0;
    line-height: 60rpx;
    padding-right: 30rpx;
}

.date {
    font-size: 15px;
    font-weight: 400;
    color: #333333;
}

.icon {
    height: 120rpx;
    width: 120rpx;
    border-radius: 50%;
}

.wardtitle {
    width: calc(100% - 56px);
    margin: 0 28rpx;
    height: 42rpx;
    font-size: 15px;
    border-left: 8rpx solid #007aff;
    font-weight: 400;
    color: #333333;
    line-height: 42rpx;
    margin-bottom: 10rpx;
}
.refresh-icon {
  font-size: 14px;
  margin-left: 8px;
  color: #007aff;
  transition: transform 0.5s ease;
}
.username {
    font-size: 14px;
    font-weight: 400;
    color: #666666;
    display: flex;
    justify-content: space-between;
}

.unwrite {
    color: red !important;
    font-size: 10px !important;
}

.but-span {
    display: flex;
    flex-direction: row;
}

.changeloc {
    width: 140rpx;
    height: 50rpx;
    background: #007aff;
    border-radius: 4px;
    font-size: 25rpx;
    color: #fff;
    line-height: 50rpx;
    border-radius: 8rpx;
    text-align: center;
}

.userout {
    width: 120rpx;
    height: 46rpx;
    border-radius: 4px;
    border: 1px solid;
    color: #007aff;
    font-size: 25rpx;
    line-height: 46rpx;
    border-radius: 8rpx;
    text-align: center;
    margin-right: 20rpx;
}

.write {
    color: #809aff !important;
    font-size: 10px !important;
}

.patcontent {
    overflow: auto;
    height: calc(100% - 500rpx);
}

.patlist .van-cell,
.patlist .van-cell__left-icon-wrap {
    height: 120rpx !important;
	padding: 0 8px !important;
}

.patlist .van-cell__left-icon-wrap {
    line-height: 120rpx !important;
}

.patlist .van-icon--image,
.patlist .van-icon__image {
    height: 90rpx !important;
    width: 90rpx !important;
    bottom: 20rpx !important;
}

.patlist .van-col {
    white-space: nowrap;
    min-height: 1px;
}

.patlist .van-cell__value {
    width: 0 !important;
}

.patlist .van-cell__title {
    padding-left: 10rpx;
}

.patlist .van-cell__right-icon-wrap {
    height: 100%;
}

.topinfo {
    font-size: 32rpx;
    font-weight: 400;
    color: #666666;
    height: 45rpx;
    line-height: 40rpx;
	padding-top: 8px;
}
.topinfo .van-col {
  text-align: left;
}
.paticon {
    display: flex;
    flex-direction: row;
	padding: 0rpx !important;
}
.bottominfo {
    font-weight: 400;
    color: #999999;
    height: 40rpx;
    line-height: 40rpx;
}
/* 让row下的所有col内容左对齐 */
.bottominfo .van-col {
  text-align: left;
}

.nurse-lv-css-red {
    background-color: red;
    color: #fff;
    border-radius: 4rpx;
    padding: 0rpx 18rpx;
    font-size: 20rpx;
    width: 50rpx;
}
.nurse-lv-css-pink {
    background-color: pink;
    color: #fff;
    border-radius: 4rpx;
    padding: 0rpx 18rpx;
    font-size: 20rpx;
    width: 50rpx;
}
.nurse-lv-css-greenyellow {
    background-color: rgb(93, 187, 93);
    color: #fff;
    border-radius: 4rpx;
    padding: 0rpx 18rpx;
    font-size: 20rpx;
    width: 50rpx;
}
.nurse-lv-css-blue {
    background-color: #007aff;
    color: #fff;
    border-radius: 4rpx;
    padding: 0rpx 18rpx;
    font-size: 20rpx;
    width: 50rpx;
}

.custom-icon {
    margin-top: 24rpx;
    width: 60rpx;
    height: 60rpx;
}

.locclass {
    font-size: 34rpx;
    font-weight: 500;
    color: #000 !important;
}

.locitem .van-cell {
    background: #fff;
}

.locitemcur .van-cell {
    background: #bfe6f8 !important;
}

.label {
    font-size: 32rpx !important;
    font-weight: 500;
}

.title {
    font-size: 34rpx;
    font-weight: 500;
    color: #000;
}
</style>