<template>
  <ay-container :hideIcon="data.hideIcon">
    <ayb-station type="2" :stationInfo="data.stationInfo" />
    <div class="section">加气员</div>
    <div class="s-fz font-bold">
      {{ data.stationInfo.cashierName }} [ 工号：{{ data.stationInfo.no }} ] 为您服务
    </div>

    <div class="chunk" v-if="false">
      <div class="center justify-start">
        <image class="personal" :src="store.user.userInfo.head_url" mode="scaleToFill" />
        <div>
          <div class="p-fz">{{ store.user.userInfo.user_name }}</div>
          <div class="mt-spacd2 s-fz">{{ store.user.userInfo.mobileDes }}</div>
        </div>
      </div>
    </div>
    <div class="station">
      <div class="section">加气量（公斤）</div>
      <uni-easyinput
        v-if="store.user.isLogined"
        v-model="data.gasQty"
        type="digit"
        :clearable="false"
        placeholder="请填写"
        focus
        @input="methods.input"
        @blur="methods.paysel"
        @confirm="methods.paysel"
      />
      <!-- @clear="methods.clear" -->
      <div v-else class="no-login-input s-fz" @click="ay.goLogin()">请填写</div>
      <div class="mt-spac">
        <ay-skeletons
          :rowList="data.rowList"
          :loading="data.fpayType === -1 && store.webapi.strategy.paysel.ing"
        >
          <ay-tabs :tabs="tabs" v-model="data.fpayType" v-show="data.fpayType !== -1">
            <template v-slot:tab0>
              <pay-type :type="0" :paysel-data="personPay" v-model:enjoyRebate="data.enjoyRebate" />
            </template>
            <template v-slot:tab1>
              <pay-type :type="1" :paysel-data="carrierPay" @re-data="methods.paysel" />
            </template>
          </ay-tabs>
        </ay-skeletons>
      </div>
    </div>
    <div class="btns">
      <button type="primary" @click="methods.confirm" :loading="createing" :disabled="noCanPay">
        {{ curPay?.buttonMsg }}
      </button>
    </div>
  </ay-container>
</template>

<script lang="ts" setup>
import payType from './components/payType.vue'

const data = ay.initData({
  input: '',
  rowList: [
    {
      align: 'left',
      colItems: [
        {
          style: {
            width: '30%',
          },
        },
      ],
    },
    ...Array(3).fill({
      align: 'left',
      colItems: 1,
    }),
  ],
  hideIcon: false,
  currentTab: 0,
  stationInfo: {} as GasstationCashierVO对象,
  gasQty: '',
  // 扫小程序码进来时，scene参数的值
  wxCodeScene: '',
  paysel: {} as 待支付订单_可选支付方式获取实体类,
  /** 页面选择支付类型：-1:未呈现 0:个人：1：物流 */
  fpayType: -1,
  /** 享受优惠 */
  enjoyRebate: true,
  /** 原生支付状态 */
  nativePayState: enums.ReqState.unasked,
  /** 加气量已清除 */
  cleared: false,
})
const cashierId = computed(
  () => data.wxCodeScene || pageConfig.value.params?.scene || pageConfig.value.params?.cashierId,
)
const gasQtyNum = computed(() => Number(data.gasQty))
const user = computed(() => store.user.userInfo)
const pageConfig = computed(() => store.curPage.pageConfig)
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,
      amount: data.paysel.personPay.amount,
    }
    if (!data.enjoyRebate) {
      rv.buttonMsg = rv.buttonMsgNoRebate
      rv.amount = rv.allAmount
    }
  }
  if (data.fpayType === 1) {
    rv = data.paysel?.carrierPay
  }
  return rv
})
/** 订单创建中 */
const createing = computed(
  () =>
    // 创建加气订单中
    store.webapi.pay.add_v2.ing ||
    // 订单支付接口请求中
    store.webapi.pay.order_pay.ing,
)
const noCanPay = computed(
  () =>
    // 按钮不可点击
    !curPay.value?.buttonEnable ||
    // 获取待支付订单的可选支付方式中
    store.webapi.strategy.paysel.ing ||
    createing.value ||
    // 订单支付接口请求成功 && 原生未支付失败
    (store.webapi.pay.order_pay.success && data.nativePayState !== enums.ReqState.fail),
)
const tabs = computed(() => {
  const tabs = []
  if (carrierPay.value) {
    tabs.push({ title: '所属物流支付', value: 1 })
  }
  if (personPay.value) {
    tabs.push({ title: '个人支付', value: 0 })
  }
  return tabs
})

const methods = {
  async checkNopayfordriver() {
    const nopayfordriver = await webapi.pay.find_unpayfordriver()
    if (nopayfordriver) {
      ay.goPage(config.pages.order_orderDetail, {
        params: { orderId: nopayfordriver.orderId },
        goPageType: enums.GoPageType.redirectTo,
      })
      return true
    }
    return false
  },

  /** 个人支付-有无优惠切换 */
  switchRebate(checked) {
    data.enjoyRebate = checked
  },
  checkLogin() {
    console.log('checkLogin')
    if (store.user.isLogined) return
    ay.goLogin()
  },
  input() {
    nextTick(() => {
      data.gasQty = data.gasQty.replace(/^\D*(\d*\.{0,1}\d{0,2}).*/, '$1')
    })
  },
  async clear() {
    data.fpayType = -1
    data.cleared = true
    await func.awaiter(100)
    data.cleared = false
  },
  async paysel() {
    // if (data.cleared) {
    //   return
    // }
    if (gasQtyNum.value <= 0) {
      data.fpayType = -1
      data.enjoyRebate = true
      func.native.showToast('加气量需大于零')
      return false
    }
    webapi.strategy
      .paysel({
        cashierId: cashierId.value,
        driverId: user.value.user_id,
        gasQty: gasQtyNum.value,
        creater: user.value.user_id,
        createrName: user.value.user_name,
      })
      .then((res) => {
        data.paysel = res
        if (data.fpayType === -1) {
          if (carrierPay.value) {
            data.fpayType = 1
          } else if (personPay.value) {
            data.fpayType = 0
          }
        }
      })
  },
  async confirm() {
    if (store.webapi.strategy.paysel.ing) return
    if (gasQtyNum.value <= 0) {
      func.native.showToast('加气量需大于零')
      return false
    }
    if (gasQtyNum.value > store.common.data.preferWeight) {
      func.native.showToast('加气量不能超过' + store.common.data.preferWeight)
    }
    // 物流支付-仅创建订单
    if (data.fpayType === 1 && carrierPay.value?.createOnly) {
      methods.createOnly()
    } else {
      methods.pay()
    }
  },
  createOnly() {
    // {
    //     cashierId: pageConfig.value.params.cashierId,
    //     driverId: user.value.user_id,
    //     gasQty: gasQtyNum.value,
    //     gasstationId: pageConfig.value.params.gasstationId,
    //     createRole: 'driver', // 1 平台管理员 2 平台运营人员 filler 加气站企业管理者 cashier 加气员 carrier 物流公司管理者 driver 司机
    //     creater: user.value.user_id,
    //     createrName: user.value.user_name,
    //   }
    webapi.pay.add_v2(data.paysel.gasOrder).then((res) => {
      ay.goPage(config.pages.order_orderDetail, {
        params: data.paysel.gasOrder,
        goPageType: enums.GoPageType.redirectTo,
      })
    })
  },
  async pay() {
    const params: OrderPayParam = {
      // orderId: data.paysel.gasOrder.orderId,
      payType: curPay.value.payType,
      gasOrder: data.paysel.gasOrder,
    }
    // 需要微信支付
    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 === 0) {
      params.personRebate = data.enjoyRebate ? 0 : 1
    }
    // 物流支付
    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)) {
          data.nativePayState = enums.ReqState.ing
          uni.requestPayment({
            ...JSON.parse(res.payInfo),
            success() {
              data.nativePayState = enums.ReqState.success
              methods.paySuccess()
            },
            fail() {
              data.nativePayState = enums.ReqState.fail
              func.native.showToast({
                icon: 'error',
                title: '支付失败',
              })
              // 物流支付失败跳订单详情
              if (data.fpayType === 1) {
                ay.goPage(config.pages.order_orderDetail, {
                  params: data.paysel.gasOrder,
                  goPageType: enums.GoPageType.redirectTo,
                })
              }
            },
          })
        } else {
          methods.paySuccess()
        }
      })
      .catch((err) => {
        if ([3003, 3110].includes(err.res.code)) {
          // 物流支付失败跳订单详情
          if (data.fpayType === 1) {
            ay.goPage(config.pages.order_orderDetail, {
              params: data.paysel.gasOrder,
              goPageType: enums.GoPageType.redirectTo,
            })
          }
        }
      })
  },
  paySuccess() {
    func.native
      .showToast({
        icon: 'success',
        title: '支付成功',
      })
      .then(() => {
        ay.goPage(config.pages.order_orderDetail, {
          params: data.paysel.gasOrder,
          goPageType: enums.GoPageType.redirectTo,
        })
      })
  },
}
ay.entrance(
  async (args) => {
    if (store.user.isLogined) {
      const hasnp = await methods.checkNopayfordriver()
      if (hasnp) return
    }
    data.wxCodeScene = args?.query?.scene
    // 微信扫小程序码进来时，scene参数有值
    if (data.wxCodeScene) {
      // 未登录隐藏返回首页按钮
      data.hideIcon = !store.user.isLogined
    }
    // console.log('params', pageConfig.value.params)
    const location = await func.native.getLocation()
    data.stationInfo = await webapi.strategy.find_by_cashier({
      cashierId: cashierId.value, // '710613333157822464', // '600021999820734464',
      longitude: location.longitude.toString(),
      latitude: location.latitude.toString(),
      driverId: store.user.userInfo.user_id,
    })
  },
  {
    addLoadTypes: [enums.LoadType.onShow],
  },
)
onUnload(() => {
  store.webapi.strategy.paysel.set()
  store.webapi.pay.add_v2.set()
  store.webapi.pay.order_pay.set()
})
</script>

<style lang="scss" scoped>
.personal {
  width: 100rpx;
  height: 100rpx;
  margin-right: $p-spac;
  border-radius: $p-spac;
}
::v-deep .is-input-border {
  border: none;
  border-bottom: 2rpx solid $p-color !important;
  border-radius: 0;
}
.no-login-input {
  padding: 20rpx;
  //font-size: 28rpx;
  color: $gray-color;
  border-bottom: 2rpx solid $p-color;
}
</style>
