<template>
  <div class="home">
    <nav-bar></nav-bar>
    <div class="bj"></div>
    <div class="lxr" @click="handleCardSelect">
      <div class="lxrr" v-if="card && card.id">
        <h2>
          {{ card.name }}
          <p>卡号：{{ card.cardNo }}</p>
        </h2>
        <h3>
          <i class="van-icon van-icon-arrow van-cell__right-icon"></i>
        </h3>
      </div>
      <van-contact-card type="add" add-text="请选择就诊人" v-else />
    </div>
    <div v-if="showbox">
        <div class="header-section">
          <h3 class="list-title">住院信息</h3>
          <span class="filter-text" @click="showFilter = true">筛选</span>
        </div>
        
        <!-- 筛选弹窗 -->
        <van-popup v-model="showFilter" position="bottom" :style="{ height: '50%' }">
          <div class="filter-popup">
            <div class="filter-header">
              <h4>筛选条件</h4>
              <van-icon name="cross" @click="showFilter = false" class="close-icon" />
            </div>
            <div class="filter-content">
              <div class="filter-item">
                <span class="filter-label">住院状态：</span>
                <van-radio-group v-model="filterState">
                  <van-radio name="">全部</van-radio>
                  <van-radio name="hospitalized">住院中</van-radio>
                  <van-radio name="discharged">已出院</van-radio>
                </van-radio-group>
              </div>
              <div class="filter-item">
                <span class="filter-label">住院病区：</span>
                <van-dropdown-menu>
                  <van-dropdown-item v-model="filterDepartment" :options="departmentOptions" placeholder="全部" />
                </van-dropdown-menu>
              </div>
              <div class="filter-item">
                <span class="filter-label">住院时间范围：</span>
                <van-radio-group v-model="filterTimeRange">
                  <van-radio name="">全部</van-radio>
                  <van-radio name="7">近7天</van-radio>
                  <van-radio name="30">近30天</van-radio>
                  <van-radio name="90">近90天</van-radio>
                </van-radio-group>
              </div>
            </div>
            <div class="filter-footer">
              <van-button type="default" @click="resetFilter" class="reset-button">重置</van-button>
              <van-button type="primary" @click="applyFilter" class="apply-button">确认筛选</van-button>
            </div>
          </div>
        </van-popup>
      <div class="hospitalization-list">
        <div v-for="(item, index) in filteredList" :key="index" class="hospitalization-item" @click="navigateToDetail(item)">
          <div class="item-header">
            <h4>{{ item.SECTIONTYPE }}</h4>
            <span :class="['status-tag', item.HOSSTATE == '2' ? 'discharged' : 'hospitalized']">
              {{ item.HOSSTATE == '2' ? '出院' : '住院' }}
            </span>
          </div>
          <div class="item-content">
            <div class="info-row">
              <span class="info-label">入院时间：</span>
              <span class="info-value">{{ item.HOSDATE }}</span>
            </div>
             <!-- <div class="info-row">
              <span class="info-label">出院时间：</span>
              <span class="info-value">{{ item.OUTHOSDATE }}</span>
            </div> -->
            <div class="info-row last-row">
              <div class="left-content">
                <span class="info-label">住院编号：</span>
                <span class="info-value">{{ item.INHOSNUM }}-{{ item.ZYCS }}</span>
              </div>
              <div class="right-content">
                <span class="info-value">住院{{ item.hospitalDays }}天</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <van-empty description="住院处暂无该患者信息" v-else style="padding-top:90px" />
    <van-action-sheet
  v-model="showPatientSelector"
  title="请选择使用的患者ID"
  :actions="patientActions"
  @select="onPatientSelect"
  cancel-text="取消"
  @cancel="showPatientSelector = false"
/>
  </div>
</template>

<script>
import {
  apiUserCardList,
  apiInHosPatientInfoQuery,
  getUserCategory
} from "@/request/api.js";
import Vue from "vue";
import { ActionSheet } from "vant";

Vue.use(ActionSheet);
export default {
  mounted() {
    this.title = this.$route.meta.title;
  },
  computed: {
  patientActions() {
    return this.patientIds.map(id => ({ name: `患者ID: ${id}`, id }));
  }
},
  data() {
    return {
      title: "",
      card: {},
      showbox: false,
      zyinfo: {},
      hospitalizationList: [], // 原始住院记录列表
      filteredList: [], // 筛选后的住院记录列表
      patientIds: [],
      patientId: "",
      showPatientSelector: false, // 控制是否显示选择弹窗
      showFilter: false, // 控制是否显示筛选弹窗
      filterState: "", // 筛选状态：空-全部，hospitalized-住院，discharged-出院
      filterDepartment: "", // 筛选病区
      filterTimeRange: "", // 筛选时间范围：空-全部，7-近7天，30-近30天，90-近90天
      departmentOptions: [], // 病区选项
    };
  },
  created() {
    this.card = JSON.parse(sessionStorage.getItem("card"));
    if (this.card) {
      this.getZYInfo();
      return;
    }
    apiUserCardList({ isYes: 0 }).then((res) => {
      this.card = res.data[0];
      this.getZYInfo();
    });
  },
  methods: {
    onPatientSelect(action) {
    this.patientId = action.id;
    this.showPatientSelector = false;
    console.log("选中的 patientId:", this.patientId);
    // 如果需要根据 patientId 做其他查询，可在这里调用
    let formData2 = {
        QueryCode: this.patientId,
        QueryType: 2,
      };
      this.apiInHosPatientInfoQuery(formData2);
  },
  apiInHosPatientInfoQuery(formData) { 
    apiInHosPatientInfoQuery(formData).then((res) => {
        console.log(res);
        let jsonObj = this.$x2js.xml2js(res.data);
        console.log(jsonObj);
        let jsonObj2 = this.$x2js.xml2js(
          jsonObj.Envelope.Body.MOP_InHosPatientInfoQueryResponse
            .MOP_InHosPatientInfoQueryResult
        );
        console.log(jsonObj2);
        let dataRows = jsonObj2.response.data.data_row;
        if (jsonObj2.response.returnresult.returncode == "1") {
          
          this.hospitalizationList = [];
          
          if (Array.isArray(dataRows)) {
            // 处理数组形式的数据
            for (var i = 0; i < dataRows.length; i++) {
              let item = dataRows[i];
              let hospitalizationItem = {
                ADDRESS: item.ADDRESS,
                BEDNO: item.BEDNO,
                BIRTHDAY: item.BIRTHDAY,
                DEPARTCODE: item.DEPARTCODE,
                DEPTNAME: item.DEPTNAME,
                HOSBALANCE: item.HOSBALANCE,
                HOSDATE: item.HOSDATE,
                HOSNATURE: item.HOSNATURE,
                HOSSTATE: item.HOSSTATE,
                IDCARDNO: item.IDCARDNO,
                IDTYPE: item.IDTYPE,
                INHOSNUM: item.INHOSNUM,
                INHOSPATIENTID: item.INHOSPATIENTID,
                OUTHOSDATE: item.OUTHOSDATE,
                PATIENTNAME: item.PATIENTNAME,
                PATIENTSEX: item.PATIENTSEX,
                PATIENTSOURCE: item.PATIENTSOURCE,
                PHONENUM: item.PHONENUM,
                SECTIONTYPE: item.SECTIONTYPE || item.DEPTNAME,
                ZYCS: item.ZYCS,
                hospitalDays: this.calculateHospitalDays(item.HOSDATE, item.OUTHOSDATE, item.HOSSTATE)
              };
              this.hospitalizationList.push(hospitalizationItem);
            }
          } else {
            // 处理单个对象形式的数据
            let item = dataRows;
            let hospitalizationItem = {
              ADDRESS: item.ADDRESS,
              BEDNO: item.BEDNO,
              BIRTHDAY: item.BIRTHDAY,
              DEPARTCODE: item.DEPARTCODE,
              DEPTNAME: item.DEPTNAME,
              HOSBALANCE: item.HOSBALANCE,
              HOSDATE: item.HOSDATE,
              HOSNATURE: item.HOSNATURE,
              HOSSTATE: item.HOSSTATE,
              IDCARDNO: item.IDCARDNO,
              IDTYPE: item.IDTYPE,
              INHOSNUM: item.INHOSNUM,
              INHOSPATIENTID: item.INHOSPATIENTID,
              OUTHOSDATE: item.OUTHOSDATE,
              PATIENTNAME: item.PATIENTNAME,
              PATIENTSEX: item.PATIENTSEX,
              PATIENTSOURCE: item.PATIENTSOURCE,
              PHONENUM: item.PHONENUM,
              SECTIONTYPE: item.SECTIONTYPE || item.DEPTNAME,
              ZYCS: item.ZYCS,
              hospitalDays: this.calculateHospitalDays(item.HOSDATE, item.OUTHOSDATE, item.HOSSTATE)
            };
            this.hospitalizationList.push(hospitalizationItem);
          }
          
          // 设置患者基本信息（使用第一条记录的数据）
          if (this.hospitalizationList.length > 0) {
            let firstItem = this.hospitalizationList[0];
            this.zyinfo = {
              PATIENTNAME: firstItem.PATIENTNAME,
              PATIENTSEX: firstItem.PATIENTSEX
            };
            
            // 初始化筛选列表
            this.filteredList = [...this.hospitalizationList];
            
            // 提取病区列表
            this.extractDepartments();
            
            this.showbox = true;
          }
        }
      })
  },
  
  // 计算住院天数
  calculateHospitalDays(hosDate, outHosDate, hosState) {
    // 处理日期字符串，确保在 iOS 上兼容
    let startDate = this.parseDate(hosDate);
    let endDate;
    
    if (outHosDate && hosState == '2') {
      // 已出院，使用出院日期
      endDate = this.parseDate(outHosDate);
    } else {
      // 未出院，使用今天日期
      endDate = new Date();
    }
    
    // 计算天数差
    let timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
    let dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
    
    return dayDiff;
  },
  
  // 解析日期字符串，确保在 iOS 上兼容
  parseDate(dateString) {
    if (!dateString) return new Date();
    // 将 "2025-07-17 11:59:05" 格式转换为 "2025-07-17T11:59:05" 格式，确保 iOS 兼容
    const isoDateString = dateString.replace(' ', 'T');
    return new Date(isoDateString);
  },
    getZYInfo() {
      let _this = this;
      console.log(_this.card);
      let formData = {
        queryCode: _this.card.idNo,
        queryType: 7,
      };
      getUserCategory(formData).then((res) => {
        console.log(res);
        let jsonObj = this.$x2js.xml2js(res.data);
        let jsonObj2 = jsonObj.Envelope.Body.MOP_OutpPatInfoQueryResponse
          .request;
        console.log(jsonObj2);
        if (Array.isArray(jsonObj2.request.data)) {
          // 如果是数组，遍历获取每个元素的 PatientId
          this.patientIds = jsonObj2.request.data.map(item => item.PatientId);
        } else {
          // 如果不是数组，说明只有一个对象
          this.patientIds = [jsonObj2.request.data.PatientId];
        }
        if (this.patientIds.length === 1) {
          this.patientId = this.patientIds[0];
           let formData2 = {
        QueryCode: this.patientId,
        QueryType: 2,
      };
      this.apiInHosPatientInfoQuery(formData2);
        } else if (this.patientIds.length > 1) {
          this.showPatientSelector = true; // 弹出选择器
        }
        console.log(this.patientIds);
      });
    },
    handleCardSelect() {
      this.$router.push({ path: "/Member_jzr", query: { f: 1 } });
    },
    
    // 跳转到住院详情页面
    navigateToDetail(item) {
      // 使用 sessionStorage 存储住院记录数据，避免通过地址栏传递大量参数
      sessionStorage.setItem('hospitalizationItem', JSON.stringify(item));
      // 跳转到住院详情页面
      this.$router.push({ path: "/ZYdetail" });
    },
    
    // 提取病区列表
    extractDepartments() {
      const departments = new Set();
      this.hospitalizationList.forEach(item => {
        if (item.SECTIONTYPE) {
          departments.add(item.SECTIONTYPE);
        }
      });
      // 生成符合 van-dropdown-item 要求的 options 格式
      this.departmentOptions = Array.from(departments).map(dept => ({
        value: dept,
        text: dept
      }));
    },
    
    
    
    // 应用筛选条件
    applyFilter() {
      this.filteredList = this.hospitalizationList.filter(item => {
        // 筛选住院状态
        if (this.filterState) {
          if (this.filterState === 'hospitalized' && item.HOSSTATE === '2') {
            return false;
          }
          if (this.filterState === 'discharged' && item.HOSSTATE !== '2') {
            return false;
          }
        }
        
        // 筛选病区
        if (this.filterDepartment && item.SECTIONTYPE !== this.filterDepartment) {
          return false;
        }
        
        // 筛选时间范围
        if (this.filterTimeRange) {
          const days = parseInt(this.filterTimeRange);
          const cutoffDate = new Date();
          cutoffDate.setDate(cutoffDate.getDate() - days);
          const hosDate = this.parseDate(item.HOSDATE);
          if (hosDate < cutoffDate) {
            return false;
          }
        }
        
        return true;
      });
      
      this.showFilter = false;
    },
    
    // 重置筛选条件
    resetFilter() {
      this.filterState = '';
      this.filterDepartment = '';
      this.filterTimeRange = '';
      this.filteredList = [...this.hospitalizationList];
      this.showFilter = false;
    }
  },
}
</script>

<style scoped lang="scss">
// 背景样式
.bj {
  background: #f5f5f5;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  z-index: -2;
}

// 就诊人卡片样式
.lxr {
  .van-cell--center {
    border-radius: 15px;
    padding: 20px;
    background: url(../assets/lxrbj.png) no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    color: #fff;

    .van-cell__value--alone {
      color: #fff;
    }

    .van-cell__right-icon {
      color: #fff;
    }
  }

  .van-contact-card::before {
    background: none;
  }

  ::v-deep .van-contact-card--add .van-cell__left-icon {
    color: #fff;
    opacity: 0.6;
  }

  .lxrr {
    border-radius: 15px;
    padding: 20px;
    background: url(../assets/lxrbj.png) no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    color: #fff;
    padding: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    h2 {
      font-size: 32px;

      p {
        font-size: 28px;
        padding-top: 10px;
      }
    }

    h3 .van-cell__right-icon {
      color: #fff;
    }
  }
}

// 通用文字颜色
.colblack {
  color: #000;
  font-weight: 600;
}

.colgray {
  color: #aaa;
}

/* 头部标题和筛选按钮布局 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding: 0 5px;
}

.list-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.filter-text {
  font-size: 24px;
  color: #2196F3;
  cursor: pointer;
  padding: 5px;
}

// ---------------------- 优化后的筛选弹窗样式 ----------------------
::v-deep .van-popup {
  &.van-popup--bottom {
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
}

.filter-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
}

// 筛选弹窗头部
.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f5f7fa;

  h4 {
    font-size: 30px;
    font-weight: 700;
    color: #1a1a1a;
    margin: 0;
  }

  .close-icon {
    font-size: 32px;
    color: #999999;
    padding: 8px;
    border-radius: 50%;
    transition: all 0.2s ease;

    &:active {
      background-color: #f5f7fa;
      color: #666666;
    }
  }
}

// 筛选弹窗内容区域
.filter-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: #fafbfc;

  // 单个筛选项容器
  .filter-item {
    margin-bottom: 32px;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);

    &:last-child {
      margin-bottom: 0;
    }

    // 筛选项标签
    .filter-label {
      font-size: 26px;
      font-weight: 600;
      color: #333333;
      margin-bottom: 16px;
      display: block;
      padding-left: 4px;
    }
  }

  // 单选框组样式（住院状态/时间范围）
  ::v-deep .van-radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    padding: 4px 0;

    .van-radio {
      flex: 1;
      min-width: 120px;
      height: 80px;
      margin: 0;

      .van-radio__wrapper {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2px solid #e5e7eb;
        border-radius: 12px;
        background-color: #ffffff;
        transition: all 0.2s ease;
        padding: 0;

        // 单选框圆点隐藏（用背景色区分选中状态，更直观）
        .van-radio__input {
          display: none;
        }

        // 单选框文字
        .van-radio__label {
          font-size: 24px;
          color: #666666;
          margin: 0;
          transition: all 0.2s ease;
        }
      }

      // 选中状态样式
      &.van-radio--checked {
        .van-radio__wrapper {
          border-color: #2196F3;
          background-color: #E3F2FD;
        }

        .van-radio__label {
          color: #2196F3;
          font-weight: 600;
        }
      }

      // 触摸反馈
      &:active {
        .van-radio__wrapper {
          opacity: 0.8;
          transform: scale(0.98);
        }
      }
    }
  }

  // 病区选择器样式
  .department-select-wrap {
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    background-color: #ffffff;
    transition: all 0.2s ease;

    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }

    .department-value {
      font-size: 24px;
      color: #333333;
    }

    .department-icon {
      font-size: 24px;
      color: #999999;
    }
  }

  // 病区picker样式优化（穿透vant）
  ::v-deep .department-picker {
    .van-picker__toolbar {
      background-color: #fafbfc;
      border-bottom: 1px solid #f5f7fa;

      .van-picker__cancel,
      .van-picker__confirm {
        font-size: 26px;
        font-weight: 600;
        color: #2196F3;
      }
    }

    .van-picker__column {
      text-align: center;

      .van-picker__option {
        font-size: 26px;
        color: #333333;
      }
    }
  }
}

// 筛选弹窗底部按钮
.filter-footer {
  padding: 20px 24px;
  background-color: #ffffff;
  display: flex;
  justify-content: space-between;
  gap: 16px;

  .reset-button,
  .apply-button {
    flex: 1;
    height: 88px;
    font-size: 28px;
    font-weight: 600;
    border-radius: 16px;
    border: none;
    transition: all 0.2s ease;

    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }
  }

  .reset-button {
    background-color: #f5f7fa;
    color: #666666;
    border: 2px solid #e5e7eb;

    &:hover {
      background-color: #eff1f5;
    }
  }

  .apply-button {
    background-color: #2196F3;
    color: #ffffff;

    &:hover {
      background-color: #1976D2;
    }
  }
}

/* 住院记录列表样式 */
.hospitalization-list {
  margin-top: 15px;
}

.hospitalization-item {
  background-color: #fff;
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 15px;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  h4 {
    font-size: .47rem;
    font-weight: 600;
    color: #333;
  }
}

/* 状态标签样式 */
.status-tag {
  font-size: .42rem;
  padding: 4px 12px;
  border-radius: 12px;
}

.status-tag.discharged {
  color: #4CAF50;
  background-color: #E8F5E9;
}

.status-tag.hospitalized {
  color: #2196F3;
  background-color: #E3F2FD;
}

/* 信息行样式 */
.item-content {
  .info-row {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: .38rem;
  }
  
  .info-label {
    color: #666;
    margin-right: 10px;
    min-width: 100px;
  }
  
  .info-value {
    color: #333;
    font-weight: 500;
  }
  
  .right-label {
    margin-left: 30px;
  }
}

/* 最后一行特殊处理 */
.item-content .info-row:last-child {
  justify-content: space-between;
}

/* 住院编号和住院天数布局 */
.info-row.last-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-content {
  display: flex;
  align-items: center;
}

.right-content {
  display: flex;
  align-items: center;
}
</style>