<template>
  <div class="p-fill-order">
    <h3 class="ptc-title">Fill Order</h3>
    <component :is="Component" @go="go" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { initProducts } from './store'

export default defineComponent({
  name: 'FillOrder',
  beforeRouteEnter(to, from, next) {
    initProducts().then(next)
  },
})
</script>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import StepOne from './StepOne.vue'
import StepTwo from './StepTwo.vue'
import StepThree from './StepThree.vue'
import { state, resetState, getModelList } from './store'
import { state as rootState, getCurrentOrder } from '@/store'
import { getDiscountInfo } from '@/service/order'

const step = ref(0)
const Component = computed(() => [StepOne, StepTwo, StepThree][step.value])
const { from, invitee, renewal, pid } = useRoute().query as any

state.form.from = from || (renewal ? 'renew' : '')
state.form.invitor = invitee || ''
if (pid && state.productList.some(v => v.id === +pid)) {
  state.form.product_id = +pid
}
if (renewal) {
  state.form.renewal = +renewal
  getCurrentOrder(renewal).then(() => {
    const order = rootState.currentOrder
    if (state.productList.some(item => item.id === +order.product_id)) {
      state.form.product_id = +order.product_id
    }
    state.form.subscribe_type = +order.subscribe_type === 1 ? 'month' : 'year'
    state.form.brand_id = +order.brand_id
    state.form.phone_id = +order.phone_id
    getModelList()
  })
}

const { orders = [], num_order_expired = 0 } = rootState.userInfo || {}
const discountType =
  orders.length || num_order_expired > 0
    ? '3'
    : ({ admin: '1', member: '2', renew: '3' } as any)[state.form.from]
if (discountType) {
  getDiscountInfo(discountType).then(
    ({ results }) =>
      (state.discount = {
        name: ['店员折扣', '新人折扣', '多次购买折扣'][discountType - 1],
        discount_amount: results.amount,
      })
  )
}
// 此处不直接传入resetState是有必要的，否则resetState在整个应用生命周期只会执行一次
onUnmounted(() => resetState())

watch(step, () => window.scrollTo(0, 0))

function go(delta = 1) {
  step.value += delta
}
</script>

<style lang="scss">
.p-fill-order {
  background: #f7f7f7;

  .detail {
    display: flex;
    align-items: flex-end;
    .s1,
    .s2 {
      font-size: 40px;
      font-weight: bold;
      color: #1a1a1a;
    }
    .s2 {
      margin: 0 20px 0 48px;
    }
    .s3 {
      margin-right: 48px;
      font-size: 28px;
      color: #1a1a1a;
    }
    .s4 {
      margin-left: auto;
      font-size: 32px;
      font-weight: bold;
      color: $primary-color;
      cursor: pointer;
    }
  }
}
</style>
