<template>
  <q-card flat class="q-pa-lg" style="shadow: 0px 0px 50px 0px rgba(82, 63, 105, 0.15); width: 50vw">
    <div class="q-mb-xs">
      <div class="">
        <span class="text-primary text-h6">{{ HotelRow.HotelName }}</span>
      </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" v-html="$t('hotel.inhouseDays', { day: joinHouse.days })"></span>
      </div>
    </div>
    <div class="f12 text-negative q-mb-md">{{ $t('hotel.waringTips') }}</div>
    <div class="bg-grey-1 rounded-borders q-px-md q-py-sm" style="max-height: 35vh; overflow-y: auto">
      <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 ? '1px dashed #ddd' : '' }">
          <div class="q-pr-md col-2">
            <div class="f12">{{ item.RoomName }}</div>
          </div>
          <div class="text-negative f12 col-3">
            <span class="fz10">¥</span>
            <span class="din">{{ item.UPriceFormat }}</span>
            <span class="text-dark" style="font-size: 12px">/{{ $t('unit.ren') }}</span>
          </div>
          <div class="q-pl-md col-4">
            <q-input style="width: 100%" @update:model-value="changePeople" v-model="item.PeopleNumber" class="col q-mr-md q-px-sm" 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="text-center col">
            <span class="f12 text-grey-6" v-html="$t('hotel.yg', { roomCount: item.Number })"></span>
          </div>
        </div>
      </template>
    </div>
    <div class="row items-center justify-between q-pt-md">
      <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 items-center q-pl-md">
        <div>
          <q-btn flat dense color="dark" :label="$t('close')" class="q-mr-sm" 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 } from '../../../utils/tools'
export default defineComponent({
  props: {
    HotelRow: {
      type: Object,
      require: true
    },
    hotelInfor: {
      type: Object,
      require: true
    }
  },
  emits:['close'],
  setup(props, context) {
    const { t } = useI18n()
    const qDateProxyOpera = ref<any>(null)
    const cars = inject(DirtionmaryHelper.HOTEL_CAR_LIST) as any
    const data = reactive({
      HotelRow: props.HotelRow as any,
      hotelInfor: props.hotelInfor as any,
      onlyNum: 0,
      parameters: {
        HotelId: '',
        HotelName: '',
        Date: '',
        RemainingInventory: '',
        total: 0,
        Money: 0,
        DetailList: [] as Array<any>,
        Remark: '',
        TaxesPrice:0,
        PriceInTangTax: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()
      }
    )

    data.onlyNum = data.hotelInfor.RemainingInventory
    //   今天购买数量
    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){
        methods.calculateNum()
      },
      // 计算房间数量
      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)
        })
      },
      joinOverride(){
        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[existsIndex]
        if(exists){
          let existsHotel = exists.Hotels?.find((h:any)=>h.HotelId==temp.HotelId)
          if(existsHotel) exists.Hotels.remove(existsHotel)
        }else{
          exists = {
            Date:temp.Date,
            Hotels:[] as Array<any>
          }
          cars.value.push(exists)
        }
        exists.Hotels.push(temp)
        console.log(cars.value)
        message.successMsg(t('success'))
        context.emit('close')
      },
      // 加入购物车
      join() {
        methods.joinOverride()
        return
        // if (data.total < 1 || data.total > data.hotelInfor.RemainingInventory) {
        //   message.errorMsg(`${t('hotel.shopping.small')}1${t('hotel.shopping.big')}${data.hotelInfor.RemainingInventory}`)
        // }
        // const parameters = data.parameters
        // let msgData = {
        //   HotelId: parameters.HotelId,
        //   HotelName: parameters.HotelName,
        //   TaxesPrice: 0.0,
        //   PriceInTangTax: 0.0,
        //   timeList: [] as Array<any>
        // }
        // let msg = {
        //   Date: parameters.Date,
        //   total: data.total,
        //   RemainingInventory: parameters.RemainingInventory,
        //   rooms: [] as Array<any>
        // }
        // data.parameters.DetailList.forEach((x, index) => {
        //   msgData.TaxesPrice = x.TaxesPrice
        //   msgData.PriceInTangTax = x.PriceInTangTax
        //   //console.log(moneyFormat(x.Unit_Price),11111111)
        //   if (x.Number > 0) {
        //     let ArrData = {
        //       HotelId: x.HotelId,
        //       Date: x.Date,
        //       RoomType: x.RoomType,
        //       RoomName: x.RoomName,
        //       Unit_Price: x.Unit_Price,
        //       Number: x.Number,
        //       PeopleNumber: x.PeopleNumber,
        //       Destription: x.Destription,
        //       TaxesPrice: x.TaxesPrice,
        //       PriceInTangTax: x.PriceInTangTax
        //     }
        //     msg.rooms.push(ArrData)
        //   }
        // })
        // msgData.timeList.push(msg)
        // if (data.total > 0) {
        //   let list = HotelCarList.value
        //   if (list.length > 0) {
        //     let fault = true
        //     list.forEach((item: any, index: number) => {
        //       if (item.HotelId == parameters.HotelId) {
        //         item.timeList.forEach((x: any, i: number) => {
        //           if (fault && x.Date == parameters.Date) {
        //             HotelCarList.value[index].timeList.splice(i, 1)
        //             HotelCarList.value[index].timeList.push(msg)
        //             fault = false
        //           } else if (fault && x.Date != parameters.Date) {
        //             HotelCarList.value[index].timeList.push(msg)
        //             fault = false
        //           }
        //         })
        //       }
        //     })
        //     if (fault) HotelCarList.value.push(msgData)
        //   } else {
        //     HotelCarList.value.push(msgData)
        //   }
        // }
        // message.successMsg(`${t('success')}`)
        // context.emit('close')
      },
      // 组装可选房间
      setList() {
        methods.setDateRange()
        data.parameters.DetailList = [] as Array<any>
        // 1:標間成本价 2:大床成本价 3:自然間成本价 4:3人間成本价 5:司機房成本价 稅金 TaxesPrice  入湯稅 PriceInTangTax
        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,
        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.hotelInfor.DateStr), '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')
      }
    }
    methods.setList()
    return { ...toRefs(data), ...methods }
  }
})
</script>

<style></style>
