<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="cellbody">
        <van-row>
          <van-col span="5" class="colgray">姓名：
          </van-col>
          <van-col span="6" class="colblack">{{ zyinfo.PATIENTNAME }}
          </van-col>
          <van-col span="5" class="colgray">住院号：
          </van-col>
          <van-col span="8" class="colblack">{{
            zyinfo.INHOSNUM
          }}
          </van-col>
        </van-row>
        <van-row>
          <van-col span="5" class="colgray">性别：
          </van-col>
          <van-col span="6" class="colblack">{{ zyinfo.PATIENTSEX }}
          </van-col>
          <van-col span="5" class="colgray">病区：
          </van-col>
          <van-col span="8" class="colblack">{{
            zyinfo.DEPTNAME
          }}
          </van-col>
        </van-row>
        <van-row>
          <van-col span="5" class="colgray">生日：
          </van-col>
          <van-col span="6" class="colblack">{{ zyinfo.BIRTHDAY }}
          </van-col>
          <van-col span="5" class="colgray">床位：
          </van-col>
          <van-col span="6" class="colblack">{{ zyinfo.BEDNO }}
          </van-col>
        </van-row>
        <van-row>
          <van-col span="5" class="colgray">账户余额：
          </van-col>
          <van-col span="8" class="colblack">{{ zyinfo.HOSBALANCE }}元
          </van-col>
        </van-row>
      </div>
      <div class="time_box">
        <div class="bt">
          <img class="img" src="../assets/label.png" />选择时间范围
        </div>

        <van-cell title="开始时间" :value="startdate" @click="startshow = true" />
        <van-cell title="结束时间" :value="enddate" @click="endshow = true" />
        <van-calendar v-model="startshow" :min-date="new Date(2020, 0, 1)" @confirm="onstartConfirm"
          :show-confirm="false" color="#2e82ef" />
        <van-calendar v-model="endshow" :min-date="new Date(2020, 0, 1)" @confirm="onendConfirm" :show-confirm="false"
          color="#2e82ef" />
      </div>
      <div :class="btnclass">
        <div @click="onConfirm">查询</div>
      </div>
    </div>
    <van-empty description="住院处暂无该患者信息" v-else style="padding-top:90px" />
    <van-popup v-model="resultshow" @click="resultshow = false" class="wrapper">
      <div class="block" @click.stop>
        <div class="listbt">{{ startdate }}至{{ enddate }}清单</div>
        <div class="listbody">
          <div class="scrollable-content">
            <van-row>
              <van-col span="9" class="colblack">项目名称</van-col>
              <van-col span="3" class="colblack">类型</van-col>
              <van-col span="3" class="colblack">单价</van-col>
              <van-col span="3" class="colblack">数量</van-col>
              <van-col span="3" class="colblack">单位</van-col>
              <van-col span="3" class="colblack">总价</van-col>
            </van-row>
            <van-row v-for="item in List" :key="item">
              <van-col span="9" class="colgray">{{ item.ITEMNAME }}</van-col>
              <van-col span="3" class="colgray">{{ item.ACCTYPE }}</van-col>
              <van-col span="3" class="colgray">{{ item.ITEMPRICE }}</van-col>
              <van-col span="3" class="colgray">{{ item.ITEMCOUNT }}</van-col>
              <van-col span="3" class="colgray">{{ item.ITEMUNIT }}</van-col>
              <van-col span="3" class="colgray">{{ item.ITEMAMOUNT }}</van-col>
            </van-row>
          </div>

          <van-row class="fixed-total">
            <van-col offset="14" span="10" class="colblack">合计：{{ money }}元
            </van-col>
          </van-row>

        </div>
      </div>
    </van-popup>
    <van-action-sheet
  v-model="showPatientSelector"
  title="请选择使用的患者ID"
  :actions="patientActions"
  @select="onPatientSelect"
  cancel-text="取消"
  @cancel="showPatientSelector = false"
/>
  </div>
</template>

<script>
import {
  apiUserCardList,
  apiInHosPatientInfoQuery,
  apiInHosFeeDetailQuery,
  apiInHosFeeMasterQuery,
  getUserCategory
} from "@/request/api.js";
import Vue from "vue";
import { Toast, Empty, Calendar, RadioGroup, Radio, popup,ActionSheet } from "vant";

Vue.use(ActionSheet);
Vue.use(Calendar);
Vue.use(Radio);
Vue.use(RadioGroup);
export default {
  mounted() {
    this.title = this.$route.meta.title;
  },
  computed: {
  patientActions() {
    return this.patientIds.map(id => ({ name: `患者ID: ${id}`, id }));
  }
},
  data() {
    return {
      title: "",
      card: {},
      activeSelect: 0,
      list: [],
      date: "",
      startshow: false,
      endshow: false, // 新增：结束时间显示控制
      startdate: "",
      enddate: "", // 新增：结束时间值
      radio: "1",
      btnclass: "btn",
      showbox: false,
      zyinfo: {},
      INHOSNUM: "",
      resultshow: false,
      money: 0,
      patientIds: [],
      patientId: "",
      showPatientSelector: false, // 控制是否显示选择弹窗
    };
  },
  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") {
          
          if (Array.isArray(dataRows)) {
            for (var i = 0; i < dataRows.length; i++) {
              if (dataRows[i].HOSSTATE == "0" || dataRows[i].HOSSTATE == "") {
                this.INHOSNUM = dataRows[i].INHOSNUM;
                let data = {
                  INHOSNUM: dataRows[i].INHOSNUM,
                  PATIENTNAME: dataRows[i].PATIENTNAME,
                  PATIENTSEX: dataRows[i].PATIENTSEX,
                  BIRTHDAY: dataRows[i].BIRTHDAY,
                  PHONENUM: dataRows[i].PHONENUM,
                  ADDRESS: dataRows[i].ADDRESS,
                  IDCARDNO: dataRows[i].IDCARDNO,
                  DEPARTCODE: dataRows[i].DEPARTCODE,
                  DEPTNAME: dataRows[i].DEPTNAME,
                  BEDNO: dataRows[i].BEDNO,
                  HOSDATE: dataRows[i].HOSDATE,
                  OUTHOSDATE: dataRows[i].OUTHOSDATE,
                  HOSSTATE: dataRows[i].HOSSTATE,
                  HOSBALANCE: dataRows[i].HOSBALANCE,
                  PATIENTSOURCE: dataRows[i].PATIENTSOURCE,
                }
                this.zyinfo = data
              }
            }
          } else {
            if (dataRows.HOSSTATE == "0" || dataRows.HOSSTATE == "") {
              this.INHOSNUM = dataRows.INHOSNUM;
              let data = {
                INHOSNUM: dataRows.INHOSNUM,
                PATIENTNAME: dataRows.PATIENTNAME,
                PATIENTSEX: dataRows.PATIENTSEX,
                BIRTHDAY: dataRows.BIRTHDAY,
                PHONENUM: dataRows.PHONENUM,
                ADDRESS: dataRows.ADDRESS,
                IDCARDNO: dataRows.IDCARDNO,
                DEPARTCODE: dataRows.DEPARTCODE,
                DEPTNAME: dataRows.DEPTNAME,
                BEDNO: dataRows.BEDNO,
                HOSDATE: dataRows.HOSDATE,
                OUTHOSDATE: dataRows.OUTHOSDATE,
                HOSSTATE: dataRows.HOSSTATE,
                HOSBALANCE: dataRows.HOSBALANCE,
                PATIENTSOURCE: dataRows.PATIENTSOURCE,
              }
              this.zyinfo = data
            }
          }
          if (this.INHOSNUM != "") {
            this.showbox = true;
          }
        }
      })
  },
    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);
        // console.log(jsonObj);
        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);
      });
    },
    formatDate(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      month = month > 9 ? month : "0" + month;
      let day = date.getDate();
      day = day > 9 ? day : "0" + day;
      return year + "-" + month + "-" + day;
    }
    ,
    onstartConfirm(date) {
      this.startshow = false;
      this.startdate = this.formatDate(date);
    }
    ,
    onendConfirm(date) {
      this.endshow = false;
      this.enddate = this.formatDate(date);
    }
    ,
    onConfirm() {
      // 验证时间范围
      if (!this.startdate || !this.enddate) {
        Toast("请选择开始和结束时间");
        return;
      }

      // 检查结束时间是否早于开始时间
      if (new Date(this.enddate) < new Date(this.startdate)) {
        Toast("结束时间不能早于开始时间");
        return;
      }

      let that = this;
      let formData = {
        QueryNum: that.INHOSNUM,
        QueryType: "1",
        SearchType: '1',
        StartTime: that.startdate,
        EndTime: that.enddate, // 新增：加入结束时间
      };

      apiInHosFeeDetailQuery(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_InHosFeeDetailQueryResponse
            .MOP_InHosFeeDetailQueryResult
        );
        console.log(jsonObj2);

        // 检查数据是否存在
        if (jsonObj2 && jsonObj2.response && jsonObj2.response.data && jsonObj2.response.data.data_row && jsonObj2.response.data.data_row.length > 0) {
          that.List = jsonObj2.response.data.data_row;
          that.money = 0;
          for (let i = 0; i < jsonObj2.response.data.data_row.length; i++) {
            that.money = (parseFloat(that.money) + parseFloat(jsonObj2.response.data.data_row[i].ITEMAMOUNT)).toFixed(2);
          }
          that.resultshow = true;
        } else {
          // 数据为空的情况
          that.List = [];
          that.money = 0;
          that.resultshow = true;
          Toast("暂无该时间段收费详情信息");
        }
      })
        .catch(error => {
          console.error("查询费用明细失败", error);
          Toast("查询失败，请重试");
        });
    },
    handleCardSelect() {
      this.$router.push({ path: "/Member_jzr", query: { f: 1 } });
    }
    ,
  },
}
  ;
</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;
    }
  }
}

::v-deep .van-tabs__content {
  margin-top: 20px;
}

.time_box {
  margin-top: 10px;
  padding: 10px;
  height: 170px;
  border-radius: 14px;
  background-color: #fff;
}

.btn {
  //margin-top: 75px;
  //position: fixed;
  padding: 100px 30px;
  bottom: 0px;

  div {
    width: 690px;
    height: 68px;
    line-height: 68px;
    text-align: center;
    background: #166bcc;
    border-radius: 14px;
    display: block;
    margin: 0px auto;
    font-size: 32px;
    color: #ffffff;
  }
}

.btn1 {
  //margin-top: 75px;
  //position: fixed;
  padding: 100px 30px;
  bottom: 0px;

  div {
    width: 690px;
    height: 68px;
    line-height: 68px;
    text-align: center;
    background: #c4c4c4;
    border-radius: 14px;
    display: block;
    margin: 0px auto;
    font-size: 32px;
    color: #ffffff;
  }
}

.bt {
  font-size: 30px;
  color: #000;
  padding: 20px;
  background-color: #fff;
}

.img {
  height: 25px;
  padding: 0 10px;
}

.colblack {
  color: #000;
  font-weight: 600;
}

.colgray {
  color: #aaa;
}

.cellbody {
  margin-top: 10px;
  width: 100%;
  font-size: 30px;
  font-family: PingFang SC;
  background-color: #fff;
  border-radius: 15px;

  .van-row {
    padding: 20px 0;
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 95%;
  height: 80%;
  border-radius: 12px;
}

.block {
  width: 95%;
  height: 80%;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
}

.listbt {
  font-size: 36px;
  font-family: PingFang SC;
  font-weight: 800;
  color: #333333;
  text-align: center;
}

.listbody {
  margin-top: 50px;
  width: 100%;
  font-size: 30px;
  font-family: PingFang SC;
  background-color: #fff;
  border-radius: 15px;
  display: flex;
  flex-direction: column;
  height: calc(100% - 50px); // 留出标题高度

  .scrollable-content {
    overflow-y: auto;
    flex: 1;

    .van-row {
      padding: 10px 0;
    }
  }

  .fixed-total {
    flex-shrink: 0; // 防止压缩
    padding: 20px 0;
    border-top: 1px solid #eee;
    background-color: #fff;
  }
}
</style>
