<script setup lang="ts">
import dayjs from 'dayjs';
const { t } = useI18n();
import {
  onMounted,
  getCurrentInstance
} from 'vue';
import Config from '@/config/index'
import {useConfigStore, useUserStore} from "@/store";
const configStore = useConfigStore()
const userStore = useUserStore();
import {EventEnum} from "@/constant/enums";
import {appMembershipRechargePost, appUserCardSelectDefaultPost} from "@/service";
import { tWithParams } from '@/utils/utils';

// 订阅选项
const subscriptionPlans = ref([]);
// 当前选中的会员下标
const currentIndex = ref(0)

// 选择订阅计划
const selectPlan = (index: string) => {
  currentIndex.value = index
};

const isUserMember = computed(()=> {
  if(!userStore.userInfo.userMembershipVo) return false
  if(userStore.userInfo.userMembershipVo && userStore.userInfo.userMembershipVo.expireTime ){
    return dayjs().isBefore(dayjs(Number(userStore.userInfo.userMembershipVo.expireTime)))
  } else {
    return false
  }
})

onMounted(() => {
  appUserCardSelectDefault()
  const instance = getCurrentInstance().proxy
  const eventChannel = instance.getOpenerEventChannel();
  eventChannel.on('acceptDataFromOpenerPage', function(data) {
    console.log('acceptDataFromOpenerPage', data)
    if(data.data) {
      subscriptionPlans.value = data.data
    }
  })
})

// 年度会员比月度会员优惠多少钱
const annualDiscount = computed(() => {
  // 找到月度会员和年度会员
  const monthlyPlan = subscriptionPlans.value.find(plan => plan.membershipType === 1);
  const annualPlan = subscriptionPlans.value.find(plan => plan.membershipType === 2);

  // 检查是否找到两种会员类型
  if (!monthlyPlan || !annualPlan) {
    return null;
  }

  // 转换为数字进行计算
  const monthlyPrice = parseFloat(monthlyPlan.rechargeAmount);
  const annualPrice = parseFloat(annualPlan.rechargeAmount);

  // 计算12个月的月度会员总价
  const yearlyMonthlyTotal = monthlyPrice * 12;

  // 计算优惠金额
  const discount = yearlyMonthlyTotal - annualPrice;

  // 如果有优惠（优惠金额大于0），返回优惠金额，否则返回null
  return discount > 0 ? parseFloat(discount.toFixed(2)) : null;
});

// 计算处理后的描述信息
const processedDescription = computed(() => {
  // 获取当前选中的会员信息
  const currentMembership = subscriptionPlans.value[currentIndex.value];
  if (!currentMembership) return '';

  // 计算时间：当前日期加上对应时长
  let timeStr = '';
  const today = dayjs();

  if (currentMembership.membershipType === 1) {
    // 月度会员：加一个月
    timeStr = today.add(1, 'month').format('YYYY-MM-DD');
  } else if (currentMembership.membershipType === 2) {
    // 年度会员：加一年
    timeStr = today.add(1, 'year').format('YYYY-MM-DD');
  }

  // 确定类型显示文本
  const typeText = currentMembership.membershipType === 1 ? 'month' : 'year';

  // 替换占位符
  return currentMembership.description
      .replace(/{time}/g, timeStr)
      .replace(/{price}/g, currentMembership.rechargeAmount)
      .replace(/{type}/g, typeText);
});


// 支付参数
const payMethodOptions = ref({
  orderId: '',
  cardId: '',
  payMethod: 1, // 支付方式 1信用卡 2余额
  payPassword: '',
})
useEventEmit(EventEnum.CHOOSE_PAYMENT_METHOD, (data) => {
  if(data) {
    if(data.payMethod === 1) {
      payMethodOptions.value.cardId = data.cardId
      payMethodOptions.value.cardNumber = data.cardNumber
      payMethodOptions.value.payMethod = 1
    } else {
      payMethodOptions.value.payMethod = 2
    }
  }
})

function appUserCardSelectDefault() {
  appUserCardSelectDefaultPost({}).then(res=> {
    console.log('查询用户默认信用卡', res)
    payMethodOptions.value.cardId = res.data?.cardId || ''
    payMethodOptions.value.cardNumber = res.data?.cardNumber || ''
  })
}

function navigateTo(url: string) {
  uni.navigateTo({ url })
}

const passwordInputRef = ref()
function payPawSuccess(password: string) {
  payMethodOptions.value.payPassword = password
  appMembershipRecharge()
}

function handleSubmit() {
  // 如果是余额支付,弹出支付密码弹窗
  if(payMethodOptions.value.payMethod === 2) {
    passwordInputRef.value?.showPasswordInput()
  } else {
    appMembershipRecharge()
  }
}
function appMembershipRecharge() {
  appMembershipRechargePost({
    body: {
      ...payMethodOptions.value,
      autoSubscribe: autoSubscribe.value,
      rechargeItemId: subscriptionPlans.value[currentIndex.value].id
    }
  }).then(res=> {
    console.log('充值结果', res)
    uni.showToast({
      title: '充值成功',
      icon: 'none'
    })
    setTimeout(()=> {
      userStore.getUserInfo()
      uni.navigateBack({
        delta: 1,
      })
    }, 500)
  })
}


// 是否订阅 autoSubscribe  1-是 2-否
const autoSubscribe = ref(2)

function changeAutoSubscribe() {
  autoSubscribe.value = autoSubscribe.value === 1 ? 2 : 1
}
</script>

<template>
  <view>
    <navbar />
    <view class="pl-30rpx mt-20rpx text-46rpx lh-46rpx text-#333 font-bold tracking-[.04em]"
    >{{ t('pages-user.member.join') }} {{ Config.appName }}</view
    >

    <!-- 订阅选项 -->
    <view class="px-30rpx mt-66rpx">
      <view
        v-for="(item, index) in subscriptionPlans"
        :key="item.id"
        class="bg-white rounded-20rpx border border-#D8D8D8 mb-30rpx relative"
        :class="{ 'border-#CE7138': item.selected }"
        @click="selectPlan(index)"
      >
        <!-- 卡片内容 -->
        <view class="border-#D8D8D8 border-solid border-1px rounded-20rpx">
          <view class="px-28rpx py-40rpx flex items-center justify-between">
            <view class="flex-1">
              <view class="text-36rpx lh-36rpx text-#333 font-bold mb-28rpx">{{
                item.name
              }}</view>
              <!--userMembershipVo为null必为没开通过-->
              <!--hasUseFree用户是否已使用试用会员资格 1是 2 否-->
              <view v-if="!userStore.userInfo.userMembershipVo || +userStore.userInfo.userMembershipVo.hasUseFree === 2" class="text-28rpx lh-28rpx text-#CE7138 mb-32rpx"
                >{{ t('pages-user.member.freeTrial') }}：{{ item.trialWeeksDisplay }}
              </view>
              <view class="flex items-center text-28rpx lh-28rpx">
                <view class="text-#f00 font-500">
                  $<template v-if="+item.membershipType === 2">{{ (item.rechargeAmount / 12).toFixed(2) }}</template>
                  <template v-else>{{ item.rechargeAmount }}</template>
                  <text class=" text-#333">
                    /{{ t('pages-user.member.month') }}
                  </text>
                </view>
                <text
                  v-if="+item.membershipType === 2"
                  class=" text-#999 ml-16rpx"
                  >({{ tWithParams('pages-user.member.billedAnnually', { amount: item.rechargeAmount }) }})</text
                >
              </view>
            </view>

            <!-- 单选按钮 -->
            <image
                :src="
                  currentIndex === index
                    ? '/static/images/chef/133.png'
                    : '/static/images/chef/134.png'
                "
                class="w-48rpx h-48rpx shrink-0"
                mode="aspectFit"
            />
          </view>
          <!-- 年度计划的节省提示 -->
          <view
              v-if="+item.membershipType === 2 && annualDiscount"
              class="bg-[rgba(206,113,56,0.1)] rounded-b-20rpx p-16rpx"
          >
            <view class="flex items-center">
              <image
                  src="@img/chef/139.png"
                  class="w-32rpx h-32rpx mr-16rpx shrink-0"
                  mode="aspectFit"
              />
              <text class="text-24rpx text-#CE7138">{{ tWithParams('pages-user.member.savingsPerYear', { amount: `$${annualDiscount}` }) }}</text>
            </view>
          </view>
        </view>
      </view>

      <view @click="changeAutoSubscribe" class="border-#D8D8D8 border-solid border-1px p-24rpx flex-center-sb rounded-20rpx">
        <view class="">{{ t('pages-user.member.autoSubscribe') }}</view>
        <view class="center">
          <image
              :src="
                  autoSubscribe === 1
                  ? '/static/images/chef/133.png'
                   : '/static/images/chef/134.png'
                  "
              class="w-44rpx h-44rpx shrink-0"
              mode="aspectFit"
          />
        </view>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="px-30rpx my-88rpx">
      <view
          @click="navigateTo('/pages-user/pages/choose-paymethod/index')"
          class="flex-center-sb text-32rpx lh-32rpx font-500 text-#333"
      >
        <view class="flex items-center">
          <image
              src="@img/chef/138.png"
              class="w-44rpx h-44rpx mr-28rpx shrink-0"
              mode="aspectFit"
          />
          <text class="">
            <template v-if="payMethodOptions.payMethod === 1">{{ t('pages-user.choosePaymethod.creditCard') }}</template>
            <template v-else>{{ t('pages-user.choosePaymethod.wallet') }}</template>
          </text>
        </view>
        <view class="flex items-center">
          <view class="mr-12px">
            <template v-if="payMethodOptions.payMethod === 1">
              <!--判断用户是否有信用卡-->
              <text v-if="!payMethodOptions.cardId">{{ t("pages-user.member.creditCard") }}</text>
              <text v-else>{{ payMethodOptions.cardNumber }}</text>
            </template>
            <template v-else-if="payMethodOptions.payMethod === 2">
              <text>{{ t('pages-user.choosePaymethod.wallet') }}</text>
            </template>
          </view>
          <image
              src="@img/chef/142.png"
              class="w-32rpx h-32rpx shrink-0"
              mode="aspectFit"
          />
        </view>
      </view>
    </view>

    <!-- 账单信息 -->
    <view class="px-30rpx mt-40rpx text-28rpx text-#333 font-500 leading-32rpx mb-10rpx">
      {{ processedDescription }}
<!--      <view class="text-28rpx text-#333 font-500 leading-32rpx mb-10rpx">-->
<!--        Starting from June 25th, 2025, billing will be charged at a rate of US-->
<!--        $96.00/year. No additional fees or penalties are required for-->
<!--        cancellation.-->
<!--      </view>-->
<!--      <view class="text-28rpx text-#7D7D7D leading-28rpx">-->
<!--        By joining Chef One, you authorize Uber to collect US $96.00 through any-->
<!--        payment method in your account after the end of any applicable free-->
<!--        trial period.-->
<!--      </view>-->
    </view>

    <!-- 底部按钮 -->
    <view class="fixed bottom-0 left-0 right-0 px-30rpx">
      <wd-button custom-class="!h-98rpx !text-30rpx !text-#fff !lh-98rpx !rounded-16rpx" block
                 @click="handleSubmit">{{ t('pages-user.member.btn-text') }}
      </wd-button>
      <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
    </view>


    <password-container @success="payPawSuccess" ref="passwordInputRef" />
  </view>
</template>

<style>
page {
  background-color: #fff;
}
</style>
