<script setup lang="ts">
import { getArrayFieldMax, isWithin45Minutes, timeFormat } from '../utils/index'
import router from '@/router'
import { StaticUrl } from '@/config'

definePage({
  name: 'film-submit-order',
  islogin: false,
  style: {
    navigationBarTitleText: '确认订单',
    backgroundColorBottom: '#fff',
  },
})

// const isDifferent = computed(() => {
//   return info.choose
// })
const showProtocol = ref(true)
const isAgree = ref(false)
const loading = ref(false)
const { userInfo } = storeToRefs(useUserStore())

const query = ref({
  memberId: unref(userInfo).id,
  channelId: unref(userInfo).channelId,
  shopId: '1',
  channelName: unref(userInfo).channelName,
  cinemaName: '',
  cinemaCode: '',
  movieCode: '',
  hallName: '',
  orderPayMode: '1',
  originPrice: 0,
  seatNames: '',
  sessionBeginTime: '',
  switchSeat: false,
  movieOrderItems: [] as Array<{ name: string, price: number }>,
  session: '',
  postImageUrl: '',
  movieName: '',
  fastTicket: false,
})

const info = ref({
  cinemaName: '',
  totalPrice: 0,
  phone: '',
  points: 0,
  language: '',
  planType: '',
  showTime: '',
  hallName: '',
  chooseSeatList: [] as Array<{ seatName: string, ticketPrice: number, fastPrice: number, areaId: string }>,
})

const isDiffrent = computed(() => {
  let flag = false
  const areaId = info.value.chooseSeatList[0].areaId
  for (const item of info.value.chooseSeatList) {
    if (item.areaId !== areaId) {
      flag = true
      break
    }
  }
  return flag
})

const totalPrice = computed(() => {
  let total = 0
  const scale = 10000
  if (!info.value.showTime)
    return 0
  const key = isWithin45Minutes(new Date(), info.value.showTime) ? 'fastPrice' : 'ticketPrice'
  const price = getArrayFieldMax(info.value.chooseSeatList, key) || 0
  total = (price * scale) * info.value.chooseSeatList.length / scale
  return total
})
function back() {
  showProtocol.value = false
  router.back()
}

function next() {
  if (!isAgree.value) {
    return useGlobalToast().show('请先勾选协议')
  }
  showProtocol.value = false
}

async function pay() {
  loading.value = true
  try {
    query.value.fastTicket = isWithin45Minutes(new Date(), info.value.showTime)
    query.value.movieOrderItems = info.value.chooseSeatList.map((item: any) => {
      if (isWithin45Minutes(new Date(), info.value.showTime)) { // 如果在45分钟内，快速出票
        return {
          name: item.seatName,
          price: item.fastPrice,
        }
      }
      else {
        return {
          name: item.seatName,
          price: item.ticketPrice,
        }
      }
    })
    const { data: orderNumber } = await Apis.film.addFilmOrder({ data: query.value })
    const payMent = await useUserStore().getPayMent(orderNumber)
    if (payMent.payType !== 'point') {
      try {
        // #ifdef MP-WEIXIN
        const res = await useUserStore().handleCommonPayMent(orderNumber)
        await useUserStore().getWxCommonPayment(res)
        await useUserStore().paySuccess('film-order', 'subPack-film/index/index')
        // #endif
        // #ifdef H5
        useUserStore().handleCommonWechatPay(orderNumber)
        await handleH5PayResult(orderNumber)
        // #endif
      }
      catch {
        await useUserStore().payError('film-order', 'subPack-film/index/index')
      }
    }
    else {
      await useUserStore().handleCommonPayMent(orderNumber)
      await useUserStore().paySuccess('film-order', 'subPack-film/index/index')
    }
  }
  catch (error) {
    console.error('支付失败:', error)
  }
  finally {
    loading.value = false
  }
}
async function handleH5PayResult(orderNumber: string) {
  const isPaySuccess = await useUserStore().pollOrderPaySuccess(orderNumber)
  if (isPaySuccess) {
    await useUserStore().paySuccess('film-order', 'subPack-film/index/index')
    return
  }
  useGlobalToast().show({ msg: '暂未查询到支付成功，请稍后在订单列表查看' })
}
function call() {
  uni.makePhoneCall({
    phoneNumber: info.value.phone,
  })
}
async function getPoints() {
  const res = await Apis.xsb.findUserPoints({})
  if (res.data) {
    info.value.points = res.data.availablePointsTotal as number
  }
  else {
    info.value.points = 0
  }
  console.log(11111111, info.value.points)
}
getPoints()

function usePoints() {
  return (totalPrice.value * 100) >= info.value.points ? info.value.points : ((totalPrice.value * 10000) / 100)
}

onLoad((options) => {
  query.value = JSON.parse(options?.query)
  info.value = uni.getStorageSync('film-info')
  console.log(11111, info.value.chooseSeatList)
})
</script>

<template>
  <view class="film-submit-order">
    <!-- 影片信息 -->
    <view class="movie-info-box block">
      <view class="movie-info">
        <image class="img" :src="query.postImageUrl" />
        <view class="title-box">
          <view class="title">
            {{ query.movieName }}
          </view>
          <view class="time-box">
            {{ timeFormat(info.showTime) }} {{ info.language }} {{ info.planType }}
          </view>
        </view>
      </view>
      <view class="phone-box">
        <view class="notice-box">
          <image class="icon" :src="`${StaticUrl}/film-error.png`" mode="scaleToFill" />
          <view class="text">
            不支持线上改签、退款，具体请咨询商家。
          </view>
        </view>
        <image class="phone" :src="`${StaticUrl}/film-phone.png`" mode="scaleToFill" @click="call" />
      </view>
    </view>

    <!-- 座位信息 -->
    <view class="seat-info block">
      <view class="sub-title">
        {{ info.cinemaName }}
      </view>
      <view class="room-num">
        {{ query.hallName }}
      </view>
      <!-- <view class="area-price">
        普通区￥29.9
      </view> -->
      <view class="seat-list">
        <view v-for="(item, index) in info.chooseSeatList" :key="index" class="item">
          <view class="label">
            {{ item.seatName }}
          </view>
          <view class="value">
            ￥{{ isWithin45Minutes(new Date(), info.showTime) ? item.fastPrice : item.ticketPrice }}
          </view>
        </view>
      </view>
      <!--
      <view class="area-price">
        贵宾区￥39.9
      </view>
      <view class="seat-list">
        <view class="item">
          <view class="label">
            2排11座
          </view>
          <view class="value">
            ￥29.9
          </view>
        </view>
        <view class="item">
          <view class="label">
            2排11座
          </view>
          <view class="value">
            ￥29.9
          </view>
        </view>
      </view> -->
    </view>

    <!-- 价格信息 -->
    <view class="goods-price-box block">
      <view class="item">
        <view class="label">
          商品金额
        </view>
        <view class="value">
          ￥{{ totalPrice || info.totalPrice }}
        </view>
      </view>
      <view v-if="isDiffrent" class="notice">
        座位跨区,按最高价格计算。订单总价=最高座位价格×座位数
      </view>
      <view class="item">
        <view class="label">
          积分（{{ usePoints() }}）
        </view>
        <view class="value price">
          -￥{{ usePoints() / 100 }}
        </view>
      </view>
      <!-- <view class="item">
        <view class="label">
          平台券
        </view>
        <view class="value price">
          -￥14
        </view>
      </view> -->
      <view class="line" />
      <view class="total-box">
        <view class="text">
          总计
        </view>
        <view class="total">
          ￥{{ (totalPrice * 100 - usePoints()) / 100 }}
        </view>
      </view>
    </view>

    <!-- 购票须知 -->
    <view class="notice-box block">
      <view class="sub-title">
        购票须知
      </view>
      <view class="content-text">
        1.请提前30分钟左右到达影院现场，通过影院自助取票机完成
        取票。

        2.若取票过程中遇到无法取票等其它问题，请联系影院工作人
        员进行处理。

        3.请及时关注电影开场时间，凭票有序检票入场。

        4.如需开具电影票发票，可联系影院工作人员凭当日票根进行
        开具，若遇到特殊情况请及时联系猫眼客服人员。

        5.退票、改签服务请参考影院具体政策要求，特殊场次及部分
        使用卡、券场次订单可能不支持此服务。

        6.由于设备故障等不可抗力因素，存在少量影院调整/取消场次
        的情况，系统将会自动退票退款。

        7.由于影院系统不稳定等因素，存在少量出票失败的情况系统
        将会自动退款请注意查收。

        8.如有其他问题可联系在线客服，工作时间:9:00-22:00。
      </view>
    </view>

    <!-- 底部 -->
    <view class="footer-box">
      <view class="price-box">
        <view class="total">
          ￥{{ (totalPrice * 100 - usePoints()) / 100 }}
        </view>
        <view class="reduce">
          共减￥{{ usePoints() / 100 }}
        </view>
      </view>
      <wd-button
        custom-style="width: 180rpx;height: 80rpx;background: #9ED605;border-radius: 40rpx 40rpx 40rpx 40rpx;" :loading="loading" @click="pay"
      >
        立即支付
      </wd-button>
    </view>

    <!-- 协议弹窗 -->
    <wd-popup v-model="showProtocol" :close-on-click-modal="false" custom-style="border-radius:16rpx;">
      <view class="popup-box">
        <view class="title">
          退改签协议
        </view>
        <view class="content-text">
          用户点击同意本协议之前，请务必认真阅读完全理解本协议中
          全部条款，特别是其中与用户权益有或可能具有重大关系的条
          款(包括但不限于第1.2条、第1.3条、第2条、第3.2条)。当用
          户按照页面提示阅读、点击确认同意本协议及完成支付购票时，
          即表示用户已经充分阅读、理解并接受本协议的全部内容。如
          用户不同意接受本协议的任何条款，或无法理解本协议相关条
          款含义的，请不要进行后续操用户点击同意本协议之前，请务
          必认真阅读完全理解木协议中全部条款 特别是其中与用户权
          益有或可能，用户点击同意本协议之前，请务必认真阅读
        </view>

        <view class="radio-box">
          <wd-checkbox v-model="isAgree">
            我已阅读并同意以上协议
          </wd-checkbox>
        </view>
        <view class="btn-box">
          <wd-button custom-class="btn" @click="next">
            继续购票
          </wd-button>
          <wd-button custom-class="btn" type="text" @click="back">
            暂不购票
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped>
.film-submit-order{
  padding: 20rpx 24rpx 300rpx;
  background: #F9F9F9;
  .block {
    background: #FFFFFF;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
  }
  .sub-title {
    font-weight: bold;
    font-size: 32rpx;
    color: #222222;
  }
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    .label {
      font-size: 28rpx;
      color: #222222;
    }
    .label.gray {
      color: #AAAAAA;
    }
    .value {
      font-size: 28rpx;
      color: #222222;
    }
    .value.price {
      color: #FF4A39;
    }
  }

  .item:first-child {
    margin-top: 0 !important;
  }

  .movie-info {
    display: flex;
    align-items: center;

    .img {
      width: 152rpx;
      height: 208rpx;
      margin-right: 24rpx;
      border-radius: 16rpx;
      vertical-align: bottom;
    }

    .title-box {
      display: flex;
      flex-direction: column;
      justify-content: center;

      .title {
        font-weight: bold;
        font-size: 32rpx;
        color: #222222;
        margin-bottom: 20rpx;
      }

      .time-box {
        font-size: 24rpx;
        color: #AAAAAA;
      }
    }
  }
  .phone-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 24rpx;
    .notice-box{
      display: flex;
      align-items: center;
      .icon{
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }
      .text{
        font-size: 24rpx;
        color: #222222;
      }
    }

    .phone{
      width: 40rpx;
      height: 40rpx;
    }
  }

  .seat-info {
    .room-num {
      font-size: 28rpx;
      color: #222222;
      margin: 20rpx 0;
    }

    .area-price {
      font-size: 24rpx;
      color: #AAAAAA;
      margin: 20rpx 0;
    }

    .seat-list {}
  }

  .goods-price-box {
    .notice {
      font-size: 24rpx;
      color: #AAAAAA;
      margin-top: 16rpx;
    }

    .line {
      height: 2rpx;
      background: #F0F0F0;
      margin-top: 20rpx;
    }

    .total-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 30rpx;

      .text {
        font-weight: bold;
        font-size: 32rpx;
        color: #222222;
      }

      .total {
        font-weight: bold;
        font-size: 32rpx;
        color: #FF4A39;
      }
    }
  }

  .notice-box{
    .content-text{
      font-size: 24rpx;
      color: #222222;
      line-height: 42rpx;
      margin-top: 24rpx;
    }
  }

  .footer-box{
    position: fixed;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    padding: 12rpx 24rpx 76rpx;
    background: #fff;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1rpx solid #EEEEEE;
    .price-box{
      display: flex;
      align-items: center;
      .total{
        font-weight: bold;
        font-size: 40rpx;
        color: #FF4A39;
      }
      .reduce{
        font-size: 24rpx;
        color: #FF4A39;
        margin-left: 20rpx;
      }
    }
  }

}
.btn-box::v-deep .btn {
  width: 654rpx;
  height: 80rpx;
  margin-top: 24rpx;
}
.popup-box{
  width: 702rpx;
  height: 826rpx;
  background: #FFFFFF;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
  padding: 28rpx 24rpx;
  box-sizing: border-box;
  .title{
    font-weight: bold;
    font-size: 28rpx;
    color: #222222;
    text-align: center;
  }
  .content-text{
    height: 500rpx;
    overflow-y: auto;
    font-size: 24rpx;
    color: #222222;
    line-height: 42rpx;
    margin-top: 24rpx;
  }
  .radio-box{
    margin-top: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .btn-box{
    display: flex;
    flex-direction: column;

  }
}
</style>
