<template>
  <view class="container">
    <view class="content">
      <view :class="!authorize ? 'userInfoTopFixe' : ''">
        <userInfo :userInfo="currentUser" :type="pageType" :bgClass="authorize ? 'bgLinGra' : 'bgWhite'"></userInfo>
        <view class="public_inner_table" v-if="!authorize">
          <view class="report_type_box displayFlexRow">
            <view class="public_inner_table_item" :class="queryData.ReportType == '1' ? 'public_inner_table_item_active' : ''" @click="navClick('1')">检验报告单</view>
            <view class="public_inner_table_item" :class="queryData.ReportType == '2' ? 'public_inner_table_item_active' : ''" @click="navClick('2')">检查报告单</view>
          </view>
          <screening :isShowTime="false" :screen="screen" @setScreenData="setScreenData" @queryRecords="queryRecords" @resetScreen="resetScreen"></screening>
        </view>
      </view>
      
      <view class="content_inner" v-if="!authorize">
        <view class="public_list" v-if="!showNoData">
          <view class="public_card border_bottom" @click="deptClick(item)" v-for="(item, index) in reportList" :key="index">
            <view class="public_card_con">
              <view class="public_user_info">
                <view class="public_user_name">{{ item.ItemName }}</view>
                <view class="public_user_time">{{ item.SubmissionTime }}</view>
              </view>
            </view>
            <view class="state_tip colorRed" v-if="item.State != '1'">报告未出</view>
            <image class="public_right_img" :src="iconUrl.icon_right"></image>
          </view>
        </view>
        <view v-if="showNoData" class="noData">
          <noData :value="queryData.ReportType == '1' ? '没有找到该患者的检验报告单' : queryData.ReportType == '2' ? '没有找到该患者的检查报告单' : '没有查到该患者的报告单信息'"></noData>
        </view>
      </view>
      <authorizeMode v-else :userInfo="currentUser" :level="authLevel"></authorizeMode>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { common } from '@/utils';
import icon from '@/utils/icon';
import { getReportList as getReportListApi } from '@/pagesPatient/service/report/index';
// 组件引用
import noData from '@/pages/st1/components/noData/noData.vue';
import userInfo from '@/pagesPersonal/st1/components/userInfo/userInfo.vue';
import screening from '@/pagesPatient/st1/components/screening/screening.vue';
import authorizeMode from '@/pages/st1/components/authorizeMode/authorizeMode.vue';

const app = getApp();
const iconUrl = ref(icon);
const pageType = ref('card'); // card 组件进入卡列表 hospital 组件进入住院号列表
const currentUser = ref<any>({});
const reportList = ref<any[]>([]);
const showNoData = ref(false);
const authorize = ref(false); // 暂时默认为 false，如果需要权限校验逻辑需补充
const authLevel = ref(2); // 假设的默认值

const screen = reactive({
  screenKey: 'screen',
  btnName: '',
  startDate: common.dateFormat(new Date(Date.now() - (180 * 24 * 60 * 60 * 1000))).formatYear, // 开始时间
  endDate: common.afterFewDays(1),
  state: [],
  sourceType: [],
  memberId: [],
  columns: [],
  screenTime: []
});

const queryData = reactive<any>({
  CardType: '1',
  CardNo: '',
  MemberId: '',
  StartDate: '', // 开始时间
  EndDate: '',
  PatientName: '',
  ReportType: '1', // 报告单类型 1检验报告 2检查报告
  Page: {
    PIndex: 0,
    PSize: 10
  },
  Data_1: {
    queryType: '1'
  }
});

onLoad((options: any) => {
  let queryType = options.queryType || '1';
  // 初始化当前选择
  if (queryData.Data_1) {
    queryData.Data_1.queryType = queryType;
  }
  queryData.ReportType = options.reportType || '1';
  pageType.value = queryType == '1' ? 'card' : 'hospital';
  // serviceType 暂时没用到，保留逻辑一致性
});

onShow(() => {
  currentUser.value = app.globalData.currentUser || uni.getStorageSync('currentUser') || {};
  main();
});

const main = async () => {
  // 权限校验逻辑
  // 原代码：if (await publicFn.isPageUserAuth(this.data.currentUser,this)) return
  // 如果无 memberId 则认为未登录/未授权
  if (!currentUser.value || !currentUser.value.memberId) {
     authorize.value = true;
     return;
  } else {
     authorize.value = false;
  }
  getReportList();
};

const setScreenData = (e: any) => {
  // 原代码：this.setData(e.detail)
  // 这里假设 e 是包含 screen 属性的对象，或者是直接更新 screen
  // 按照 screening 组件通常的行为，可能传回的是 screen 对象
  // 但原代码 this.setData(e.detail) 意味着 e.detail 可能包含 screen 字段
  if (e && e.screen) {
    Object.assign(screen, e.screen);
  } else if (e) {
      // 尝试合并
      Object.assign(screen, e);
  }
};

const resetScreen = (e: any) => {
  let newScreen = common.deepCopy(e); // 假设 e 就是 screen 数据，原代码 e.detail
  Object.assign(screen, newScreen);
  getReportList();
};

const queryRecords = (e: any) => {
  reportList.value = [];
  getReportList();
};

const getReportList = async (pIndex = 0) => {
  let showNoDataFlag = true;
  let obj = {
    CardType: currentUser.value.cardType,
    CardNo: currentUser.value.cardNo,
    MemberId: currentUser.value.memberId,
    PatientName: currentUser.value.memberName,
    Store: {
      cardEncryptionStore: currentUser.value.encryptionStore || '',
      baseMemberEncryptionStore: currentUser.value.baseMemberEncryptionStore
    }
  };

  queryData.StartDate = screen.startDate;
  queryData.EndDate = screen.endDate;
  
  // 合并 obj 到 queryData
  let requestData = common.deepCopy(obj, queryData);
  requestData.Page.PIndex = pIndex;

  let resp = await getReportListApi(requestData);
  
  if (!common.isEmpty(resp)) {
    resp.sort((a: any, b: any) => {
      return new Date(common.iosTime(b.SubmissionTime)).getTime() - new Date(common.iosTime(a.SubmissionTime)).getTime();
    });
    reportList.value = resp;
    showNoDataFlag = false;
  } else {
      reportList.value = [];
  }
  
  showNoData.value = showNoDataFlag;
};

const deptClick = (item: any) => {
  let queryBean = JSON.stringify(item);
  let url = "";
  if (item.State != '1') {
    // 如果不是已发布的 不能点击
    return;
  }
  // 检验报告
  if (item.ReportType == '1') {
    url = `/pagesPatient/st1/business/report/inspectCheckReportDetails/inspectCheckReportDetails?queryBean=${queryBean}`;
  }
  // 检查
  if (item.ReportType == '2') {
    url = `/pagesPatient/st1/business/report/inspectTestReportDetails/inspectTestReportDetails?queryBean=${queryBean}`;
  }
  // 体检
  if (item.ReportType == '3') {
    url = `/pagesPatient/st1/business/report/examinationReport/examinationReport?queryBean=${queryBean}`;
  }
  
  if (url) {
      common.goToUrl(url);
  }
};

const navClick = (type: string) => {
  reportList.value = [];
  showNoData.value = true;
  queryData.ReportType = type;
  // noDataValue 计算属性可以直接在 template 处理，或者这里不用管
  getReportList();
};
</script>

<style scoped>
.container {
    height: 100vh;
    background-color: #f5f5f5;
}

.content {
    /* padding-bottom: 20upx; */
}

.userInfoTopFixe {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 100;
}

.public_inner_table {
  height: 110upx;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 30upx;
  color: rgba(85, 85, 85, 1);
  background-color: #fff;
}

.report_type_box {
  width: 70%;
  height: 106upx;
  display: flex; /* Added flex based on usage */
  justify-content: space-around;
  align-items: center; /* Typically needed */
}

.public_inner_table_item {
  font-size: 32upx;
  color: #666;
  /* padding-bottom: 10upx; */
  position: relative;
  height: 100%;
  display: flex;
  align-items: center;
}

.public_inner_table_item_active {
  font-size: 32upx;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: var(--dominantColor) !important;
}

.public_inner_table_item_active::before {
  content: '';
  position: absolute;
  width: 36upx;
  height: 6upx;
  border-radius: 3upx;
  bottom: 18upx; /* Changed from top to bottom for better positioning usually, matching original approximately */
  left: 0;
  right: 0;
  margin: 0 auto;
  background-color: var(--dominantColor);
  box-shadow: 0px 8px 12px 0px var(--dominantColor);
}

/* Adjust top based on original css logic but using upx */
/* Original: top: 18rpx; margin: 20rpx auto 0 auto; This seems weird for an underline. 
   Usually underlines are at bottom. 
   Let's stick to original relative logic if possible or safer standard.
   Original:
   top: 18rpx;
   margin: 20rpx auto 0 auto;
   If parent height is 106rpx, 18+20 = 38rpx from top. That's top aligned?
   Let's trust the original css values but converted.
*/

.content_inner{
  margin-top: 300upx; /* Adjust based on fixed header height */
  padding-bottom: 20upx;
}

/* 暂无数据 */
.public_list{
  width: 100%;
  background: white;
  padding-left: 30upx;
  box-sizing: border-box;
  position: relative;
  z-index: 1; /* Changed from -1 to 1 to be visible/clickable */
}

.public_card{
  padding: 40upx 30upx 40upx 0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.public_user_name{
  font-size: 32upx;
  color: #333;
  margin-bottom: 10upx;
}

.public_user_time{
  font-size: 24upx;
  color: #999;
}

.border_bottom {
  position: relative;
  z-index: 10;
}

.border_bottom::after {
  content: " ";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  border-top: 1px solid #e6e6e6;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}

.noData {
  margin-top: 260upx;
}

.public_right_img{
  width: 30upx; /* Added width/height for image */
  height: 30upx;
  /* right: 30rpx;  Removed absolute positioning if flex is used correctly */
}

.state_tip{
  margin-right: 22upx;
}

.colorRed {
    color: red;
}

.displayFlexRow {
    display: flex;
    flex-direction: row;
}
</style>
