<template>
  <ay-container>
    <ay-skeletons :rowList="data.rowList" :loading="data.firstLoad">
      <div class="station">
        <ayb-station type="2" :stationInfo="data.stationInfo" />
      </div>
      <div class="chunk1">
        <div>
          <span class="mr-spacd4">加气量</span>
          <span class="font-bold b-fz mr-spacd4">{{ data.orderDetail.gasQty }}</span>
          <span>公斤</span>
        </div>
      </div>
      <div class="section s-fz">选择支付方式</div>
      <div class="flex chunk s-fz" :class="{ checked: data.fpayType === 0 }">
        <span
          class="mr-spacd2 radio"
          :class="{ checked: data.fpayType === 0 }"
          @click="methods.choose(0)"
        ></span>
        <div>
          <span class="font-bold" @click="methods.choose(0)">个人支付</span>
          <div class="ml-spacd2 mt-spacd2">
            结算金额 ¥ {{ personPay?.amount }} 元 （结算价 ¥ {{ personPay?.actualPrice }} 元/公斤）
          </div>
        </div>
      </div>
      <div class="flex chunk s-fz" v-if="carrierPay" :class="{ checked: data.fpayType === 1 }">
        <span
          class="mr-spacd2 radio"
          :class="{ checked: data.fpayType === 1 }"
          @click="methods.choose(1)"
        ></span>
        <div class="flex-1">
          <span class="font-bold" @click="methods.choose(1)">所属物流支付</span>
          <div class="childs-fc-mbd2 ml-spacd2 mt-spacd2">
            <div @click="methods.switchRebateDetail">
              结算金额 ¥ {{ carrierPay.amount }} 元 （结算价 ¥
              {{ carrierPay.actualPrice }} 元/公斤）
            </div>
            <span v-if="carrierPay.carrierRebate">
              优惠金额{{ carrierPay.carrierRebate }}元
              <uni-icons
                :type="data.showRebateDetail ? 'up' : 'down'"
                color=""
                class="p-color p-fz"
                v-if="carrierPay.rebateNum"
                @click="methods.switchRebateDetail"
              />
            </span>
            <span
              v-if="carrierPay.rebateNum"
              v-show="data.showRebateDetail"
              class="chunk childs-fcjb-mbd2 rebate-detail money-bg"
            >
              <div v-for="(rd, i) in carrierPay.rebateDetail" :key="i">
                <div>{{ config.common.interestType[rd.interestType] }}</div>
                <div>￥{{ rd.rebateAmount }}元</div>
              </div>
            </span>
            <div class="pt-spacd2 top-line">{{ carrierPay.carrierOrgName }}</div>
            <div>[{{ carrierPay.carNumber }}]</div>
            <div class="justify-start">
              <div>可用余额￥{{ carrierPay.balance }}元</div>
              <div class="center p-color ml-spacd2" @click="methods.paysel">
                <uni-icons
                  type="refresh"
                  color=""
                  size="20"
                  :class="{ rotater: store.webapi.strategy.paysel.ing }"
                ></uni-icons>
                刷新
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="chunk2">
        <div>
          <span>创建订单</span>
          <div>{{ data.orderDetail.createDate }}</div>
        </div>
        <div>
          <span>订单编号</span>
          <div>{{ data.orderDetail.orderId }}</div>
        </div>
        <div>
          <span>驾驶员</span>
          <div>{{ data.orderDetail.driverName }}</div>
        </div>
      </div>
      <div class="btns">
        <button
          type="primary"
          :disabled="!canPay"
          :loading="store.webapi.pay.order_pay.ing"
          @click="methods.pay()"
        >
          {{ curPay?.buttonMsg }}
        </button>
      </div>
    </ay-skeletons>
  </ay-container>
</template>

<script lang="ts" setup>
const data = reactive({
  firstLoad: true,
  /** 页面选择支付类型： -1:未选择 0:个人：1：物流 */
  fpayType: -1,
  orderDetail: {} as 订单详情,
  stationInfo: {} as GasstationVO对象,
  paysel: {} as 待支付订单_可选支付方式获取实体类,
  showRebateDetail: false,
  rowList: [
    {
      align: 'left',
      verticalAlign: 'top',
      colItems: [
        {
          style: {
            width: '168rpx',
            height: '168rpx',
            'flex-shrink': 0,
          },
        },
        {
          style: {
            width: '100%',
          },
          childRowItems: [
            {
              style: {
                width: '80%',
              },
            },
            {
              style: {
                width: '100%',
              },
            },
            {
              style: {
                width: '100%',
              },
            },
          ],
        },
      ],
    },
    ...Array(20).fill({
      align: 'left',
      colItems: 1,
    }),
    {
      align: 'left',
      colItems: [
        {
          style: {
            width: '60%',
          },
        },
      ],
    },
  ],
})

const canPay = computed(() => curPay.value?.buttonEnable && !store.webapi.pay.order_pay.ing)
const pageParams = computed(() => store.curPage.pageConfig.params)
const personPay = computed(() => data.paysel?.personPay)
const carrierPay = computed(() => data.paysel?.carrierPay)
/** 当前支付方式 */
const curPay = computed<待支付订单_可选支付方式物流支付实体类>(() => {
  let rv: 待支付订单_可选支付方式物流支付实体类 = {
    buttonMsg: '请选择支付方式',
    buttonEnable: false,
  }
  if (data.fpayType === 0) {
    rv = {
      ...data.paysel?.personPay,
      wxAmount: data.paysel.personPay.amount,
    }
  }
  if (data.fpayType === 1) {
    rv = data.paysel?.carrierPay
  }
  return rv
})

const methods = {
  switchRebateDetail() {
    data.showRebateDetail = !data.showRebateDetail
  },
  choose(fpayType) {
    data.fpayType = fpayType
  },
  async pay() {
    if (data.fpayType === -1) {
      func.native.showToast('请选择支付方式')
      return
    }
    const params: OrderPayParam = {
      orderId: pageParams.value.orderId,
      payType: curPay.value.payType,
    }
    // 需要微信支付
    if ([1, 2, 3].includes(curPay.value.payType)) {
      const li = await uni.login()
      params.jsCode = li.code
      params.wxAmount = curPay.value.wxAmount
    }
    // 物流支付
    if (data.fpayType === 1) {
      params.carNumber = carrierPay.value.carNumber
      params.carrierOrgId = carrierPay.value.carrierOrgId
      params.carrierOrgName = carrierPay.value.carrierOrgName
      params.linked = carrierPay.value.linked
      params.tradeType = carrierPay.value.tradeType
      params.truckId = carrierPay.value.truckId
    }
    webapi.pay.order_pay(params).then((res) => {
      if ([1, 2, 3].includes(curPay.value.payType)) {
        uni.requestPayment({
          ...JSON.parse(res.payInfo),
          success() {
            methods.paySuccess()
          },
          fail() {
            func.native.showToast({
              icon: 'error',
              title: '支付失败',
            })
          },
        })
      } else {
        methods.paySuccess()
      }
    })
  },
  paySuccess() {
    func.native
      .showToast({
        icon: 'success',
        title: '支付成功',
      })
      .then(() => {
        ay.goPage(config.pages.order_orderDetail, {
          params: data.orderDetail,
          goPageType: enums.GoPageType.redirectTo,
        })
      })
  },
  getOrderDetail() {
    return webapi.strategy
      .get_order_detail({ orderId: pageParams.value.orderId, orderType: 1 })
      .then(async (res) => {
        data.orderDetail = res
        const location = await func.native.getLocation()
        data.stationInfo = await webapi.strategy.find_for_mini({
          gasstationId: res.gasstationId,
          longitude: location.longitude.toString(),
          latitude: location.latitude.toString(),
        })
      })
  },
  async paysel(first) {
    if (store.webapi.strategy.paysel.ing) return
    await webapi.strategy
      .paysel({ orderId: pageParams.value.orderId })
      .then((res) => {
        data.paysel = res
        // 仅“（散户）个人支付”选项 时，保持 其 选中
        if (!res.carrierPay) {
          data.fpayType = 0
        }
      })
      .catch(() => {})
    if (first) {
      data.firstLoad = false
    }
  },
}

ay.entrance(async (args) => {
  methods.getOrderDetail()
  methods.paysel(true)
})

onUnload(() => {
  store.webapi.strategy.get_order_detail.set()
  store.webapi.strategy.paysel.set()
  store.webapi.strategy.find_for_mini.set()
})
</script>

<style lang="scss">
.rebate-detail {
  width: 50%;
  padding: $p-spacd2;
}
.carrier-rebate {
  position: relative;
  z-index: 1;
  display: inline;
  padding: $p-spacd2;
  margin-bottom: 0;
  background: #fff;
  border: 1px solid #ccc;
  border-bottom: 0;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  transform: translateY(1px);
}
.rotater {
  animation: rotate 0.5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
