<template>
  <div class="fix-height-subpage no-wrap q-pa-md" v-if="order">
    <div class="q-py-sm q-px-md rounded-borders bg-white f12" :class="{'row items-center justify-between':$q.platform.is.desktop,'colunm':$q.platform.is.mobile}">
      <div class="f12 text-grey-6">{{ $t('hotelorder.search.orderNum') }}：{{ order.OrderNo }}</div>
      <div class="rounded-border text-orange-10 f12" :class="{'q-pa-sm':$q.platform.is.desktop,'q-my-sm':$q.platform.is.mobile}">
        {{ $t('hotel.car.title') }}
        <span class="din text-orange-10">{{ order.DetailList.length }}</span>
        {{ $t('hotel.car.title1') }}
        <span class="din text-primary">{{ order.HotelCount }}</span>
        {{ $t('hotel.car.title2') }}
      </div>
      <div class="text-negative text-weight-bolder din">
          <span class="text-weight-thin">{{$t('hotel.car.sumPrice')}}：</span>
          <span class="fz14">円</span>
          <span class="text-h6">{{ moneyFormat(order.Money) }}</span>
        </div>
      <div :class="{'text-right q-mt-sm':$q.platform.is.mobile}">
        <q-btn color="negative" class="q-mr-sm" flat :label="$t('hotelm.cancel')" @click="cancelOrder" />
        <q-btn color="primary" unelevated :label="$t('hotelm.save')" @click="saveOrderHandler" />
      </div>
    </div>

    <div class="q-py-sm q-px-md rounded-borders bg-white row f12 q-mt-md">
      <div class="f12 q-mb-sm text-grey-5" :class="{'col-12':$q.platform.is.desktop}">訂單信息</div>
      <div :class="{'col-12':$q.platform.is.mobile}">
        <n-select filterable v-model:value="order.OrderType" :placeholder="$t('hotel.car.OrderType')" :options="cacheHotels" max-tag-count="responsive" size="large" value-field="ID" label-field="Name" />
      </div>
      <div :class="{'col-12 q-my-md':$q.platform.is.mobile,'q-mx-md':$q.platform.is.desktop}" v-if="order.OrderType == 2">
        <q-input v-model="order.TCNum" reverse-fill-mask dense standout :label="$t('hotel.car.inputText') + $t('hotel.car.TCNum')" ref="TCNumRef" :rules="$q.platform.is.desktop ? [val => !!val || $t('hotel.car.inputText') + $t('hotel.car.TCNum')] : [val => !!val || '']" />
      </div>
      <div :class="{'col-12 q-my-md':$q.platform.is.mobile,'q-mx-md':$q.platform.is.desktop}" v-if="order.OrderType == 1">
        <q-input v-model="order.ContactName" reverse-fill-mask dense standout :label="$t('hotel.car.inputText') + $t('hotel.car.ContactName')" ref="ContactNameRef" :rules="$q.platform.is.desktop?[val => !!val || $t('hotel.car.inputText') + $t('hotel.car.ContactName')]:[val => !!val || '']" />
      </div>
      <div :class="{'col-12 q-mb-md':$q.platform.is.mobile,'q-mr-md':$q.platform.is.desktop}" v-if="order.OrderType == 1">
        <q-input v-model="order.ContactNumber" reverse-fill-mask dense type="text" standout :label="$t('hotel.car.inputText') + $t('hotel.car.ContactNumber')" ref="ContactNumberRef" :rules="$q.platform.is.desktop?[val => !!val || $t('hotel.car.inputText') + $t('hotel.car.ContactNumber')]:[val => !!val || '']" />
      </div>
      <q-input :class="{'col-12':$q.platform.is.mobile,'col':$q.platform.is.desktop}" v-model="order.Remark" reverse-fill-mask dense filled type="text" :label="$t('hotel.car.Remark')" />
    </div>

    <div class="flex justify-start items-start content-start">
      <div class="q-pa-sm rounded-borders bg-white q-mt-md" :class="{'q-mr-md':$q.platform.is.desktop}" :style="{'width':$q.platform.is.mobile?'100%':'320px'}" v-for="(x, xi) in order.DetailList">
        <div class="text-h6 row items-center">
          <div class="col">{{ x.key }}</div>
          <q-btn color="primary" icon="add" class="q-mr-md" rounded dense size="sm" flat @click="chosenNewHotel(x)" />
          <q-btn color="negative" icon="delete" rounded dense size="sm" flat @click="removeHotelHandler(xi, -1)" />
        </div>
        <div class="q-pa-sm rounded-borders bg-blue-grey-1 q-mt-sm" v-for="(y, yi) in x.data">
          <div class="row items-center item-hide-opera" style="border-bottom: 1px dashed #607d8b33">
            <div class="text-subtitle1 text-primary ellipsis col">{{ y.HotelName }}</div>
            <div class="q-ml-sm opera-box-item">
              <q-btn color="negative" icon="delete" @click="removeHotelHandler(xi, yi)" rounded dense size="sm" flat />
            </div>
          </div>
          <template v-for="(z, i) in y.RoomList">
            <div v-if="z.IsSelf" class="q-mb-md">
              <div class="row no-wrap items-center q-mt-sm f12">
                <span class="col">
                  {{ z.RoomInfo.TypeName }}
                  <div class="text-blue-grey-6">{{ moneyFormat(z.Unit_Price) }}/{{ $t('unit.ren') }}</div>
                </span>
                <div class="col">
                  <div class="f12 text-grey-6 text-center col">
                    {{ $t('hotel.yg') }}<span class="din text-yellow-10">{{ z.Number }}</span> {{ $t('unit.jf') }}
                  </div>
                  <!-- <div>{{$t('hotelorder.xj')}}：{{moneyFormat(z.Money)}}</div> -->
                </div>
                <span>
                  <q-input style="width: 90px" v-model="z.PeopleNumber" class="q-pa-none" mask="#" reverse-fill-mask dense standout>
                    <template v-slot:prepend>
                      <q-btn color="primary" size="sm" class="q-px-none" flat icon="remove" @click="calcPeople(y, i, 0)" />
                    </template>
                    <template v-slot:append>
                      <q-btn color="primary" size="sm" class="q-px-none" flat icon="add" @click="calcPeople(y, i, 1)" />
                    </template>
                  </q-input>
                </span>
              </div>
            </div>
          </template>
          <div class="q-mb-sm f12">
            <span class="text-blue-grey-4" v-if="!y.HaveOtherRoom">{{ $t('hotelm.noneOther') }}</span>
            <span class="text-accent" v-else>{{ $t('hotelm.otherRoom') }}</span>
          </div>
          <template v-for="(z, i) in y.RoomList">
            <div v-if="!z.IsSelf" class="q-mb-md">
              <div class="row no-wrap items-center q-mt-sm f12">
                <span class="col">
                  {{ z.RoomInfo.TypeName }}
                  <div class="text-blue-grey-6">{{ moneyFormat(z.Unit_Price) }}/{{ $t('unit.ren') }}</div>
                </span>
                <div class="col">
                  <div class="f12 text-grey-6 text-center col">
                    {{ $t('hotel.yg') }}<span class="din text-yellow-10">{{ z.Number }}</span> {{ $t('unit.jf') }}
                  </div>
                  <!-- <div>{{$t('hotelorder.xj')}}：{{moneyFormat(z.Money)}}</div> -->
                </div>
                <span>
                  <q-input style="width: 90px" v-model="z.PeopleNumber" class="q-pa-none" mask="#" reverse-fill-mask dense standout>
                    <template v-slot:prepend>
                      <q-btn color="primary" size="sm" class="q-px-none" flat icon="remove" @click="calcPeople(y, i, 0)" />
                    </template>
                    <template v-slot:append>
                      <q-btn color="primary" size="sm" class="q-px-none" flat icon="add" @click="calcPeople(y, i, 1)" />
                    </template>
                  </q-input>
                </span>
              </div>
            </div>
          </template>
          <div class="row items-center justify-between" style="border-top: 1px dashed #607d8b33">
            <div class="q-mt-sm text-blue-grey-6">{{ $t('hotelorder.col.t') }}：{{ moneyFormat(y.TaxesPrice) }}/{{ $t('unit.ren') }}</div>
            <div class="q-mt-sm text-blue-grey-6">{{ $t('hotelorder.col.t2') }}：{{ moneyFormat(y.PriceInTangTax) }}/{{ $t('unit.ren') }}</div>
          </div>
          <div class="text-right text-primary q-mt-sm" style="border-top: 1px dashed #607d8b33">
            <span class="text-weight-thin">{{ $t('hotel.groupPrice') }}：</span>
            <span class="fz14">円</span>
            <span class="text-subtitle1">{{ moneyFormat(y.HotelMoeny) }}</span>
          </div>
        </div>
      </div>
      <div class="q-pa-sm rounded-borders bg-white q-mt-md" :class="{'q-mr-md':$q.platform.is.desktop,'q-mb-md':$q.platform.is.mobile}" :style="{'width':$q.platform.is.mobile?'100%':'320px'}">
        <div class="text-h6 row items-center">
          <div class="col">{{ $t('hotel.newDateOrder') }}</div>
          <q-field :label="$t('daterange')" style="min-width: 120px" standout :model-value="tempHotels.key" class="col-2 text-dark" dense>
            <template v-slot:control>
              <div class="self-center full-width no-outline" tabindex="0">{{ tempHotels.key }}</div>
            </template>
            <q-popup-proxy :offset="[0, 10]" ref="qDateProxy">
              <q-date v-model="tempHotels.key" :options="optionsFn" mask="YYYY/MM/DD" landscape></q-date>
            </q-popup-proxy>
          </q-field>
        </div>
        <div class="q-pa-sm rounded-borders bg-blue-grey-1 q-mt-sm q-">
          <div style="padding: 100px 0" class="text-center">
            <q-btn color="primary" :label="$t('hotel.newHotelBtn')" :disable="tempHotels.key == ''" outline @click="chosenNewHotel(tempHotels)" />
            <div class="text-blue-grey-4 q-mt-md" v-if="tempHotels.key == ''">* {{ $t('hotel.newDateTips') }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <q-dialog v-model="showChosenHotel" :class="{ 'full-window': $q.platform.is.mobile }">
    <chosen-hotel @finish="finishHandler"></chosen-hotel>
  </q-dialog>

  <q-inner-loading :showing="loading" :label="$t('loading')" label-class="text-grey-6 f12" />
  <div class="text-center q-mt-xl" v-if="!order && !loading">
    <svg-icon :size="50" color="nav" icon="General/Clipboard.svg"></svg-icon>
    <div class="q-mt-md f12 text-grey-6">{{ $t('noneData') }}</div>
  </div>
</template>

<script lang="ts">
import useMetaModule from '../../module/meta/metaModule'
import { ApiResult } from 'src/@types/enumHelper'
import HotelService from 'src/api/hotel'
import { DirtionmaryHelper } from 'src/config/dictionary'
import { currentRouter } from 'src/router'
import message from 'src/utils/message'
import { defineComponent, inject, provide, reactive, ref, toRefs } from 'vue'
import { useI18n } from 'vue-i18n'
import { RoomType, StandardStatus } from 'src/@types'
import { getHotelOrderStatus, getHotelRoomType, groupBy, moneyFormat } from 'src/utils/tools'
import { date, useQuasar } from 'quasar'
import ChosenHotel from '../../components/hotel/chosen/ChosenHotel.vue'
import { NSelect } from 'naive-ui'
export default defineComponent({
  components: { ChosenHotel, NSelect },
  setup(props) {
    const $q = useQuasar()
    let { setTitle } = useMetaModule()
    const { t } = useI18n()
    const pageTitle = inject(DirtionmaryHelper.PAGE_TITLE_KEY) as any
    pageTitle.value = t('hotelm.pageTitle')
    setTitle(pageTitle.value)
    const menu = inject(DirtionmaryHelper.MENU_KEYS) as any
    menu.value = 3

    const TCNumRef = ref(null) as any
    const ContactNameRef = ref(null) as any
    const ContactNumberRef = ref(null) as any

    const search = reactive({
      HotelChooseArray: [],
      StartDate: '2022/11/25',
      EndDate: '2022/11/25',
      Country: '651',
      Province: 0,
      City: 0,
      OutBranchId: -1,
      Star: 0,
      PriceLevel: 0,
      Supplier: 0,
      MaxPrice: '',
      MinPrice: '',
      SearchByUpdate: true
    })
    provide(DirtionmaryHelper.HOTEL_QUERY_PARAM, search)
    const data = reactive({
      orderId: 0,
      order: null as any,
      loading: true,
      status: [] as Array<StandardStatus>,
      rooms: [] as Array<RoomType>,
      limitGuestNum: [2, 1, 1, 3, 1],
      showChosenHotel: false,
      tempHotels: {
        key: '',
        data: [] as Array<any>
      },
      cacheHotels: [
        { Name: t('hotel.car.scattered'), ID: 1 },
        { Name: t('hotel.car.group'), ID: 2 }
      ]
    })
    data.orderId = currentRouter.currentRoute.value.params.orderId
    if (data.orderId == 0) {
      history.back()
    }

    const methods = {
      initOrderDetails() {
        HotelService.GetOrderDetail(data.orderId)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              data.order = r.data.data
              data.order.typeInfo = data.status.find(y => y.StatusId == data.order.OrderStatus) ?? data.status[1]
              data.order.DetailList.forEach((y: any) => {
                let PeopleNum = 0
                y.RoomList.forEach((z: any) => {
                  z.RoomInfo = data.rooms.find(r => r.TypeId == z.RoomType) ?? data.rooms[0]
                  console.log(z.RoomInfo)
                  PeopleNum += z.PeopleNumber
                  z.IsSelf = true
                })
                console.log(PeopleNum)
                y.PeopleNum = PeopleNum
                methods.loadOtherRoom(y)
              })
              data.order.HotelCount = data.order.DetailList.length

              data.order.DetailList = groupBy(data.order.DetailList, (x: any) => {
                return x.Date
              })
              console.log(data.order)
            } else {
              message.errorMsg(r.data.message)
            }
            data.loading = false
          })
          .catch(e => {
            message.errorMsg(e.message)
            data.loading = false
          })
      },
      calcPeople(hotel: any, room: number, type: 0 | 1) {
        let t = hotel.RoomList[room]
        if (t.PeopleNumber == 0 && type == 0) return
        t.PeopleNumber += type == 0 ? -1 : 1
        t.Number = Math.ceil(t.PeopleNumber / data.limitGuestNum[t.RoomType - 1])
        t.Money = t.PeopleNumber * t.Number
        methods.calcMoney(hotel)
      },
      calcMoney(hotel: any) {
        let money = 0.0
        let peoples = 0
        hotel.RoomList.forEach((x: any) => {
          money += x.Unit_Price * x.PeopleNumber
          peoples += x.PeopleNumber
        })
        money += peoples * (hotel.TaxesPrice + hotel.PriceInTangTax)
        hotel.PeopleNum = peoples
        hotel.HotelMoeny = money
        methods.cancelHotelCount()
        //return money
      },
      loadOtherRoom(hotel: any) {
        let searchObj = {
          HotelChooseArray: [hotel.HotelId],
          StartDate: hotel.Date,
          EndDate: hotel.Date,
          Country: '651',
          Province: 0,
          City: 0,
          OutBranchId: -1,
          Star: 0,
          PriceLevel: 0,
          Supplier: 0,
          MaxPrice: '',
          MinPrice: '',
          pageIndex: 1,
          pageSize: 10,
          pageCount: 0
        }
        HotelService.GetHotelList(searchObj).then(r => {
          if (r.data.resultCode == ApiResult.SUCCESS) {
            if (r.data.data.pageData.length > 0) {
              let temp = r.data.data.pageData[0].subList[0].PriceList[0]
              data.rooms.forEach((x: RoomType) => {
                if (hotel.RoomList.findIndex((y: any) => y.RoomType == x.TypeId) == -1 && temp[x.Field ?? ''] > 0) {
                  hotel.RoomList.push({
                    Description: '',
                    Money: 0,
                    PeopleNumber: 0,
                    RoomType: x.TypeId,
                    RoomTypeName: x.TypeName,
                    Unit_Price: temp[x.Field ?? ''],
                    RoomInfo: x,
                    IsSelf: false
                  })
                  hotel.HaveOtherRoom = true
                }
              })
            }
          }
        })
      },
      removeHotelHandler(x: number, y: number) {
        let cando = false
        if (y > -1) {
          cando = data.order.DetailList.length > 1 || data.order.DetailList[0].data.length > 1
        } else {
          cando = data.order.DetailList.length > 1
        }
        if (cando) {
          methods.deleteHotelsHandler(x, y)
        } else {
          methods.cancelOrder()
        }
      },
      cancelOrder() {
        $q.dialog({
          title: t('dialog.titles.horder'),
          message: t('dialog.contents.horder'),
          cancel: true,
          persistent: true
        }).onOk(() => {
          if (data.loading) return
          data.loading = true
          HotelService.CancelHotelOrder(data.order.OrderId)
            .then(r => {
              if (r.data.resultCode == ApiResult.SUCCESS) {
                currentRouter.push('/hotel/order')
              }else{
                message.errorMsg(r.data.message)
              }
              data.loading = false
            })
            .catch(e => {
              message.errorMsg(e.message)
              data.loading = false
            })
        })
      },
      deleteHotelsHandler(x: number, y: number) {
        $q.dialog({
          title: t('dialog.titles.hotel'),
          message: `${t('dialog.contents.hotel.t1')} ${data.order.DetailList[x].key} ${t('dialog.contents.hotel.t2')}${y > -1 ? data.order.DetailList[x].data[y].HotelName : ''}`,
          cancel: true,
          persistent: true
        }).onOk(() => {
          if (y > -1) {
            data.order.DetailList[x].data.splice(y, 1)
            if (data.order.DetailList[x].data.length == 0) {
              data.order.DetailList.splice(x, 1)
            }
          } else {
            data.order.DetailList.splice(x, 1)
          }
          methods.cancelHotelCount()
        })
      },
      chosenNewHotel(x: any) {
        search.StartDate = x.key
        search.EndDate = x.key
        data.showChosenHotel = true
      },
      finishHandler(h: any) {
        data.showChosenHotel = false
        let hp = h.subList[0].PriceList[0]
        console.log(h)
        //#region 組裝對象
        let hotel = {
          ContractUrl: null,
          CurrencyId: hp.CurrencyId,
          CurrencyName: '日元',
          CustomerPayType: 0,
          Date: h.subList[0].DateStr.replace(/-/g, '/'),
          Destription: null,
          HaveOtherRoom: false,
          HotelId: h.HotelId,
          HotelMoeny: 0.0,
          HotelName: h.HotelName,
          HotelStatus: 1,
          HotelStatusName: '暫定',
          Id: 0,
          ImageList: h.ImageList,
          PeopleNum: 0,
          PriceInTangTax: hp.PriceInTangTax,
          ReserveRoomNo: null,
          RoomList: [] as Array<any>,
          TaxesPrice: hp.TaxesPrice
        }
        data.rooms.forEach((x: RoomType) => {
          if (hp[x.Field ?? ''] > 0) {
            hotel.RoomList.push({
              Destription: '',
              IsSelf: true,
              Money: 0,
              PeopleNumber: 0,
              RoomInfo: x,
              RoomType: x.TypeId,
              RoomName: x.TypeName,
              Unit_Price: hp[x.Field ?? '']
            })
          }
        })
        //#endregion
        let i = data.order.DetailList.findIndex((x: any) => x.key == hotel.Date)
        if (i == -1) {
          data.order.DetailList.push({
            key: hotel.Date,
            data: [hotel]
          })
          data.order.DetailList.sort((x: any, y: any) => {
            return new Date(x.key).getTime() - new Date(y.key).getTime()
          })
        } else {
          let y = data.order.DetailList[i].data.findIndex((x: any) => x.HotelId == hotel.HotelId)
          if (y == -1) data.order.DetailList[i].data.push(hotel)
        }

        if (hotel.Date == data.tempHotels.key) {
          data.tempHotels.key = ''
          data.tempHotels.data = []
        }
        methods.cancelHotelCount()
      },
      optionsFn(cd: any) {
        data.tempHotels.key = date.formatDate(date.addToDate(new Date(), { days: 20 }), 'YYYY/MM/DD')
        return cd >= date.formatDate(date.addToDate(new Date(), { days: 20 }), 'YYYY/MM/DD') && data.order.DetailList.findIndex((x: any) => x.key == cd) == -1
      },
      cancelHotelCount() {
        data.order.HotelCount = 0
        data.order.Money = 0
        data.order.DetailList.forEach((x: any) => {
          data.order.HotelCount += x.data.length
          x.data.forEach((y:any)=>{
            data.order.Money+=y.HotelMoeny
          })
        })
      },
      saveOrderHandler(){
        if(data.loading) return
        let flag = false
        if (data.order.OrderType == 1) {
          ContactNameRef.value.validate()
          ContactNumberRef.value.validate()
          flag = !ContactNameRef.value.hasError && !ContactNumberRef.value.hasError
        }else{
          TCNumRef.value.validate()
          flag = !TCNumRef.value.hasError
        }
        if(!flag) return
        data.loading = true
        let detailList=[] as Array<any>
        data.order.DetailList.forEach((x:any)=>{
          detailList.push(...x.data)
        })
        detailList.forEach((x:any)=>{
          x.RoomList = x.RoomList.filter((y:any)=>y.Number>0)
        })
        detailList = detailList.filter((x:any)=>x.RoomList.length>0)
        let parameter = JSON.parse(JSON.stringify(data.order))
        parameter.DetailList = detailList
        HotelService.SetCustomerOrder(parameter)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              message.successMsg(`${t('success')}`)
              currentRouter.push('/hotel/order')
            } else {
              message.errorMsg(r.data.message)
            }
            data.loading = false
          })
          .catch(e => {
            message.errorMsg(e.message)
            data.loading = false
          })
      }
    }
    data.status = getHotelOrderStatus()
    data.rooms = getHotelRoomType()
    methods.initOrderDetails()
    return {
      ...toRefs(data),
      ...methods,
      moneyFormat,
      TCNumRef,
      ContactNameRef,
      ContactNumberRef
    }
  }
})
</script>

<style>
.opera-box-item {
  display: none !important;
}
.item-hide-opera:hover .opera-box-item {
  display: block !important;
}
</style>
