import Vue from 'vue'
import './SntOrderDetail.scss'
import { mapActions, mapGetters } from 'vuex'
import { VProgressCircular, VImg } from 'vuetify/lib'
import {
  GET_SALEPAGE_ORDER,
  GET_SALEPAGE_ORDER_CREDITCARD
} from '../../resources/graphql'
import CreditCardForm from '../common/CreditCardForm.vue'

export default Vue.extend({
  name: 'SntOrderDetail',
  components: { CreditCardForm, VProgressCircular, VImg },
  apollo: {
    order: () => ({
      fetchPolicy: 'network-only',
      query: GET_SALEPAGE_ORDER,
      skip () {
        return !this.isAuth
      },
      variables () {
        return {
          domain: this.subdomain,
          customerId: this.customerId,
          orderId: this.orderId
        }
      },
      update ({ salePage }) {
        const order = this.$_.head(salePage.findCustomer?.orderList.nodes || [])
        const purchaseTotalPrice = this.$_.reduce(order.purchases, (sum, item) => sum + (item.price * item.quantity), 0)
        const setPurchaseTotalPrice = this.$_.reduce(order.setPurchases, (sum, item) => sum + (item.price * item.quantity), 0)
        order.totalPrice = purchaseTotalPrice + setPurchaseTotalPrice
        return order
      },
      result () {
        const order = this.order
        this.setCheckout({
          shipping: {
            name: order.shippingType
          },
          paymentMethod: null
        })
        if (this.isDemo) {
          console.group('Order state')
          console.log('order', order)
          console.log('isUnconfirmed', this.isUnconfirmed)
          console.log('isPending', this.isPending)
          console.log('isConfirmed', this.isConfirmed)
          console.log('isDone', this.isDone)
          console.log('isCancelled', this.isCancelled)
          console.groupEnd()
        }
      }
    })
  },
  data () {
    return {
      order: {
        id: null,
        shippingType: '',
        address: '',
        bankAccountId: '',
        customerId: '',
        customer: {

        },
        email: '',
        name: '',
        paymentSlip: '',
        promotionCode: '',
        salePageDomain: '',
        shippop: false,
        taxable: false,
        taxId: '',
        tel: '',
        transferredAt: '',
        purchases: [],
        setPurchases: [],
        totalPrice: 0,
        promoCodeDiscount: 0,
        shippingFee: 0,
        price: 0,
        createdAt: null
      },
      submitting: false,
      creditCard: undefined
    }
  },
  computed: {
    ...mapGetters({
      subdomain: 'salePage/subdomain',
      customer: 'salePage/customer',
      checkout: 'salePage/checkout'
    }),
    isDemo () {
      return !this.subdomain
    },
    items () {
      return this.order ? this.$_.concat(this.order.purchases, this.order.setPurchases) : []
    },
    orderId () {
      return this.$route.params.orderId
    },
    customerId () {
      return this.customer?.id
    },
    isAuth () {
      return !!this.customerId
    },
    loading () {
      return this.$apollo.queries.order.loading
    },
    transferred () {
      return this.order.orderBank && this.order.transferredAt
    },
    paymentMethod () {
      return this.checkout.paymentMethod
    },
    paymentAccepted () {
      return this.$_.eq(this.order.paymentAccepted, true)
    },
    closed () {
      return this.$_.eq(this.order.closed, true)
    },
    cancelled () {
      return this.$_.eq(this.order.cancelled, true)
    },
    isCancelled () {
      return this.order.salePageStatus === 'CANCELLED'
    },
    isUnconfirmed () {
      return this.order.salePageStatus === 'UNCONFIRMED'
    },
    isPending () {
      return this.order.salePageStatus === 'PENDING'
    },
    isConfirmed () {
      return this.order.salePageStatus === 'CONFIRMED'
    },
    isDone () {
      return this.order.salePageStatus === 'DONE'
    },
    valid () {
      return this.paymentMethod !== null
    },
    slotProps () {
      return {
        loading: this.loading,
        order: this.order,
        items: this.items,
        isCancelled: this.isCancelled,
        isUnconfirmed: this.isUnconfirmed,
        isPending: this.isPending,
        isConfirmed: this.isConfirmed,
        isDone: this.isDone,
        valid: this.valid,
        submitting: this.submitting,
        submit: this.submit
      }
    }
  },
  created () {
    if (!this.isDemo) {
      if (!this.isAuth) {
        this.$router.push({ name: 'SalePage' })
      }
    }
  },
  methods: {
    ...mapActions({
      setCheckout: 'salePage/setCheckout'
    }),
    async submitCreditCardForm (payload) {
      if (this.isDemo) {
        return
      }
      const { id } = payload
      const url = window.location.origin
      const orderId = Number(id)
      const resultUrl = `${url}/orders/${orderId}`
      const { data: { salePage } } = await this.$apollo.query({
        fetchPolicy: 'network-only',
        query: GET_SALEPAGE_ORDER_CREDITCARD,
        variables: {
          domain: this.subdomain,
          customerId: this.$shipnity.customerId,
          orderId,
          resultUrl
        }
      })
      const order = this.$_.head(salePage.findCustomer?.orderList.nodes || [])
      if (order) {
        if (order.creditCardFormData) {
          this.creditCard = order.creditCardFormData
          setTimeout(() => {
            this.$refs.creditCardForm.$el.submit()
          }, 1000)
        }
      }
    },
    async submit () {
      if (this.isDemo) {
        return
      }
      if (this.valid) {
        const paymentMethod = this.paymentMethod
        const order = this.order
        if (paymentMethod === 0) {
          this.$router.push({
            name: 'SalePageOrderPayment',
            params: {
              orderId: order.id
            }
          })
        } else if (paymentMethod === 1) {
          this.$router.push({
            name: 'SalePageOrderPayment',
            params: {
              orderId: order.id
            }
          })
        } else if (paymentMethod === 2) {
          this.$router.push({
            name: 'SalePageOrderPayment',
            params: {
              orderId: order.id
            },
            query: {
              method: 'qr'
            }
          })
        } else if (paymentMethod === 3) {
          await this.submitCreditCardForm(order)
        }
      }
    }
  },
  template: `
    <div class="snt-order">
      <slot v-bind="slotProps">
        <div
          v-if="loading"
          class="text-center">
          <v-progress-circular
            :size="14"
            :width="1"
            color="secondary"
            indeterminate
          />
        </div>
        <template v-else>
          <snt-container class="snt-order__container">
            <div class="snt-order__title">
              <slot
                v-bind="slotProps"
                name="header">
                <div>
                  รายละเอียดคำสั่งซื้อ
                </div>
                <span
                  v-if="!isUnconfirmed"
                  class="snt-order__caption">
                  สั่งซื้อเมื่อ {{ order.createdAt | formatTime }}
                </span>
              </slot>
            </div>
            <div class="snt-order__address">
              <slot
                v-bind="slotProps"
                name="address">
                <snt-address v-if="isUnconfirmed" />
                <snt-container
                  v-else
                  class="snt-order-address">
                  <div class="snt-order-address__title">
                    ที่อยู่ในการจัดส่ง
                  </div>
                  <div class="snt-order-address__text">
                    <div>
                      {{ order.customer.name }} {{ order.customer.tel }}
                    </div>
                    <div>{{ order.customer.address }}</div>
                  </div>
                </snt-container>
              </slot>
            </div>
            <div class="snt-order-purchase">
              <slot
                v-bind="slotProps"
                name="items">
                <div class="snt-order-purchase__table">
                  <table>
                    <thead>
                      <tr>
                        <th class="snt-order-purchase__th snt-order-purchase__name">
                          ชื่อสินค้า
                        </th>
                        <th class="snt-order-purchase__th snt-order-purchase__price">
                          ราคา
                        </th>
                        <th class="snt-order-purchase__th snt-order-purchase__amount">
                          จำนวน
                        </th>
                        <th class="snt-order-purchase__th snt-order-purchase__total">
                          <div style="min-width: 80px;">
                            ราคารวม
                          </div>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr
                        v-for="(item, i) in items"
                        :key="'order-table-item-'+i">
                        <td class="snt-order-purchase__td snt-order-purchase__name">
                          <v-img
                            :src="item.pictureUrl"
                            class="snt-order-purchase__image"
                            max-width="100"
                            height="100">
                          </v-img>
                          <div class="d-flex flex-column justify-center">
                            <div class="snt-order-purchase__name-title">
                              {{ item.name }}
                            </div>
                          </div>
                        </td>
                        <td class="snt-order-purchase__td snt-order-purchase__price">
                          {{ item.price | toLocaleStringDecimal }}
                        </td>
                        <td class="snt-order-purchase__td snt-order-purchase__amount">
                          {{ item.quantity | toLocaleString }}
                        </td>
                        <td class="snt-order-purchase__td snt-order-purchase__total">
                          {{ (item.price * item.quantity) | toLocaleStringDecimal }}
                        </td>
                      </tr>
                    </tbody>
                    <tfoot>
                      <tr>
                        <td
                          v-if="!$shipnity.breakpoint.smAndDown"
                          colspan="2">
                        </td>
                        <td class="snt-order-purchase__summary">
                          <div class="snt-order-purchase__summary-text">
                            ราคารวมสินค้าทั้งหมด
                          </div>
                          <div class="snt-order-purchase__summary-text">
                            โค้ดส่วนลด
                            <span
                              v-if="order.promotionCode"
                              class="snt-order-purchase__summary-text-promocode">
                              ( {{ order.promotionCode }} )
                            </span>
                          </div>
                          <div class="snt-order-purchase__summary-text">
                            วิธีการจัดส่ง {{ order.shippingType }}
                          </div>
                          <div class="snt-order-purchase__summary-text">
                            ราคาสุทธิ
                          </div>
                        </td>
                        <td class="snt-order-purchase__total">
                          <div class="snt-order-purchase__summary-text">
                            {{ order.totalPrice | toLocaleStringDecimal }}
                          </div>
                          <div class="snt-order-purchase__summary-text">
                            {{ order.promoCodeDiscount | toLocaleStringDecimal }}
                          </div>
                          <div class="snt-order-purchase__summary-text">
                            {{ order.shippingFee | toLocaleStringDecimal }}
                          </div>
                          <div class="snt-order-purchase__summary-text">
                            {{ order.price | toLocaleStringDecimal }}
                          </div>
                        </td>
                        <td
                          v-if="$shipnity.breakpoint.smAndDown"
                          colspan="2">
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </slot>
            </div>
            <div
              v-if="!isUnconfirmed"
              class="snt-order-status">
              <slot
                v-bind="slotProps"
                name="paymentStatus">
                <div class="snt-order-status__title">
                  สถานะการชำระเงิน
                </div>
                <div>
                  <div
                    v-if="order.markTransferredAt"
                    class="snt-order-status__card mb-6">
                    <div class="d-flex align-center mb-4 mb-md-0">
                      <div class="snt-order-status__card-icon mr-2">
                        <snt-icon
                          icon="mdi-record"
                          color="#4E4E4E" />
                      </div>
                      <div>
                        <div>
                          {{ order.markTransferredAt | formatDateTime }}
                        </div>
                        <div>
                          กำลังตรวจสอบการชำระเงิน
                        </div>
                      </div>
                    </div>
                    <div class="snt-order-status__card-method">
                      <div>จำนวนเงิน {{ order.paidAmount | toLocaleString }} บาท</div>
                      <div>วิธีการชำระเงิน  {{ order.orderBankDisplayName }}</div>
                      <div>วัน/เวลา ที่โอนเงิน {{ order.transferredAt | formatDateTime }}</div>
                      <div
                        v-if="order.paymentAccepted"
                        class="snt-order-status__card-method-badge">
                        ผ่าน
                      </div>
                    </div>
                  </div>
                </div>
                <div
                  v-if="order.paymentAccepted"
                  class="snt-order-status__card">
                  <div class="snt-order-status__card-icon">
                    <snt-icon
                      icon="mdi-record"
                      color="#4E4E4E" />
                  </div>
                  <div>
                    <div v-if="order.paymentAcceptedAt">
                      {{ order.paymentAcceptedAt | formatDateTime }}
                    </div>
                    <div>
                      การชำระเงินเสร็จสิ้น
                    </div>
                  </div>
                </div>
                <div
                  v-if="order.paymentRejected"
                  class="snt-order-status__card">
                  <div class="snt-order-status__card-icon">
                    <snt-icon
                      icon="mdi-record"
                      color="error"/>
                  </div>
                  <span class="error--text"> รายการโอนเงินถูกยกเลิก </span>
                </div>
              </slot>
            </div>
            <div
              v-else
              class="snt-order-payment-methods">
              <slot
                v-bind="slotProps"
                name="paymentMethods">
                <snt-payment-methods />
              </slot>
            </div>
            <snt-spacer />
            <div class="snt-order__action">
              <slot
                v-bind="slotProps"
                name="action">
                <div
                  v-if="isUnconfirmed"
                  class="snt-order-footer">
                  <div class="snt-order-footer__net-price">
                    <div class="snt-order-footer__net-price-title">
                      ราคาสุทธิ
                    </div>
                    <div class="snt-order-footer__net-price-text">
                      {{ order.price | toLocaleString }}
                    </div>
                  </div>
                  <snt-button
                    :loading="submitting"
                    :disabled="!valid"
                    class="snt-order-footer__submit"
                    color="primary"
                    depressed
                    large
                    @click="submit()">
                    ชำระเงิน
                  </snt-button>
                </div>
              </slot>
            </div>
          </snt-container>
        </template>
      </slot>
      <credit-card-form
        ref="creditCardForm"
        :credit-card="creditCard" />
    </div>
  `
})
