<template>
  <div class="full-height column hotel-list">
    <q-table v-if="$q.platform.is.desktop" :loading="loading" :rows="hotels" :loading-label="$t('loading')"
      class="sticky-column-table col sticky-header-column-table hotel-table" flat :pagination="pages"
      :no-data-label="$t('noneData')">
      <template v-slot:top>
        <div class="row full-width">
          <div class="col"></div>
          <div class="flex items-center q-ml-md" v-for="x in dateTypes">
            <div class="cos-item-icon rounded-border q-mr-sm" :class="[x.bg]"></div>
            <span class="f12">{{ x.text }}</span>
          </div>
        </div>
      </template>
      <template v-slot:header>
        <q-tr>
          <q-th>{{ $t('hotel.col.first') }}</q-th>
          <q-th>{{ $t('hotel.col.second') }}</q-th>
          <q-th v-for="(x, i) in cols">
            {{ x }}
          </q-th>
          <q-th>{{ $t('hotel.addRoomBtn') }}</q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td style="width:200px">
            <div class="ellipsis-3-lines" style="padding: 7px 16px;width: 200px;white-space: break-spaces;">{{
              props.row.HotelName
            }}</div>
          </q-td>
          <q-td>
            <div class="td-item">{{ $t('hotel.table.price') }}</div>
            <div class="td-item">{{ $t('hotel.table.ins') }}</div>
            <div class="td-item">{{ $t('hotel.table.limit') }}</div>
          </q-td>
          <q-td v-for="x in props.row.subList">
            <template v-if="x.PriceList && x.PriceList.length > 0">
              <div class="td-item cursor-pointer" :class="[x.PriceList[0].ins.bg, x.PriceList[0].ins.color]">
                {{ x.PriceList[0].CostPrice }}
                <q-tooltip>
                  <sample-price-list :price="x"></sample-price-list>
                </q-tooltip>
              </div>
            </template>
            <div class="td-item bg-dark" v-else></div>
            <div class="td-item cursor-pointer">
              {{ x.Inventory }}/{{ x.UseInventory }}/{{ x.RemainingInventory }}
            </div>
            <div class="td-item" :class="{ 'bg-red-9 text-white': x.UseInventory - x.Inventory > 0 }">
              <span v-if="x.UseInventory - x.Inventory > 0">
                {{ x.UseInventory - x.Inventory }}
              </span>
            </div>
          </q-td>
          <q-td class="text-center" style="border-left:1px solid #eee;">
            <q-btn color="primary" :label="$t('hotel.addRoom')" size="sm" outline @click="finishHanler(props.row)" />
          </q-td>
        </q-tr>
      </template>
      <template v-slot:bottom>
        <q-pagination class="full-width justify-end" v-model="pages.pageIndex" color="primary" :max="pages.pageCount"
          :input="true" @update:model-value="changePageHandler" />
      </template>

    </q-table>
    <q-table hide-header v-else :rows="hotels" grid :columns="mobileCols" row-key="name"
      card-class="no-shadow bg-primary text-white col" :pagination="pages" :loading="loading">
      <template v-slot:item="props">
        <div @click="viewHotelPriceListHandler(props.row)" class="rounded-borders bg-primary text-white col-12 q-mb-sm"
          style="padding: 12px;margin-left: 12px;margin-right: 12px; width: calc(100% - 24px);">
          <div>
            <div style="opacity: 0.54;font-weight: 500;font-size: 12px;margin-bottom: 4px;">{{ $t('hotel.col.first') }}
            </div>
            <div style="font-size: 13px;">{{ props.row.HotelName }}</div>
          </div>
          <div class="q-my-md">
            <div style="opacity: 0.54;font-weight: 500;font-size: 12px;margin-bottom: 4px;">{{ $t('hotel.col.three') }}
            </div>
            <div style="font-size: 13px;">{{ props.row.TotalInventory }}</div>
          </div>
          <div>
            <div style="opacity: 0.54;font-weight: 500;font-size: 12px;margin-bottom: 4px;">{{ $t('hotel.col.four') }}
            </div>
            <div class="row items-center justify-between">
              <span>円{{ props.row.LowerPrice.toFixed(2) }}{{ $t('unit.jp') }} {{ $t('hotel.col.low') }}</span>
              <q-btn color="grey-3" :label="$t('hotel.addRoom')" size="sm" outline @click="finishHanler(props.row)" />
            </div>
          </div>
        </div>
      </template>
      <template v-slot:bottom>
        <q-pagination class="full-width justify-end" v-model="pages.pageIndex" color="primary" :max="pages.pageCount"
          :input="true" @update:model-value="changePageHandler" />
      </template>
    </q-table>
    <q-dialog v-model="showPriceList">
      <hotel-price-list :hotel="queryHotelObj"></hotel-price-list>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { ApiResult } from '../../../@types/enumHelper'
import HotelService from '../../../api/hotel'
import { DirtionmaryHelper } from '../../../config/dictionary'
import message from '../../../utils/message'
import { defineComponent, inject, reactive, toRefs, watch } from 'vue'
import { date, useQuasar } from 'quasar'
import { DateType, getDateType, getDayOfWeek } from '../../../utils/tools'
import { useI18n } from 'vue-i18n'
import HotelPriceList from '../list/HotelPriceList.vue'
import SamplePriceList from '../list/SamplePriceList.vue'
export default defineComponent({
  components: { HotelPriceList, SamplePriceList },
  name: 'list-table',
  emits: ['finish'],
  setup(props, context) {
    const $q = useQuasar()
    const { t } = useI18n()
    const search = inject(DirtionmaryHelper.HOTEL_QUERY_PARAM) as any
    watch(search, (n, o) => {
      if (data.loading) return
      data.pages.pageIndex = 1
      methods.calcDateRangeCols()
      methods.initHotels()
    })

    const data = reactive({
      hotels: [] as Array<any>,
      loading: false,
      cols: [] as Array<string>,
      pages: {
        pageIndex: 1,
        pageSize: 10,
        pageCount: 0,
        rowsPerPage: 10
      },
      pageTitle: '' as (string | undefined),
      dateTypes: [] as Array<DateType>,
      mobileCols: [
        { name: 'HotelName', label: t('hotel.col.first'), field: (row: any) => row.HotelName },
        { name: 'TotalInventory', label: t('hotel.col.three'), field: (row: any) => row.TotalInventory },
        { name: 'LowerPrice', label: t('hotel.col.four'), field: (row: any) => row.LowerPrice }
      ],
      showPriceList: false,
      queryHotelObj: {}
    })


    data.dateTypes = getDateType()
    data.pageTitle = inject(DirtionmaryHelper.PAGE_TITLE_KEY)


    const methods = {
      initHotels() {
        data.loading = true
        data.hotels = []
        let param = Object.assign(data.pages, search)
        HotelService.GetHotelList(param)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              r.data.data.pageData.forEach((x: any) => {
                x.subList.forEach((y: any) => {
                  y.PriceList.forEach((z: any) => {
                    z.ins = methods.getDateTypeById(z.InventoryType)
                  })
                  let cd = new Date(y.DateStr)
                  y.FormatDate = `${date.formatDate(cd, 'MM/DD')} (${getDayOfWeek(date.getDayOfWeek(cd))})`
                })
                if ($q.platform.is.mobile) {
                  x.LowerPrice = methods.calcLowerPrice(x)
                }
              })

              data.hotels = r.data.data.pageData
            } else {
              message.errorMsg(r.data.message)
            }
            data.pages.pageCount = r.data.data.pageCount
            data.loading = false
          })
          .catch(e => {
            message.errorMsg(e.message)
            data.loading = false
          })
      },
      calcDateRangeCols() {
        data.cols = []
        let dateBegin = new Date(search.StartDate)
        const dateEnd = new Date(search.EndDate)
        while (dateBegin <= dateEnd) {
          data.cols.push(`${date.formatDate(dateBegin, 'MM/DD')} (${getDayOfWeek(date.getDayOfWeek(dateBegin))})`)
          dateBegin = date.addToDate(dateBegin, { days: 1 })
        }
      },
      changePageHandler(n: any) {
        data.pages.pageIndex = n
        methods.initHotels()
      },
      getDateTypeById(id: number) {
        return data.dateTypes.find(x => x.id == id)
      },
      calcLowerPrice(hotel: any) {
        let lower = 0
        hotel.subList.forEach((x: any) => {
          if (x.PriceList && x.PriceList.length > 0) {
            x.PriceList.forEach((y: any) => {
              if (y.CostPrice > lower) lower = y.CostPrice
            })
          }
        })
        return lower
      },
      viewHotelPriceListHandler(row: any) {
        data.queryHotelObj = row
        data.showPriceList = true
      },
      finishHanler(hotel: any) {
        context.emit('finish', hotel)
      }
    }
    methods.calcDateRangeCols()
    methods.initHotels()
    return { ...toRefs(data), ...methods, search }
  }
})
</script>

<style>
.cos-item-icon {
  width: 14px;
  height: 14px;
  border-radius: 4px;
}

.td-item {
  width: 100%;
  height: 35px;
  line-height: 35px;
  font-size: 13px;
  font-family: 'Microsoft YaHei' !important;
  color: var(--q-dark);
  text-align: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.12);
}

.td-item:last-child {
  border-bottom: none;
}

.hotel-table .q-table td {
  padding: 0 !important;
}

/* .td-item.cursor-pointer:hover{
    color: var(--q-primary) !important;
  } */
</style>
