<template>
  <view class="container">
    <view class="content" v-if="showCon">
      <view class="userInfoTopFixe">
        <userInfo page-type="1" :userInfo="currentUser" bgClass="bgLinGra"></userInfo>
      </view>
      <view class="content_inner">
        <block v-if="!showNoData">
          <view class="inner_list">
            <view class="public_con" v-for="(item, index) in list" :key="index">
              <view class="public_con_nav displayFlexBetween">
                <view class="public_con_nav_tit">
                  {{item.PrescTimeDiy}}
                </view>
                <view class="public_con_nav_name">
                  <text class="mr10">{{item.DoctorName}} </text>
                  <text>{{item.DeptName}}</text>
                </view>
              </view>
              <view class="public_con_info border_top">
                <view class="info_list" @click="getDetail(item, index)">
                  <view class="list_item" @click.stop="selectedOptions(item)">
                    <image class="list_circle" :src="isInclude(item) ? iconUrl.circle_active : iconUrl.circle"></image>
                    <view class="list_name">{{item.PrescType||item.ServiceName||item.ReceiptName}}</view>
                  </view>
                  <view class="list_item list_item_sec">
                    <view class="list_money">{{(item.Price/100||item.TotalMoney/100||item.TotalPrice/100)}}元</view>
                    <image class="public_right_img" :src="iconUrl.icon_right"></image>
                  </view>
                </view>
                <view class="list_itemDetail " v-if="item.check">
                  <view class="itemDetail_list displayFlexBetween" v-for="(detailItem, ind) in item.ItemList" :key="ind">
                    <view class="name">{{detailItem.Project||detailItem.ReceiptName}}</view>
                    <view class="specifications">{{detailItem.Specifications}}</view>
                    <view class="money">{{detailItem.SumOfMoney/100}}元</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </block>
        <view v-else class="noData">
          <noData :value="noDataValue"></noData>
        </view>
      </view>
    </view>
    <!-- 底部结算 -->
    <view class="order_bottom">
      <view class="bottom_checkbox" v-if="pageConfig.consolidationPayment" @click="allSelecteClick">
        <view class="icon">
          <image class="list_circle" :src="isAllSelected ? iconUrl.circle_active : iconUrl.circle"></image>
        </view>
        <view>全选</view>
      </view>
      <view class='bottom_cost'>
        <view>合计：
          <text class="c_fa4844">{{totalPrice}}元</text>
        </view>
      </view>
      <view class='cost_btn backgroundCustom' @click="pay">去缴费</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {common} from '@/utils';
import icon from '@/utils/icon';
import {
  queryOrderSettlementList,
  queryOrderReceiptList,
  queryOrderPrescriptionList,
  queryOrderSettlementInfo,
  queryOrderPrescriptionInfo,
  settleOrderSettlement,
  addOrderPrescription,
  mergeSettledPayReceipt
} from '@/pagesPatient/service/order/index';
import { pagesPatientFn } from '@/utils';
import userInfo from '@/pagesPersonal/st1/components/userInfo/userInfo.vue';
import noData from '@/pages/st1/components/noData/noData.vue';

const app = getApp();
const iconUrl = icon;
const currentUser = ref<any>({});
const list = ref<any[]>([]);
const listSelected = ref<any[]>([]);
const showNoData = ref(false);
const isAllSelected = ref(false);
const noDataValue = ref('暂无待结算处方');
const showCon = ref(false);
const pageConfig = ref<any>({});

onLoad((options) => {
  let config = common.deepCopy(app.globalData.config.pageConfiguration.orderPayment_config);
  currentUser.value = app.globalData.currentUser;
  pageConfig.value = config;

  // 判断是否合并支付
  if (config.consolidationPayment) {
    common.showModal('标准不做合并处方结算，如医院有要上，个性化。');
    return;
  }
  main();
});

const main = async () => {
  // /**如果没有就诊卡 */
  // if (await publicFn.cardListIsEmpty(this)) {
  //   return
  // }
  queryList();
};

const refresh = () => {
  main();
};

const selectedOptions = (item: any) => {
  let selected = listSelected.value;
  let consolidationPayment = pageConfig.value.consolidationPayment;
  let has = false;
  let key = item.PrescNo ? 'PrescNo' : 'ReceiptNo';
  
  for (let i of selected) {
    if (i[key] == item[key]) {
      has = true;
      break;
    }
  }
  
  if (consolidationPayment) {
    /**可合并支付 */
    if (has) {
      /**如果当前点击的处方已经选中 将其删除*/
      selected = selected.filter(cell => cell[key] != item[key]);
    } else {
      selected.push(item);
    }
  } else {
    /**不可合并支付 */
    selected = [item];
  }
  
  listSelected.value = selected;
  isAllSelected.value = list.value.length == selected.length;
};

const allSelecteClick = () => {
  if (isAllSelected.value) {
    listSelected.value = [];
  } else {
    listSelected.value = [...list.value];
  }
  isAllSelected.value = !isAllSelected.value;
};

const queryList = async (pIndex = 0) => {
  let orderPaymentMode = pageConfig.value.orderPaymentMode;
  let consolidationPayment = pageConfig.value.consolidationPayment;
  let dataList: any[] = [];
  let showNoDataVal = true;
  let times = 30 * 24 * 60 * 60 * 1000;
  let beginDate = common.dateFormat(new Date(Date.now() - times)).formatYear;
  let endDate = common.newDay();
  let user = currentUser.value;
  let queryData: any = {
    CardNo: user.cardNo,
    CardType: user.cardType,
    MemberId: user.memberId,
    Store: {
      cardEncryptionStore: user.encryptionStore || '',
      baseMemberEncryptionStore: user.baseMemberEncryptionStore
    },
    BeginDate: beginDate,
    EndDate: endDate,
    Page: {
      PIndex: pIndex,
      PSize: 10
    }
  };
  
  let resp;
  if (orderPaymentMode == '1') {
    /**预交金模式 */
    queryData.IsSettlement = '0';
    resp = await queryOrderSettlementList(queryData);
  } else if (orderPaymentMode == '2') {
    /**线上支付 */
    if (consolidationPayment) {
      /**如果是合并支付 */
      queryData.IsSettlement = '0';
      resp = await queryOrderReceiptList(queryData);
    } else {
      /**单笔支付 */
      queryData.OrderState = '0';
      resp = await queryOrderPrescriptionList(queryData);
    }
  }
  
  if (!common.isEmpty(resp)) {
    resp.map((item: any) => {
      item.PrescTimeDiy = item.PrescTime || item.ReceiptTime;
      item.PrescTimeDiy = item.PrescTimeDiy.substring(0, 10);
    });
    dataList = resp;
    showNoDataVal = false;
  }
  
  list.value = dataList;
  showNoData.value = showNoDataVal;
  showCon.value = true;
  listSelected.value = [];
  isAllSelected.value = false;
};

const getDetail = async (item: any, index: number) => {
  let orderPaymentMode = pageConfig.value.orderPaymentMode;
  let user = currentUser.value;
  let resp;
  
  if (common.isEmpty(item.ItemList)) {
    let queryData = {
      HisOrderId: item.HisOrderId,
      PrescNo: item.PrescNo || item.ReceiptNo || '',
      MemberId: user.memberId,
      Store: {
        cardEncryptionStore: user.encryptionStore || '',
        baseMemberEncryptionStore: user.baseMemberEncryptionStore
      },
    };
    
    if (orderPaymentMode == '1') {
      /**如果是预交金模式 */
      resp = await queryOrderSettlementInfo(queryData);
    } else {
      /**订单模式 在线支付 */
      resp = await queryOrderPrescriptionInfo(queryData);
    }
    
    if (!common.isEmpty(resp)) {
      list.value[index].ItemList = resp[0].Data_1;
    }
  }
  
  list.value[index].check = !list.value[index].check;
};

const toDetail = (e: any) => {
  let queryBean = JSON.stringify(e.currentTarget.dataset.item);
  common.goToUrl(`/pages/st1/business/order/orderPaymentDetails/orderPaymentDetails?queryBean=${queryBean}`);
};

const pay = (e: any) => {
  prescriptionPayment();
};

const prescriptionPayment = async () => {
  /**订单缴费模式  1预交金  2线上支付 */
  let config = !common.isEmpty(pageConfig.value) ? pageConfig.value : (app.globalData.config.pageConfiguration.orderPayment_config || {});
  let orderPaymentMode = config.orderPaymentMode;
  /**是否合并支付 */
  let consolidationPayment = config.consolidationPayment;
  let user = currentUser.value;
  
  if (common.isEmpty(listSelected.value)) {
    common.showModal('请选择处方');
    return;
  }
  
  let total = 0;
  let hisOrderIds: any[] = [];
  let prescNos: any[] = [];
  let receiptPrices: any[] = [];
  let receiptNames: any[] = [];
  let serviceId = listSelected.value[0].ServiceId;
  
  listSelected.value.map(item => {
    total += item.Price || item.TotalMoney || item.TotalPrice;
    receiptPrices.push(item.Price || item.TotalMoney || item.TotalPrice);
    receiptNames.push(item.PrescType || item.ServiceName || item.ReceiptName);
    hisOrderIds.push(item.HisOrderId);
    prescNos.push(item.PrescNo || item.ReceiptNo);
  });
  
  if (orderPaymentMode == '1') {
    /**预交金模式 */
    common.showModal('确认结算？', async () => {
      let queryData = {
        CardNo: user.cardNo,
        CardType: user.cardType,
        MemberId: user.memberId,
        TotalPrice: total,
        HisOrderIds: hisOrderIds.join(','),
        PrescNos: prescNos.join(','),
        Store: {
          cardEncryptionStore: user.encryptionStore || '',
          baseMemberEncryptionStore: user.baseMemberEncryptionStore
        }
      };
      let resp = await settleOrderSettlement(queryData);
      if (!common.isEmpty(resp)) {
        common.goToUrl(`/pagesPatient/st1/business/pay/payState/payState?pageType=orderPayment`);
      }
    }, {
      cancelText: '取消'
    });
  } else {
    /**判断是否有待支付订单*/
    if (await pagesPatientFn.hasOrderToBePaid(serviceId)) {
      return;
    }
    
    common.showModal('确认结算？', async () => {
      let resp;
      if (consolidationPayment) {
        /**如果是订单缴费合并支付 */
        let queryData = {
          CardNo: user.cardNo,
          CardType: user.cardType,
          MemberId: user.memberId,
          TotalPrice: total,
          ReceiptNos: prescNos.join(','),
          ReceiptPrices: receiptPrices.join(','),
          ReceiptNames: receiptNames.join(','),
          Store: {
            cardEncryptionStore: user.encryptionStore || '',
            baseMemberEncryptionStore: user.baseMemberEncryptionStore
          }
        };
        resp = await mergeSettledPayReceipt(queryData);
      } else {
        /**订单缴费单笔支付 */
        let queryData = {
          HisOrderId: hisOrderIds.join(','),
          PrescNo: prescNos.join(','),
          PayMoney: total,
          TotalMoney: total,
          OperatorName: user.memberName,
          EqptType: '3',
          MemberId: user.memberId,
          CardNo: user.cardNo,
          CardType: user.cardType,
          OperatorId: uni.getStorageSync('openid'),
          ServiceId: serviceId,
          TransactionCode: "",
          Store: {
            cardEncryptionStore: user.encryptionStore || '',
            baseMemberEncryptionStore: user.baseMemberEncryptionStore
          }
        };
        resp = await addOrderPrescription(queryData);
      }
      
      if (!common.isEmpty(resp)) {
        common.goToUrl(`/pagesPatient/st1/business/pay/payMent/payMent?orderId=${resp[0].OrderId}`);
      }
    }, {
      cancelText: '取消'
    });
  }
};

const totalPrice = computed(() => {
  let num = 0;
  if (listSelected.value && listSelected.value.length > 0) {
    for (let i = 0; i < listSelected.value.length; i++) {
      const item = listSelected.value[i];
      num += item.Price || item.TotalMoney || item.TotalPrice || 0;
    }
  }
  return num / 100;
});

const isInclude = (item: any) => {
  const selected = listSelected.value;
  if (selected && selected.length > 0) {
    const variable = selected[0].PrescNo ? "PrescNo" : "ReceiptNo";
    return selected.some((i: any) => i[variable] == item[variable]);
  }
  return false;
};

defineExpose({
  refresh
});
</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  padding-bottom: 132upx;
  overflow: auto;
  padding-top: 190upx;
}
.noData {
  margin-top: 250upx;
}
.public_con{
  margin: 30upx;
  background-color: #fff;
  border-radius: 24upx;
}
.public_con_nav{
  font-size: 32upx;
  padding: 40upx 30upx;
}
.public_con_info {
  margin: 0 30upx;
}

.public_con_info .info_list {
  font-size: 30upx;
  font-weight: 400;
  color: #222326;
  display: flex;
  align-items: center;
}

.list_item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 50%;
  padding: 40upx 0 46upx;
}

.list_item_sec {
  justify-content: flex-end;
  position: relative;
}

.list_money {
  margin-right: 32upx;
}

.list_circle {
  width: 44upx;
  height: 44upx;
  margin-right: 24upx;
  flex-shrink: 0;
}
.list_name{
  line-height: 24upx;
}


.list_itemDetail .itemDetail_list {
  font-size: 30upx;
  font-weight: 400;
  color: #222326;
  padding-bottom: 30upx;
}
.list_itemDetail .itemDetail_list .name{
  width: 50%;
}

.list_itemDetail .itemDetail_list .money{
  width: 20%;
  text-align: right;
}
.list_itemDetail .itemDetail_list .specifications{
  color:#6f6f6f;
  width: 30%;
}
/* 底部结算 */

.order_bottom {
  height: 132upx;
  width: 100%;
  background: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  padding: 0 30upx;
}

.order_bottom .bottom_checkbox {
  flex: 0 0 auto;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 30upx;
  font-weight: 400;
  color: rgba(0, 0, 0, 1);
  margin-right: 40upx;
}

.order_bottom .bottom_cost {
  font-size: 32upx;
  font-weight: 500;
  color: rgba(0, 0, 0, 1);
}

.order_bottom  .cost_btn {
  font-size: 32upx;
  font-weight: 500;
  width: 240upx !important;
  height: 92upx;
  border-radius: 46upx;
  color: #fff;
  position: absolute;
  top: 20upx;
  right: 30upx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.c_fa4844 {
  color: #fa4844;
}

/* Helper classes */
.displayFlexBetween {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.border_top {
  border-top: 1upx solid #eee;
}
.mr10 {
  margin-right: 10upx;
}
</style>