<template>
  <div class="full-height column hotel-list">
    <!-- <hotelCard></hotelCard> -->
    <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-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td style="width:200px;" class="cursor-pointer ListTable-title"
            @click="showHotelDetailHandler(props.row.HotelId)">
            <div class="ellipsis-3-lines" style="padding: 7px 16px;width: 200px;white-space: break-spaces;">
              {{ props.row.HotelName }}
              <!-- <q-tooltip style="padding:none;">
                <hotel-card class="ListTable-show"></hotel-card>
              </q-tooltip> -->
            </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.confirm') }}</div>
            <div class="td-item">{{ $t('hotel.table.limit') }}</div>
          </q-td>
          <q-td v-for="x in props.row.subList"
            @click="x.PriceList[0].CostPrice > 0 ? showOrderSubmitHandler(props.row, x) : ''">
            <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 cursor-pointer">
              {{ x.ConfirmNum }}/{{ x.ReserveNum }}
            </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-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 :title="pageTitle" :rows="hotels" grid :columns="mobileCols" row-key="name"
      card-class="no-shadow bg-primary text-white" :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 @click.stop="showHotelDetailHandler(props.row.HotelId)">
            <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="">
              <span>円{{ props.row.LowerPrice.toFixed(2) }}{{ $t('unit.jp') }} {{ $t('hotel.col.low') }}</span>
            </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" @update:model-value="showOrderSubmitHandler"></hotel-price-list>
    </q-dialog>
    <q-dialog v-model="showOrderPreview" persistent>
      <table-operation :HotelRow="orderSubmitObj" :hotelInfor="orderSubmitItemObj"
        @close="showOrderPreview = false"></table-operation>
    </q-dialog>
    <q-dialog v-model="showHotelDetails" persistent>
      <hotel-details :hotelId="showHotelDetailId"></hotel-details>
    </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 './HotelPriceList.vue'
import TableOperation from "./TableOperation.vue"
import SamplePriceList from './SamplePriceList.vue'
import hotelCard from './hotelCard.vue'
import hotelDetails from './hotelDetails.vue'
export default defineComponent({
  components: { HotelPriceList, TableOperation, SamplePriceList, hotelCard, hotelDetails },
  name: 'list-table',
  setup() {
    const $q = useQuasar()
    const { t } = useI18n()
    const orderstatus = inject(DirtionmaryHelper.HOTEL_CAR_ORDER_STATUS) as any
    const search = inject(DirtionmaryHelper.HOTEL_QUERY_PARAM) as any
    const updateHotel = inject(DirtionmaryHelper.HOTEL_UPDATEHOTEL_CAR) as any
    watch(search, (n, o) => {
      if (data.loading) return
      data.pages.pageIndex = 1
      methods.calcDateRangeCols()
      methods.initHotels()
    })
    watch(updateHotel, (n, o) => {
      if (updateHotel.value.HotelId) {
        data.showOrderPreview = true
        data.orderSubmitItemObj = null
        data.orderSubmitObj = null
      }
      //methods.initHotels()
    })
    watch(orderstatus, (n, o) => {
      if (orderstatus.value == true) {
        methods.initHotels()
        orderstatus.value = false
      }
    })

    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.toFixed(2)}${$t('unit.jp')} ${t('hotel.col.low')}` }
      ],
      showPriceList: false,
      queryHotelObj: {},
      orderSubmitObj: {} as any,
      orderSubmitItemObj: {} as any,
      showOrderPreview: false,
      showHotelDetails: false,
      showHotelDetailId: 0
    })


    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 })
        }
        console.log(data.cols)
      },
      changePageHandler(n: any) {
        console.log(n)
        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
      },
      showOrderSubmitHandler(row: any, col: any) {
        data.orderSubmitObj = row
        data.orderSubmitItemObj = col
        data.showOrderPreview = true
      },
      showHotelDetailHandler(hotelId: number) {
        data.showHotelDetailId = hotelId
        data.showHotelDetails = true
      }
    }
    methods.calcDateRangeCols()
    methods.initHotels()
    return { ...toRefs(data), ...methods }
  }
})
</script>

<style>
.ListTable-title {
  position: relative !important;
}

.ListTable-title:hover .ListTable-show {
  display: block;
}

.ListTable-show {
  /* position: absolute;
  left: 0;
  top:80px;
  z-index: 9999; */
  /* display: none; */
}

.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>
