import Vue from 'vue'
import './SntOrders.scss'
import { mapActions, mapGetters } from 'vuex'
import { VChip, VImg, VDivider, VProgressCircular } from 'vuetify/lib'
import {
  GET_SALEPAGE_ORDERS
} from '../../resources/graphql'

export default Vue.extend({
  name: 'SntOrders',
  components: { VChip, VImg, VDivider, VProgressCircular },
  apollo: {
    orderList: () => ({
      fetchPolicy: 'network-only',
      query: GET_SALEPAGE_ORDERS,
      skip () {
        return !this.isAuth || !this.subdomain
      },
      variables () {
        const filters = {
          domain: this.subdomain,
          customerId: this.customerId
        }
        return this.$_.defaults(filters, this.filters)
      },
      update (data) {
        return data.salePage.findCustomer.orderList
      }
    })
  },
  props: {
    perPage: {
      type: [String, Number],
      default: 12
    }
  },
  data () {
    return {
      orderId: null,
      dialog: false,
      selectedStatus: 'UNCONFIRMED',
      statusList: [
        {
          text: 'ที่ต้องชำระเงิน',
          value: 'UNCONFIRMED'
        },
        {
          text: 'ที่กำลังตรวจสอบ',
          value: 'PENDING'
        },
        {
          text: 'ที่ต้องได้รับ',
          value: 'CONFIRMED'
        },
        {
          text: 'เสร็จสิ้น',
          value: 'DONE'
        },
        {
          text: 'ยกเลิก',
          value: 'CANCELLED'
        }
      ],
      page: 1,
      orderList: {
        nodes: [],
        nodesCount: 0,
        pagesCount: 0
      }
    }
  },
  computed: {
    ...mapGetters({
      subdomain: 'salePage/subdomain',
      customer: 'salePage/customer',
      purchases: 'cart/purchases',
      setPurchases: 'cart/setPurchases'
    }),
    customerId () {
      return this.customer?.id
    },
    isAuth () {
      return !!this.customerId
    },
    isDemo () {
      return !this.subdomain
    },
    isLogin () {
      return !this.isDemo && !this.isAuth
    },
    loading () {
      return this.$apollo.queries.orderList.loading
    },
    filters () {
      return {
        status: this.selectedStatus,
        page: Number(this.page),
        perPage: Number(this.perPage)
      }
    },
    orders () {
      return this.orderList.nodes.map((order) => {
        const daysOfExpire = this.getDaysOfBefore(order.expirationDate)
        const done = order.closedAt ? this.getDaysOfBefore(order.closedAt) <= -7 : false
        const items = []
        const purchases = this.$_.concat(order.purchases, order.setPurchases)
        purchases.forEach((item) => {
          items.push({
            id: item.id,
            name: item.name,
            price: item.price,
            pictureUrl: item.pictureUrl,
            quantity: item.quantity,
            stockAvailable: item.stockAvailable,
            subproduct: item.subproduct,
            productSet: item.productSet,
            isCollection: item.__typename === 'SetPurchase'
          })
        })
        return {
          id: order.id,
          name: order.name,
          invoiceNumber: order.invoiceNumber,
          paymentAccepted: order.paymentAccepted,
          paymentAcceptedAt: order.paymentAcceptedAt,
          price: order.price,
          paidAmount: order.paidAmount,
          outstandingBalance: (order.price - order.paidAmount),
          paymentRejected: order.paymentRejected,
          markTransferredAt: order.markTransferredAt,
          transferredAt: order.transferredAt,
          closed: order.closed,
          closedNote: order.closedNote,
          closedAt: order.closedAt,
          orderBank: order.orderBank,
          orderBankDisplayName: order.orderBankDisplayName,
          cancelled: order.cancelled,
          salePageStatus: order.salePageStatus,
          items,
          daysOfExpire,
          done
        }
      })
    },
    slotProps () {
      return {
        statusItems: this.statusList,
        isSelelectedStatus: this.isSelelectedStatus,
        selectStatus: this.setStatus,
        orderAgain: this.orderAgain,
        filters: this.filters,
        items: this.orders,
        pagesCount: this.orderList.pagesCount,
        itemsCount: this.orderList.nodesCount,
        page: this.page,
        selectPage: this.setPage,
        props: {
          perPage: this.perPage
        }
      }
    }
  },
  watch: {
    customerId () {
      this.selectedStatus = 'UNCONFIRMED'
    }
  },
  methods: {
    ...mapActions({
      setCustomer: 'salePage/setCustomer',
      addToCart: 'cart/addToCart',
      clearCart: 'cart/clearCart'
    }),
    isUnconfirmed (order) {
      return order.salePageStatus === 'UNCONFIRMED'
    },
    isPending (order) {
      return order.salePageStatus === 'PENDING'
    },
    isConfirmed (order) {
      return order.salePageStatus === 'CONFIRMED'
    },
    isDone (order) {
      return order.salePageStatus === 'DONE'
    },
    getDaysOfBefore (expire) {
      if (!expire) {
        return null
      }
      const dateNow = this.$dayjs()
      const expireDate = this.$dayjs(expire)
      return expireDate.diff(dateNow, 'day')
    },
    claim () {
      if (!this.isAuth) {
        this.$router.push({ name: 'SalePage' })
      }
    },
    isSelelectedStatus (item) {
      return this.selectedStatus === item.value
    },
    setStatus (selected) {
      this.setPage(1)
      this.selectedStatus = selected
    },
    orderAgain (order) {
      const outOfStock = order.items.some((item) => {
        if (item.isCollection) {
          return item.stockAvailable < item.quantity
        }
        return item.subproduct.available < item.quantity
      })
      if (!outOfStock) {
        this.clearCart()
        order.items.forEach((item) => {
          let name = item.name
          if (!item.isCollection) {
            if (item.subproduct.name !== 'main') {
              name += ` (${item.subproduct.name})`
            }
          }
          this.addToCart({
            id: item.isCollection ? item.productSet.id : item.subproduct.id,
            name,
            pictureUrl: item.pictureUrl,
            price: item.isCollection ? item.productSet.price : item.subproduct.price,
            available: item.isCollection ? item.productSet.available : item.subproduct.available,
            isCollection: item.isCollection,
            quantity: item.quantity ? Number(item.quantity) : 1
          })
        })
        this.$shipnity.notification.success('คุณเพิ่มสินค้าลงตะกร้าแล้ว')
        this.$router.push({
          name: 'SalePageCart'
        })
      } else {
        this.$shipnity.notification.warning('สินค้าหมดสต็อก')
      }
    },
    setPage (page) {
      this.page = page
    }
  },
  template: `
    <div class="snt-orders">
      <slot v-bind="slotProps">
        <snt-container class="snt-orders__container">
          <slot
            v-bind="slotProps"
            name="headers">
            <div class="snt-orders__title">
              รายการสินค้าของคุณ
            </div>
            <div class="snt-orders-status">
              <template v-for="(item, i) in statusList">
                <v-chip
                  :key="'status-button-'+i"
                  :color="isSelelectedStatus(item) ? 'primary': '#C4C4C4'"
                  :dark="!isSelelectedStatus(item)"
                  class="snt-orders-status__chip"
                  @click="setStatus(item.value)">
                  {{ item.text }}
                </v-chip>
              </template>
            </div>
          </slot>
          <div
            v-if="loading"
            class="text-center">
            <v-progress-circular
              :size="14"
              :width="1"
              color="secondary"
              indeterminate
            />
          </div>
          <slot
            v-else
            v-bind="slotProps"
            name="items">
            <div class="snt-orders__items">
              <div
                v-for="(order, i) in orders"
                :key="'order-'+i"
                class="snt-orders-card">
                <div class="snt-orders-card__title">
                  <span class="mr-4">
                    ออเดอร์ : {{ order.invoiceNumber }}
                  </span>
                  <v-chip
                    v-if="isUnconfirmed(order)"
                    color="#E56060"
                    label
                    dark>
                    <div v-if="order.daysOfExpire > 0">
                      หมดอายุในอีก {{ order.daysOfExpire }} วัน
                    </div>
                    <div v-else>
                      หมดอายุแล้ว
                    </div>
                  </v-chip>
                </div>
                <div class="snt-orders-card__table">
                  <table class="snt-orders__table">
                    <tbody>
                      <tr
                        v-for="(item, j) in order.items"
                        :key="'order-row-'+j">
                        <template v-if="$shipnity.breakpoint.smAndDown">
                          <td style="width: 120px">
                            <v-img
                              :src="item.pictureUrl"
                              :width="120"
                              class="snt-orders__table-image"
                              aspect-ratio="1">
                            </v-img>
                          </td>
                          <td class="pa-2">
                            <div class="snt-orders__table-name mb-1">
                              {{ item.name }}
                            </div>
                            <div>
                              {{ item.price | toLocaleString }} บาท  ({{ item.quantity | toLocaleString }} ชิ้น)
                            </div>
                            <div>
                              รวม {{ item.price * item.quantity | toLocaleString }} บาท
                            </div>
                          </td>
                        </template>
                        <template v-else>
                          <td
                            style="width: 150px;"
                            class="pa-2">
                            <v-img
                              :src="item.pictureUrl"
                              class="snt-orders__table-image"
                              aspect-ratio="1">
                            </v-img>
                          </td>
                          <td
                            style="width: 35%;"
                            class="snt-orders__table-name pa-2">
                            <div style="max-width: 90%;">
                              {{ item.name }}
                            </div>
                          </td>
                          <td class="pa-2">
                            {{ item.price | toLocaleString }} บาท
                          </td>
                          <td
                            style="width: 15%;"
                            class="pa-2">
                            {{ item.quantity | toLocaleString }} ชิ้น
                          </td>
                          <td class="pa-2">
                            รวม {{ item.price * item.quantity | toLocaleString }} บาท
                          </td>
                        </template>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <v-divider />
                <div class="snt-orders-card__footer flex-column flex-md-row">
                  <div class="d-flex align-md-center flex-column flex-md-row mb-4 mb-md-0">
                    <div class="d-flex justify-space-between flex-row flex-md-column mb-4 mb-md-0 mr-2">
                      ราคาสุทธิ
                      <p class="mb-0">
                        {{ order.price | toLocaleString }} บาท
                      </p>
                    </div>
                    <div
                      v-if="order.outstandingBalance > 0"
                      class="snt-orders-outstanding">
                      <v-chip
                        color="error"
                        label
                        small>
                        ยอดค้างชำระ {{ order.outstandingBalance | toLocaleString }}
                      </v-chip>
                    </div>
                    <div
                      v-if="order.paymentRejected"
                      class="snt-orders-incorrect">
                      <v-chip
                        color="warning"
                        label
                        small>
                        หลักฐานโอนเงินไม่ถูกต้อง
                      </v-chip>
                    </div>
                  </div>
                  <snt-spacer />
                  <div class="snt-orders-action">
                    <div>
                      <snt-button
                        :to="{
                          name: 'SalePageOrder',
                          params: { orderId: order.id }
                        }"
                        :outlined="!isPending(order)"
                        class="snt-orders-card__footer-button button--outlined"
                        color="primary"
                        depressed
                        large
                        block>
                        รายละเอียดคำสั่งซื้อ
                      </snt-button>
                    </div>
                    <snt-dialog
                      v-if="isConfirmed(order) && !!order.closedNote"
                      :width="450"
                      :retain-focus="false">
                      <template #activator="{ on }">
                        <snt-button
                          class="snt-orders-card__footer-button button--outlined"
                          color="primary"
                          depressed
                          large
                          block
                          v-on="on">
                          ติดตามพัสดุ
                        </snt-button>
                      </template>
                      <template #default="{ on: { close } }">
                        <snt-tracking :order-id="order.id">
                          <template #header>
                            <span>
                              ติดตามขนส่ง
                            </span>
                            <snt-spacer />
                            <snt-icon
                              icon="mdi-close"
                              @click="close()"/>
                          </template>
                        </snt-tracking>
                      </template>
                    </snt-dialog>
                    <div v-if="isUnconfirmed(order)">
                      <snt-button
                        :to="{
                          name: 'SalePageOrderPayment',
                          params: { orderId: order.id }
                        }"
                        class="snt-orders-card__footer-button"
                        color="primary"
                        depressed
                        large
                        block>
                        แจ้งชำระเงิน
                      </snt-button>
                    </div>
                    <div v-if="isDone(order)">
                      <snt-button
                        class="snt-orders-card__footer-button"
                        color="primary"
                        depressed
                        large
                        block
                        @click="orderAgain(order)">
                        สั่งซื้ออีกครั้ง
                      </snt-button>
                    </div>
                  </div>
                </div>
              </div>
              <div
                v-if="!loading && !orders.length"
                class="snt-orders__not-found">
                <snt-icon
                  icon="mdi-cart-variant"
                  size="64" />
                <div class="snt-orders-not-found">
                  ไม่มีรายการ
                </div>
              </div>
            </div>
          </slot>
          <slot
            v-bind="slotProps"
            name="pagination">
            <template v-if="orderList.pagesCount > 1">
              <snt-pagination
                :value="page"
                :length="orderList.pagesCount"
                :total-visible="7"
                class="snt-all-products__pagination"
                @input="setPage($event)">
              </snt-pagination>
            </template>
          </slot>
        </snt-container>
        <slot
          v-if="isLogin"
          :claim="claim"
          name="login">
          <snt-dialog
            :value="true"
            :width="400"
            @input="claim()">
            <template #default="{ on: { close } }">
              <snt-login
                @submit="(valid) => !valid || close()"
                @click:close="close()">
                <template #header>
                  <span>
                    เข้าสู่ระบบ
                  </span>
                  <snt-spacer />
                  <snt-icon
                    icon="mdi-close"
                    @click="close()"/>
                </template>
              </snt-login>
            </template>
          </snt-dialog>
        </slot>
      </slot>
    </div>
  `
})
