<template>
  <view class="container">
    <view class="content">
      <screening 
        class="screen" 
        @dateChange="dateChange" 
        @screenInfoChange="screenInfoChange" 
        :queryData="queryData" 
        showMemberList="cardAndName" 
        :showAllMember="false"
      ></screening>
      <view class="content_inner" v-if="!showNoData">
        <view class="public_con" v-for="(item, index) in list" :key="index" @click="itemClick(item)">
          <view class="public_con_nav border_bottom">
            <view class="public_con_nav_tit">
              {{memberName}}
            </view>
            <image class="public_line" src="https://zygzh.fyey.cn/uploadFile/staticresource/st1/green/static/images/icon/line.png"></image>
            <view class="public_con_nav_name">
              <text class="colorCustom">{{item.children[0].AppointmentStatus}}</text>
            </view>
          </view>
          <view class="public_info_list">
            <view class="public_info_item">
              <view class="public_info_tit">就诊人</view>
              <view class="public_info_val">{{memberName}}</view>
            </view>
            <view class="public_info_item" v-for="(child, childIndex) in item.children" :key="childIndex">
              <view class="public_info_tit">项目名称</view>
              <view class="public_info_val">{{child.LabName}}</view>
            </view>
            <view class="public_info_item">
              <view class="public_info_tit">开单时间</view>
              <view class="public_info_val">{{item.children[0].BillDate}}</view>
            </view>
            <view class="public_info_item">
              <view class="public_info_tit">就诊时间</view>
              <view class="public_info_val">{{item.children[0].AppointmentTime}}</view>
            </view>
            <view class="public_info_item">
              <view class="public_info_tit">预约详情</view>
              <view class="public_info_val showDetail" v-if="!item.showTip" @click.stop="showTipFn(index)">点击查看详情</view>
              <view class="public_info_val" v-else>{{item.FriendlyReminder}}</view>
            </view>
          </view>
          <view class="public_info_foot border_top">
            <view class="info_foot_item cancel_btn border" v-if="item.cancenBtn" @click.stop="cancelYjyy(item)">退号</view>
            <view 
              v-if="item.allowSignIn" 
              class="info_foot_item cancel_btn border" 
              :class="{'colorCustom': item.children[0].AppointmentStatus == '已预约'}" 
              @click.stop="jumpSignPage(item)"
            >在线签到</view>
          </view>
        </view>
      </view>
      <view v-else class="noData">
        <noData :value="noDataValue"></noData>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useOnLoad } from '@dcloudio/uni-app';
import { queryExamItemList, getMedicalReceipts, cancelAppoint } from '@/pagesPatient/service/otherService';
import { orderDetailLocal } from '@/pagesPatient/service/record/index';
import { request, handle } from '@kasite/uni-app-base';
import { common, menuClick } from '@/utils';
import { REQUEST_CONFIG } from '@/config/requestConfig';

const app = getApp();
const list = ref<any[]>([]);
const showNoData = ref(false);
const noDataValue = ref('暂无医技预约记录信息');
const screenInfo = ref({});
const memberName = ref('');
const cardNo = ref('');
const currentUser = ref<any>({});
const queryData = ref({
  beginDate: common.dateFormat(new Date(Date.now() - (30 * 24 * 60 * 60 * 1000))).formatYear, //开始时间
  endDate: common.newDay(), //结束时间 
  memberId: '',
  cardNo: '',
  cardType: ''
});

useOnLoad((options: any) => {
  if (app.globalData.logSuccess) {
    main(options);
  } else {
    app.loginReadyCallBack = () => main(options);
  }
});

const queryMemberCardList = async (cardType: string, isEncrypted: string) => {
  let resp = handle.promistHandleNew(await request.doPost(`${REQUEST_CONFIG.BASE_URL}wsgw/member/memberApi/QueryMemberCardList/callApiJSON.do`, {
    CardType: cardType,
    IsEncrypted: isEncrypted
  }));
  return handle.catchPromiseNew(resp, () => resp);
};

const main = async (options: any = {}) => {
  let queryUser = app.globalData.currentUser;
  if (options.orderId) {
    let cNo;
    let orderResp = await orderDetailLocal({ OrderId: options.orderId });
    if (!common.isEmpty(orderResp)) {
      cNo = orderResp[0].CardNo;
    }
    if (cNo) {
      let resp = await queryMemberCardList('1', '1');
      if (!common.isEmpty(resp)) {
        queryUser = resp.filter((item: any) => item.CardNo == cNo)[0] || resp[0];
      } else {
        common.showModal(`当前就诊卡不存在`, () => {
          uni.reLaunch({
            url: `/pages/st1/green/business/tabbar/homePage/homePage`,
          });
        });
        return;
      }
    } else {
      return;
    }
  } else if (options.cardNo) {
    let cNo = options.cardNo;
    let resp = await queryMemberCardList('1', '1');
    if (!common.isEmpty(resp)) {
      queryUser = resp.filter((item: any) => item.CardNo == cNo)[0] || resp[0];
    } else {
      common.showModal(`当前就诊卡不存在`, () => {
        uni.reLaunch({
          url: `/pages/st1/green/business/tabbar/homePage/homePage`,
        });
      });
      return;
    }
  }

  let user = options.userInfo ? JSON.parse(options.userInfo) : queryUser || {};
  // Assuming yjyyRecord_screening is in app.globalData.config.pageConfiguration
  let sInfo = common.deepCopy(app.globalData.config?.pageConfiguration?.yjyyRecord_screening?.value || [], []);
  
  queryData.value.memberId = user.MemberId || '';
  queryData.value.cardNo = user.CardNo || '';
  queryData.value.cardType = user.CardType || '';
  cardNo.value = user.CardNo || '';
  currentUser.value = user;
  screenInfo.value = sInfo;
  memberName.value = user.MemberName;

  queryExamItemListFn();
};

const dateChange = (e: any) => {
  let detail = e; // component emits detail directly? or e.detail? usually in vue3 emit payload is the value.
  // Assuming screening component emits {type: 'beginDate', value: '...'}
  // But legacy code: this.setData({ [detail.type]: detail.value })
  // We need to check how screening component emits. 
  // Assuming it matches legacy `e.detail`.
  if (detail.type) {
     // @ts-ignore
    queryData.value[detail.type] = detail.value;
  }
  queryExamItemListFn();
};

const screenInfoChange = async (e: any) => {
  let qData = e.queryData;
  let obj = {
    memberId: qData.memberId,
    cardNo: qData.cardNo,
    cardType: qData.cardType
  };
  queryData.value = { ...queryData.value, ...obj };
  cardNo.value = qData.cardNo;
  await queryExamItemListFn();
  memberName.value = qData.memberName;
};

const queryExamItemListFn = async () => {
  let resp = await queryExamItemList(queryData.value) || [];
  resp = resp.filter((item: any) => item.IsBook == '0');
  
  const inspectDeptIds = app.globalData.config?.inspectDeptIds?.split(",") || [];
  resp.map((item: any) => {
    item.showTip = false;
    item.allowSignIn = inspectDeptIds.includes(item.ExamDept);
  });
  
  let newResp = recombination(resp);
  newResp.forEach((item: any, index: number) => {
    item.cancenBtn = [];
    if (common.isNotEmpty(item.children)) {
      let code = ['35512', '42448', '42449', '42450'];
      code.forEach((codeItem) => {
        let found = item.children.filter((childitem: any) => {
          return childitem.LabCode == codeItem;
        });
        if(found && found.length > 0) {
            item.cancenBtn = item.cancenBtn.concat(found);
        }
      });
    }
    // Legacy logic: item.cancenBtn = common.isEmpty(item.cancenBtn)
    // Wait, if it's empty, it returns true? So if cancelBtn is empty (no match), it shows button?
    // "item.cancenBtn = common.isEmpty(item.cancenBtn)" -> true if empty.
    // So if LabCode is NOT in the list, show cancel button?
    // Let's re-read legacy:
    // item.cancenBtn = item.children.filter(...)
    // item.cancenBtn = common.isEmpty(item.cancenBtn)
    // If empty -> true.
    // wx:if="{{item.cancenBtn}}" -> show if true.
    // So if code matches, it is NOT empty, so isEmpty is false, so button hidden.
    // So button is HIDDEN for these codes. Shown for others.
    item.cancenBtn = common.isEmpty(item.cancenBtn);

    const mainAllowSignIn = !item.children.map((child: any) => child.allowSignIn).includes(false);
    item.allowSignIn = mainAllowSignIn;
  });

  list.value = newResp;
  showNoData.value = common.isEmpty(resp);
};

const itemClick = (item: any) => {
  let hisKeys = "";
  let totalLength = item.children.length;
  item.children.map((child: any, index: number) => {
    hisKeys += child.HisKey;
    if (index + 1 != totalLength) {
      hisKeys += "|";
    }
  });
  let queryBean = JSON.stringify({
    hisKey: hisKeys,
    cardNo: cardNo.value
  });
  common.navigateTo(`/pages/st1/green/business/pay/payState/payState?pageType=yjyy&queryBean=${queryBean}`);
};

const recombination = (l: any[]) => {
  let newList: any[] = [];
  l.forEach(item => {
    let newItem = newList.find((i) => i.GroupId == item.GroupId);
    if (!newItem) {
      newList.push({
        GroupId: item.GroupId,
        children: [item]
      });
    } else {
      newItem.children.push(item);
    }
  });
  return newList;
};

// Regex helper to extract value from XML-like string
const getXmlValue = (xml: string, tag: string) => {
  // Match <tag>...</tag> or <tag attr="...">...</tag>, support multiline content
  const match = xml.match(new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`));
  return match ? match[1] : '';
};

const showTipFn = async (index: number) => {
  let item = list.value[index];
  let orderType = 1;
  let groupStore = "";
  let totalLength = item.children.length;
  let receipt = "";

  if (totalLength == 1) {
    groupStore = item.children[0].Store;
    receipt = item.children[0].HisKey;
  } else if (totalLength > 1) {
    orderType = 2;
    item.children.map((child: any, idx: number) => {
      let store = child.Store;
      // Use regex to parse
      let hisKey = getXmlValue(store, "HisKey");
      let groupId = getXmlValue(store, "GroupID");
      let groupSort = getXmlValue(store, "GroupSort");
      let orderId = getXmlValue(store, "OrderID");
      let printAppointmentId = getXmlValue(store, "PrintAppointmentID");
      let labCode = getXmlValue(store, "LabCode");
      let inspectionItemId = getXmlValue(store, "InspectionItemID");
      let patientId = getXmlValue(store, "PatientId");
      let appointmentFlag = getXmlValue(store, "AppointmentFlag");
      let serialNo = getXmlValue(store, "SerialNo");

      let receiptItems = `${groupId}|${groupSort}|${orderId}|${printAppointmentId}|${labCode}|${inspectionItemId}|${patientId}|${appointmentFlag}|${serialNo}`;
      
      if (idx + 1 != totalLength) {
        receiptItems += ";";
        hisKey += "_";
      }
      groupStore += receiptItems;
      receipt += hisKey;
    });
  }

  let qData = {
    Store: groupStore,
    OrderType: orderType,
    HisKey: receipt
  };

  let resp = await getMedicalReceipts(qData);
  if (resp) {
    uni.previewImage({
      urls: [resp[0].Url]
    });
  }
};

const cancelYjyy = (item: any) => {
  common.showModal(`确认取消预约?`, async () => {
    let hisKeys = "";
    let labNames = "";
    let totalLength = item.children.length;
    item.children.map((child: any, index: number) => {
      hisKeys += child.HisKey;
      labNames += child.LabName;
      if (index + 1 != totalLength) {
        hisKeys += "|";
        labNames += ",";
      }
    });
    let qData = {
      CardNo: currentUser.value.CardNo,
      CardType: currentUser.value.CardType,
      HisKey: hisKeys,
      LabName: labNames
    };
    let resp = await cancelAppoint(qData);
    if (!common.isEmpty(resp)) {
      common.showModal('取消成功', () => {
        main();
      });
    }
  }, '取消');
};

const jumpSignPage = (item: any) => {
  if (item.children[0].AppointmentStatus != "已预约") {
    common.showModal("预约已经退号或已签到");
    return;
  }
  let menuList = app.globalData.menuList;
  let targetItem = item; // Default
  
  // Try to find "检查签到" menu item
  if (menuList) {
    menuList.forEach((mItem: any) => {
      if (common.isNotEmpty(mItem.Children)) {
        mItem.Children.forEach((childItem: any) => {
          if (common.isNotEmpty(childItem.Children)) {
            childItem.Children.forEach((sunItem: any) => {
              if (sunItem.MenuName == "检查签到") {
                targetItem = sunItem;
              }
            });
          }
        });
      }
    });
  }
  
  // The original code passed `e` which had `dataset.item`.
  // Here we pass `item` directly to logic, but `menuClick` expects event or item.
  // `menuClick` signature: (e, _this, skipWay)
  // Inside `menuClick`: `let item = e.currentTarget ? e.currentTarget.dataset.item : e;`
  // So we can pass `targetItem` as first arg.
  menuClick(targetItem, null);
};
</script>

<style lang="scss">
.public_con{margin: 30upx}

.info_foot_item {
  width: 160upx;
  height: 56upx;
  font-size:30upx;
  font-family:Source Han Sans CN;
  font-weight:400;
  background: rgba(255, 255, 255, 1);
  border-radius: 28upx;
  text-align: center;
  line-height: 56upx;
  /* position: absolute; */
}

.public_info_foot {
  justify-content: flex-end;
}

.public_info_foot .cancel_btn{
  right: 31upx;
  color:rgba(166,166,166,1);
  margin-left: 30upx;
}
.cancel{
  color: #999;
}
.showDetail{
  color: #00a2fe;
}
.noData {
    width: 100%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
</style>
