<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="col sticky-header-column-table" flat :pagination="pages" :no-data-label="$t('noneData')" :columns="cols">
      <template v-slot:top>
        <div class="row full-width">
          <div class="col"></div>
          <q-btn class="hover q-mr-md" v-for="(item,index) in 2"
          :class="{'bg-blue text-white':pages.sort==index+1,'bg-grey-3':pages.sort!=index+1}" @click="pages.sort=index+1,initHotels()">
            {{index+1==1?$t('v101.scattered.anrenqi'):$t('v101.scattered.anjiage')}}
          </q-btn>
        </div>
      </template>
      <template v-slot:body-cell-hotelName="props">
        <q-td class="cursor-pointer" :props="props" @click="goUrl('/scattered/HotelDetails',props.row)">
          <span>{{props.row.hotelName}}</span>
        </q-td>
      </template>
      <template v-slot:body-cell-reviewRating="props">
        <q-td :props="props">
          <div class="row no-wrap items-center">
              <q-rating v-model="props.row.reviewRating" size="1.5em" color="orange" :max="5"
              icon="star_border"
              icon-selected="star"
              icon-half="star_half" no-dimming readonly />
            <span class="q-ml-xs" v-if="props.row.reviewRating>0">{{props.row.reviewRating}}</span>
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-lowrateBySetCurrency="props">
        <q-td :props="props">
          <span class="q-ml-xs text-orange text-weight-bold fz18" >
            円
            <template v-if="props.row.type==1">
              {{getPrice(props.row.lowrateBySetCurrency)}}
            </template>
            <template v-else>
              {{props.row.lowrateBySetCurrency}}
            </template>
          </span>
          <span class="text-grey-8 q-pl-xs">{{$t('v101.scattered.qi')}}</span>
        </q-td>
      </template>
      <template v-slot:body-cell-type="props">
        <q-td :props="props">
          <span class="q-ml-xs text-green-4 fz14" >
            {{props.row.type==2?$t('v101.scattered.ziying'):$t('v101.scattered.jalan')}}
          </span>
        </q-td>
      </template>
      <template v-slot:body-cell-hotelFeaturesMask="props">
        <q-td :props="props">
          <span v-for="(subItem,index) in props.row.hotelFeaturesMask" :key="index">
            <span class="rounded-borders bg-blue-1 text-blue q-mr-xs q-px-sm q-py-xs" v-if="subItem">
              {{subItem==1?themeList[index].name:''}}
          </span>
          </span>
        </q-td>
      </template>
      <template v-slot:bottom>
        <q-pagination class="full-width justify-end" v-model="pages.displayFrom" color="primary" :max="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:top>
        <div class="row full-width">
          <div class="col"></div>
          <q-btn class="hover q-mr-md" v-for="(item,index) in 2"
          :class="{'bg-blue text-white':pages.sort==index+1,'bg-grey-3':pages.sort!=index+1}" @click="pages.sort=index+1,initHotels()">
            {{index+1==1?$t('v101.scattered.anrenqi'):$t('v101.scattered.anjiage')}}
          </q-btn>
        </div>
      </template>
    <template v-slot:item="props">
      <div @click="goUrl('/scattered/HotelDetails',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('v101.scattered.titleHeard1')}}</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('v101.scattered.titleHeard2')}}</div>
          <div style="font-size: 13px;">
            <q-rating v-model="props.row.reviewRating" size="1.5em" color="orange" :max="5"
            icon="star_border"
            icon-selected="star"
            icon-half="star_half" no-dimming readonly />
          <span class="q-ml-xs" v-if="props.row.reviewRating>0">{{props.row.reviewRating}}</span>
          </div>
        </div>
        <div>
          <div style="opacity: 0.54;font-weight: 500;font-size: 12px;margin-bottom: 4px;">{{$t('v101.scattered.titleHeard3')}}</div>
          <div class="">
            <span>円
              <template v-if="props.row.type==1">
                {{getPrice(props.row.lowrateBySetCurrency)}}
              </template>
              <template v-else>
                {{props.row.lowrateBySetCurrency}}
              </template>
            </span>
            <span class="q-pl-xs">{{$t('v101.scattered.qi')}}</span>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:bottom>
        <q-pagination class="full-width justify-end" v-model="pages.displayFrom" color="primary" :max="pageCount" :input="true" @update:model-value="changePageHandler" />
      </template>
    </q-table>
  </div>
</template>

<script lang="ts">
import { useRouter } from 'vue-router'
import HotelService from '../../../api/scattered'
import { DirtionmaryHelper } from '../../../config/dictionary'
import message from '../../../utils/message'
import { defineComponent, inject, reactive, toRefs, watch } from 'vue'
import { date,useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { HotelArea, useHotel } from '../../../utils/hotelRate'
export default defineComponent({
  components: { },
  name: 'list-table',
  setup() {
    const $q=useQuasar()
    const { t } = useI18n()
    const search = inject(DirtionmaryHelper.HOTEL_QUERY_PARAM) as any
    const $router = useRouter()
    watch(search, (n, o) => {
      if (data.loading) return
      search.displayFrom = 1
      methods.initHotels()
    })

    const data = reactive({
      groupBookingFlg: '' as any,
      JapanIncrease: '' as any,
      travelLngLat: [] as Array<any>,//地图坐标
      themeList: [] as Array<HotelArea>,
      hotels: [] as Array<any>,
      loading: false,
      cols: [
        { name: 'hotelName', label: t('v101.scattered.titleHeard1'), align: 'left' },
        { name: 'reviewRating', label: t('v101.scattered.titleHeard2'), field: (row: any) => (row.reviewRating), align: 'left' },
        { name: 'lowrateBySetCurrency', label: t('v101.scattered.titleHeard3'), align: 'left' },
        { name: 'type', label: t('v101.scattered.titleHeard4'), field: (row: any) => row.type==2?t('v101.scattered.ziying'):t('v101.scattered.jalan'), align: 'left' },
        { name: 'hotelFeaturesMask', label: t('v101.scattered.titleHeard5'), align: 'left' },
        { name: 'address', label: t('v101.scattered.titleHeard6'), field: (row: any) => (row.address), align: 'left' },
      ] as any,
      pages: {
        displayFrom: 1,//页数
        numberOfResults: 12,
        rowsPerPage: 15,
        sort: 1
      },
      pageCount: 0,
      pageTitle: '' as (string | undefined),
      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,
      showHotelDetailId: 0,
      
    })
    data.themeList = useHotel.getHotelTheme()
    data.pageTitle = inject(DirtionmaryHelper.PAGE_TITLE_KEY)


    const methods = {
      initHotels() {
        data.loading = true
        data.hotels = []
        let dataList = [];
        data.travelLngLat = [];
        let param = Object.assign(data.pages, search)
        HotelService.GetJAPANHotelList(param)
          .then(r => {
            if (r.data.data.parmResult && r.data.data.parmResult.hotelSummary) {
                dataList = r.data.data.parmResult.hotelSummary;
            }
            var ourHotelList = r.data.data.ourHotelList;
            if (ourHotelList && ourHotelList.length > 0) {
                ourHotelList.forEach(x => {
                    x.type = 2
                })
            }
            if (dataList && dataList.length > 0) {
                //获取酒店坐标
                dataList.forEach(x => {
                    x.reviewRating = parseFloat(x.reviewRating);
                    x.lowrateBySetCurrency = parseFloat(x.lowrateBySetCurrency);
                    let obj = {
                        lat: x.latitudeW,
                        lng: x.longitudeW,
                        name: x.hotelName
                    }
                    data.travelLngLat.push(obj);
                    x.type = 1
                })
            }
            data.hotels = ourHotelList.concat(dataList);
            data.hotels.forEach(x=>{
                if(isNaN(x.reviewRating)){
                    x.reviewRating=0
                }
                x.hotelFeaturesMask = x.hotelFeaturesMask.split(',')
            })
            //按价格升序
            if(data.pages.sort==2){
              data.hotels.sort(methods.getSortFun('asc', 'lowrateBySetCurrency'));    
            }
            //按照星级降序
            if(data.pages.sort==1){
              data.hotels.sort(methods.getSortFun('desc', 'reviewRating'));    
            }
            let jalanTotalCount = 0
            if (r.data.data.parmResult && r.data.data.parmResult.numberOfResultMatched) {
                jalanTotalCount = r.data.data.parmResult.numberOfResultMatched;
            }

            let ourHotelTotalCount = 0;
            if (ourHotelList && ourHotelList.length > 0) {
                ourHotelTotalCount = ourHotelList[0].totalHotelCount;
            }
            let totalCount = Number(jalanTotalCount) + Number(ourHotelTotalCount);
            data.pageCount = r.data.data.parmResult.numberOfResultMatched
            data.groupBookingFlg = r.data.data.parmResult.groupBookingFlg;
            data.JapanIncrease = r.data.data.parmResult.JapanIncrease;
            data.loading = false
          })
          .catch(e => {
            data.loading = false
          })
      },
      //数组排序
      getSortFun(order, sortBy) {
        var ordAlpah = (order == 'asc') ? '>' : '<';
        var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
        return sortFun;
      },
      //获取价格
      getPrice(price) {
        return Math.ceil(price / data.JapanIncrease);
      },
      changePageHandler(n: any) {
        data.pages.displayFrom = n
        methods.initHotels()
      },
      showHotelDetailHandler(hotelId:number){
        data.showHotelDetailId=hotelId
      },
      goUrl(url:string,row: {}){
        url = `${url}/${row.hotelId}/${data.groupBookingFlg}/${row.type==1?methods.getPrice(row.lowrateBySetCurrency):row.lowrateBySetCurrency}`
        window.open(url, '_blank')
        // $router.push({ path:url })
      },
    }
    methods.initHotels()
    return { ...toRefs(data), ...methods }
  }
})
</script>

<style>

</style>
