<template>
  <q-card flat class="q-pa-lg" style="shadow: 0px 0px 50px 0px rgba(82, 63, 105, 0.15);"
    :style="{ 'width': $q.platform.is.desktop ? '50vw' : '100vw' }">
    <div class="q-mb-xs">
      <div class="" :class="{ 'row items': $q.platform.is.desktop }">
        <span class="text-primary text-h6 col">{{ parameters.HotelName }}</span>
        <div class="f12" :class="{ 'q-mt-sm': $q.platform.is.mobile }">
          <span class="q-mr-md">
            <q-icon name="check" size="18px" color="primary" v-if="parameters.PriceIsBreakfast == 1" />
            <q-icon name="close" size="18px" color="negative" v-else />
            {{ $t('dinner.a') }}
          </span>
          <span class="">
            <q-icon name="check" size="18px" color="primary" v-if="parameters.PriceIsDinner == 1" />
            <q-icon name="close" size="18px" color="negative" v-else />
            {{ $t('dinner.c') }}
          </span>
        </div>
      </div>
      <div class="q-my-md rounded-borders q-pa-sm bg-yellow-1 row items-center justify-between">
        <q-field stack-label :label="$t('hotel.inHouseDate')" class="text-primary" standout dense>
          <template v-slot:control>
            <div class="self-center no-outline text-yellow-10" tabindex="0">{{ joinHouse.dateRangeFormat }}</div>
          </template>
          <!-- <q-popup-proxy :offset="[0, 10]" ref="qDateProxyOpera">
            <q-date v-model="joinHouse.dateRange" :options="optionsFn" range mask="YYYY/MM/DD" landscape @range-end="dateRangeHandler"></q-date>
          </q-popup-proxy> -->
        </q-field>
        <span class="text-grey-6 f12">
          {{ $t('hotel.inhouseDays') }}
          <span class="din text-yellow-10">{{ joinHouse.days }}</span>
          {{ $t('unit.night') }}
        </span>
      </div>
    </div>
    <div class="f12 text-negative q-mb-md">{{ $t('hotel.waringTips') }}</div>
    <div class="rounded-borders" style="max-height: 35vh; overflow-y: auto"
      :class="{ 'bg-grey-1': $q.platform.is.desktop, 'q-px-md': $q.platform.is.desktop, 'q-py-sm': $q.platform.is.desktop, }">
      <template v-for="(item, index) in parameters.DetailList">
        <div class="row no-wrap items-center q-py-sm"
          :style="{ 'border-top': index > 0 && !item.Tips && $q.platform.is.desktop ? '1px dashed #ddd' : '' }"
          :class="{ 'HotelTableOperation': $q.platform.is.mobile, 'q-px-md': $q.platform.is.mobile, 'q-mb-md': $q.platform.is.mobile }">
          <div
            :class="{ 'row': $q.platform.is.desktop, 'col-5': $q.platform.is.desktop, 'q-pr-md': $q.platform.is.mobile, 'col-6': $q.platform.is.mobile, 'column': $q.platform.is.mobile }">
            <div :class="{ 'q-pr-md': $q.platform.is.desktop, 'col-4': $q.platform.is.desktop, }">
              <div class="f12">{{ item.RoomName }}</div>
            </div>
            <div class="text-negative f12" :class="{ 'col-6': $q.platform.is.desktop, 'q-pt-sm': $q.platform.is.mobile }">
              <span class="fz10">円</span>
              <span class="din">{{ item.UPriceFormat }}</span>
              <span class="text-dark" style="font-size: 12px">/{{ $t('unit.ren') }}</span>
            </div>
          </div>
          <div
            :class="{ 'row': $q.platform.is.desktop, 'col': $q.platform.is.desktop, 'q-pl-md': $q.platform.is.desktop, 'column': $q.platform.is.mobile }">
            <div :class="{ 'col-7': $q.platform.is.desktop }">
              <q-input style="width: 100%" @update:model-value="changePeople" v-model="item.PeopleNumber" class="col"
                :class="{ 'q-mr-md': $q.platform.is.desktop, 'q-px-sm': $q.platform.is.desktop, 'q-pl-sm': $q.platform.is.desktop, }"
                mask="#" reverse-fill-mask dense standout :label="$t('hotel.shopping.peopleNum')">
                <template v-slot:prepend>
                  <q-btn color="primary" size="sm" class="q-px-none" flat icon="remove" @click="addPeople(item, 0)" />
                </template>
                <template v-slot:append>
                  <q-btn color="primary" size="sm" class="q-px-none" flat icon="add" @click="addPeople(item, 1)" />
                </template>
              </q-input>
            </div>
            <div
              :class="{ 'col': $q.platform.is.desktop, 'text-center': $q.platform.is.desktop, 'text-right': $q.platform.is.mobile, }">
              <span class="f12 text-grey-6">
                {{ $t('hotel.yg') }}<span class="din text-yellow-10">{{ item.Number }}</span> {{ $t('unit.jf') }}
              </span>
            </div>
          </div>
        </div>
      </template>
    </div>
    <div class="q-pt-md" :class="{ 'row': $q.platform.is.desktop, 'items-center': $q.platform.is.desktop, 'justify-between': $q.platform.is.desktop, 'column': $q.platform.is.mobile }
    ">
      <div>
        <div class="text-grey-6 fz12 row items-center">
          <div class="q-mr-lg">
            {{ $t('hotel.shopping.only') }}
            <span class="text-orange-14 fz14 q-px-xs">{{ onlyNum }}</span>
            {{ $t('hotel.shopping.between') }}
          </div>
          <div v-if="total > 0" class="q-pr-md f12">
            <span>{{ $t('hotel.shopping.TheSelected') }}</span>
            <span class="text-red q-px-sm">{{ sumPeople }}</span>
            <span>{{ $t('unit.ren') }}</span>
            <span class="text-red q-px-sm">{{ total }}</span>
            <span>{{ $t('hotel.shopping.between') }}</span>
          </div>
        </div>
        <div class="q-mt-sm rounded-borders bg-orange-1 text-orange-10 f12 q-pa-sm" v-if="(total - onlyNum) > 0">
          {{ $t('hotel.outbind') }}
        </div>
      </div>
      <div class="row"
        :class="{ 'items-center': $q.platform.is.desktop, 'q-pl-md': $q.platform.is.desktop, 'justify-end': $q.platform.is.mobile, 'q-pt-md': $q.platform.is.mobile }">
        <div>
          <q-btn flat dense color="dark" :label="$t('close')" class="q-mr-sm" @click="editor = {}" v-close-popup />
          <q-btn unelevated dense color="negative" :disable="total == 0" icon="shopping_cart"
            :label="$t('hotel.car.addShopping')" @click="join" />
        </div>
      </div>
    </div>
  </q-card>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRef, toRefs, provide, onMounted, inject, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { DirtionmaryHelper } from '../../../config/dictionary'
import { date } from 'quasar'
import message from '../../../utils/message'
import { moneyFormat, dateDiffer } from '../../../utils/tools'
export default defineComponent({
  props: {
    HotelRow: {
      type: Object,
      require: false
    },
    hotelInfor: {
      type: Object,
      require: false
    }
  },
  emits: ['close'],
  setup(props, context) {
    const { t } = useI18n()
    const qDateProxyOpera = ref<any>(null)
    const HotelLength = inject(DirtionmaryHelper.HOTEL_CAR_ORDER_LENGTH) as any
    const cars = inject(DirtionmaryHelper.HOTEL_CAR_LIST) as any
    // cars&&cars.value.forEach((item:any,index:Number) => {
    //   if(dateDiffer(item.Date)<15){
    //     cars.value.splice(index,1)
    //   }
    // });
    HotelLength.value = cars.value.length
    const editor = inject(DirtionmaryHelper.HOTEL_UPDATEHOTEL_CAR) as any
    const data = reactive({
      HotelRow: {} as any,
      hotelInfor: {} as any,
      onlyNum: 0,
      parameters: {
        HotelId: '',
        HotelName: '',
        Date: '',
        RemainingInventory: '',
        total: 0,
        Money: 0,
        DetailList: [] as Array<any>,
        Remark: '',
        TaxesPrice: 0,
        PriceInTangTax: 0,
        PriceIsBreakfast: 0,
        PriceIsDinner: 0
      },
      total: 0,
      joinHouse: {
        StartDate: '',
        EndDate: '',
        dateRange: [] as Array<any>,
        dateRangeFormat: '',
        days: 1
      },
      sumPrice: 0,
      sumPeople: 0
    })

    watch(
      () => props.HotelRow,
      (o, n) => {
        data.HotelRow = props.HotelRow
        data.hotelInfor = props.hotelInfor
        methods.setList()
      }
    )

    //   今天购买数量
    watch(data.parameters, (n, o) => {
      methods.calculateNum()
    })
    const methods = {
      addPeople(item: any, type: any) {
        // && item.Number < data.hotelInfor.RemainingInventory
        if (type == 1) {
          item.PeopleNumber++
        } else if (type == 0 && item.PeopleNumber > 1) {
          item.PeopleNumber--
        }
        item.PeopleNumber = item.PeopleNumber != '' ? item.PeopleNumber : '0'
        methods.calculateNum()
      },
      changePeople(val: string) {
        setTimeout(() => {
          methods.calculateNum()
        }, 50)
      },
      // 计算房间数量
      calculateNum() {
        data.total = 0
        data.sumPeople = 0
        data.parameters.DetailList.forEach(item => {
          item.Number = Math.ceil(parseFloat(item.PeopleNumber) / parseFloat(item.LimitGuestNum))
          data.total += item.Number
          data.sumPeople += parseInt(item.PeopleNumber)
        })
      },
      join() {
        const temp = JSON.parse(JSON.stringify(data.parameters))
        temp.Money = 0
        temp.Total = data.total
        temp.SumPeople = data.sumPeople
        temp.DetailList = temp.DetailList.filter(((x: any) => x.PeopleNumber > 0))
        temp.DetailList.forEach((x: any) => {
          temp.Money += (x.PeopleNumber * (x.Unit_Price + x.TaxesPrice + x.PriceInTangTax))
        });
        let existsIndex = cars.value.findIndex((x: any) => x.Date == temp.Date)

        let exists = existsIndex == -1 ? null : cars.value[existsIndex]
        if (exists) {
          let existsHotel = exists.Hotels.findIndex((h: any) => h.HotelId == temp.HotelId)
          if (existsHotel != -1) exists.Hotels.splice(existsHotel, 1)
        } else {
          exists = {
            Date: temp.Date,
            Hotels: [] as Array<any>
          }
          cars.value.push(exists)
        }
        exists.Hotels.push(temp)
        cars.value.sort((x: any, y: any) => {
          return new Date(x.Date).getTime() - new Date(y.Date).getTime()
        })
        HotelLength.value = cars.value.length
        message.successMsg(t('success'))
        editor.value = {}
        context.emit('close')
      },
      // 组装可选房间
      setList() {

        data.parameters.DetailList = [] as Array<any>
        let roomTyps = ['CostPrice', 'BidroomPrice', 'SingleroomPrice', 'AddBedPrice', 'GuideRoomPrice']
        let roomLangs = [t('hotel.rooms.normal'), t('hotel.rooms.big'), t('hotel.rooms.sing'), t('hotel.rooms.three'), t('hotel.rooms.driver')]
        let tips = ['', t('hotel.bigTips'), '', '', '']
        let limitGuestNum = [2, 1, 1, 3, 1]
        let tempPrice = data.hotelInfor.PriceList[0]
        let hotel = data.hotelInfor
        data.parameters.HotelId = data.HotelRow.HotelId
        data.parameters.HotelName = data.HotelRow.HotelName
        data.parameters.Date = hotel.DateStr
        data.parameters.RemainingInventory = hotel.RemainingInventory
        data.parameters.TaxesPrice = tempPrice.TaxesPrice
        data.parameters.PriceInTangTax = tempPrice.PriceInTangTax
        data.parameters.PriceIsBreakfast = tempPrice.PriceIsBreakfast
        data.parameters.PriceIsDinner = tempPrice.PriceIsDinner

        methods.setDateRange()
        roomTyps.forEach((x: any, i: number) => {
          if (tempPrice[x] > 0) {
            let dataMsg = {
              HotelId: data.HotelRow.HotelId,
              Date: hotel.DateStr,
              RoomType: i + 1,
              RoomName: roomLangs[i],
              Unit_Price: tempPrice[x],
              UPriceFormat: moneyFormat(tempPrice[x]),
              LimitGuestNum: limitGuestNum[i],
              Tips: tips[i],
              Number: 0,
              PeopleNumber: 0,
              Destription: '',
              TaxesPrice: tempPrice.TaxesPrice,
              PriceInTangTax: tempPrice.PriceInTangTax,
              HotelName: data.HotelRow.HotelName
            }
            data.parameters.DetailList.push(dataMsg)
          }
        })
      },
      dateRangeHandler(e: any) {
        data.joinHouse.StartDate = `${e.from.year}/${e.from.month}/${e.from.day}`
        data.joinHouse.EndDate = `${e.to.year}/${e.to.month}/${e.to.day} `
        data.joinHouse.dateRangeFormat = `${data.joinHouse.StartDate} - ${data.joinHouse.EndDate} `
        data.joinHouse.days = date.getDateDiff(new Date(data.joinHouse.EndDate), new Date(data.joinHouse.StartDate), 'days')
        console.log(qDateProxyOpera)
        if (qDateProxyOpera.value) qDateProxyOpera.value.hide()
      },
      setDateRange() {
        data.joinHouse.StartDate = date.formatDate(new Date(data.parameters.Date), 'YYYY/MM/DD')
        data.joinHouse.EndDate = date.formatDate(date.addToDate(new Date(data.joinHouse.StartDate), { days: 1 }), 'YYYY/MM/DD')
        data.joinHouse.dateRangeFormat = `${data.joinHouse.StartDate} - ${data.joinHouse.EndDate} `
        data.joinHouse.days = date.getDateDiff(new Date(data.joinHouse.EndDate), new Date(data.joinHouse.StartDate), 'days')
      },
      optionsFn(cd: any) {
        return cd >= date.formatDate(date.addToDate(new Date(), { days: 7 }), 'YYYY/MM/DD')
      },
      setInjectHandler() {
        data.parameters = editor.value
        methods.calculateNum()
        methods.setDateRange()
      }
    }
    if (props.HotelRow && props.hotelInfor) {
      data.HotelRow = props.HotelRow
      data.hotelInfor = props.hotelInfor
      methods.setList()
    } else {
      methods.setInjectHandler()
    }
    onMounted(() => {
      if (data.hotelInfor.RemainingInventory) {
        data.onlyNum = data.hotelInfor.RemainingInventory
      } else {
        data.onlyNum = editor.value.RemainingInventory
      }
    })

    return { ...toRefs(data), editor, HotelLength, ...methods }
  }
})
</script>

<style>
.HotelTableOperation {
  /* box-shadow: 0 1px 3px #0003, 0 1px 1px #00000024, 0 2px 1px -1px #0000001f; */
  border-radius: 10px;
  vertical-align: top;
  background: rgba(225, 245, 254, .7);
  position: relative;
}
</style>
