<template>
  <div>
    <q-card class="light-shadow q-pa-md bg-white rounded-borders q-mb-md" flat v-for="x in orders">
      <div class="row items-center desktop-only">
        <div class="q-mr-md">
          <q-btn :color="x.OrderType == 1 ? 'cyan' : 'negative'" unelevated disable size="sm"
            :label="`${x.OrderType == 1 ? $t('hotelorder.orderType.guest') : $t('hotelorder.orderType.tour')}`"></q-btn>
        </div>
        <div class="f12 text-grey-6">{{ $t('hotelorder.search.orderNum') }}：{{ x.OrderNo }}</div>
        <div class="q-ml-md">
          <q-btn color="dark" flat size="sm" :label="$t('hotelorder.copy')" v-if="copyId != x.OrderId"
            @click="setCopyHandler(x)" />
          <q-btn color="cyan" icon="check" outline size="sm" :label="$t('hotelorder.copyed')" v-else></q-btn>
        </div>
        <div class="col text-center f12 text-grey-6">
          <span v-if="x.OrderType == 1">{{ $t('hotelorder.search.contactInfo') }}：{{ x.ContactName }}/{{
            x.ContactNumber
          }}</span>
          <span v-else>{{ $t('hotelorder.search.tcNum') }}：{{ x.TCNum }}</span>
        </div>
        <div class="f12 text-grey-6">{{ $t('hotelorder.createTime') }}：{{ x.CreateTime }}</div>
        <div class="q-ml-md f12" :class="[x.typeInfo.Color]">
          <q-icon :name="x.typeInfo.Icon" />
          <span class="q-ml-sm">{{ x.typeInfo.StatusName }}</span>
        </div>
      </div>
      <div class="mobile-only">
        <div class="row justify-between">
          <div class="q-mr-md">
            <q-btn :color="x.OrderType == 1 ? 'cyan' : 'negative'" unelevated disable size="sm"
              :label="`${x.OrderType == 1 ? $t('hotelorder.orderType.guest') : $t('hotelorder.orderType.tour')}`"></q-btn>
          </div>
          <div class="q-ml-md f12" :class="[x.typeInfo.Color]">
            <q-icon :name="x.typeInfo.Icon" />
            <span class="q-ml-sm">{{ x.typeInfo.StatusName }}</span>
          </div>
        </div>
        <div class="bg-grey-2 rounded-borders q-pa-sm q-mt-md">
          <div class="row items-center justify-between">
            <div class="f12 text-grey-6">{{ $t('hotelorder.search.orderNum') }}：{{ x.OrderNo }}</div>
            <div class="q-ml-md">
              <q-btn color="dark" flat size="sm" :label="$t('hotelorder.copy')" v-if="copyId != x.OrderId"
                @click="setCopyHandler(x)" />
              <q-btn color="cyan" outline size="sm" :label="$t('hotelorder.copyed')" v-else></q-btn>
            </div>
          </div>
          <div class="f12 text-grey-6">
            <span v-if="x.OrderType == 1">{{ $t('hotelorder.search.contactInfo') }}：{{ x.ContactName }}/{{
              x.ContactNumber
            }}</span>
            <span v-else>{{ $t('hotelorder.search.tcNum') }}：{{ x.TCNum }}</span>
          </div>
          <div class="f12 text-grey-6">{{ $t('hotelorder.createTime') }}：{{ x.CreateTime }}</div>
        </div>
      </div>

      <div class="q-mt-md row">
        <q-table separator="cell" :hide-bottom="!x.Remark" :pagination="{ rowsPerPage: 100 }" dense :rows="x.DetailList"
          bordered :columns="cols" class="sticky-rightrowspan-column-table light-border col no-shadow">
          <template v-slot:header-cell-Room="props">
            <q-th :props="props">
              <div class="row items-center">
                <span class="q-mr-md">{{ props.col.label }}</span>
                <q-tooltip>{{ $t('hotelorder.priceTips') }}</q-tooltip>
                <svg-icon icon="Code/Question-circle.svg" :size="14"></svg-icon>
              </div>
            </q-th>
          </template>
          <template v-slot:body-cell-Room="props">
            <q-td :props="props">
              <div class="room-item f12 text-grey-6" v-for="x in props.row.RoomList">
                <span class="q-mr-md"> {{ x.RoomInfo.TypeName }}: {{ x.Number }} {{ $t('unit.jian') }} </span>
                <span class="q-mr-md"> {{ $t('hotelorder.people') }}: {{ x.PeopleNumber ?? 1 }} {{ $t('unit.ren') }}
                </span>
                <span class="q-mr-md"> {{ $t('hotelorder.unitPrice') }}: {{ x.Unit_Price ?? 1 }} </span>
                <span class="q-mr-md"> {{ $t('hotelorder.xj') }}: {{ x.Money ?? 1 }} </span>
              </div>
            </q-td>
          </template>
          <template v-slot:body-cell-RoomNo="props">
            <q-td :props="props">
              <n-tag :bordered="false" size="small" type="error" v-if="!props.row.ReserveRoomNo">
                {{ $t('hotelorder.check.un') }}
              </n-tag>
              <n-tag :bordered="false" size="small" type="success" v-else>
                {{ props.row.ReserveRoomNo }}
              </n-tag>
            </q-td>
          </template>
          <template v-slot:body-cell-HandFittingFee="props">
            <q-td :props="props" :colspan="x.DetailList.length" v-if="props.rowIndex == 0" >
              {{ moneyFormat(x.HandFittingFee) }}
              <div class="q-mt-sm" v-if="x.OrderStatus == 2">
                <q-btn size="sm" dense outline color="primary" v-if="x.ContractUrl">
                  <a class="text-primary" style="text-decoration:none"
                    :href="x.ContractUrl">{{ $t('v101.downloadHands') }}</a>
                </q-btn>
                <span class="text-grey-500 f12">{{ $t('v101.noneHands') }}</span>
              </div>
            </q-td>
          </template>
          <template v-slot:body-cell-HotelName="props">
            <q-td :props="props">
              <div class="max-hotelname ellipsis">{{ props.value }}</div>
              <q-tooltip>{{ props.value }}</q-tooltip>
            </q-td>
          </template>
          <template v-slot:bottom>
            <div class="msl text-negative">{{ $t('v101.hotelRemark') }}：{{ x.Remark }}</div>
          </template>
        </q-table>
      </div>
      <div class="q-mt-md" v-if="x.OrderStatus != 3"
        :class="{ row: $q.platform.is.desktop, 'column reverse': $q.platform.is.mobile }">
        <div class="pay row text-grey rounded-borders q-pa-md"
          v-if="$q.platform.is.desktop || ($q.platform.is.mobile && expendsOrderId == x.OrderId)"
          :class="{ 'bg-grey-2': $q.platform.is.mobile }">
          <svg-icon color=" svg-red" icon="Code/Warning-1-circle.svg" :size="16"
            v-if="$q.platform.is.desktop"></svg-icon>
          <div class="q-ml-sm">
            <div class="q-mb-sm" v-if="x.CustomerPayType == 2 || x.CustomerPayType == 3">
              <div class="f12">
                {{ $t('hotelorder.pay.t1') }}
                <span class="text-orange">{{ x.PaymentDate }}</span>
                {{ $t('hotelorder.pay.t11') }}
                <span class="text-orange">{{ x.FinalPaymentDate }}</span>
                {{ $t('hotelorder.pay.t12') }}
              </div>
              <q-btn dense outline color="accent" size="sm" class="q-mt-sm" :label="$t('hotelorder.payinfo')"
                @click="ViewPayment"></q-btn>
              <!-- <q-btn dense unelevated color="accent" size="sm" class="q-mt-sm q-ml-sm" :label="$t('hotelorder.sendpay')"></q-btn> -->
            </div>
            <div v-if="x.CustomerPayType == 1 || x.CustomerPayType == 3">
              <div class="f12">
                {{ $t('hotelorder.pay.t2') }}
                <span class="text-negative">{{ x.UploadGuestDate }}</span>
                {{ $t('hotelorder.pay.t21') }}
              </div>
              <div class="row items-center f12 q-mt-sm">
                <div class="text-accent q-mr-md" v-if="x.GuestFileList.length > 0">
                  {{ x.GuestFileList[0].split('/').at(-1) }}</div>
                <q-btn dense unelevated color="primary" size="sm" class="q-mr-sm" v-if="x.GuestFileList.length > 0">
                  <a class="text-white" style="text-decoration:none"
                    :href="x.GuestFileList[0]">{{ $t('upload.down') }}</a>
                </q-btn>
                <n-upload class="col" :action="importFileUrl" @finish="handleFinish"
                  @change="uploadHandleChange(x.OrderId)" file-list-style="display:none">
                  <q-btn dense outline color="primary" size="sm"
                    :label="x.GuestFileList.length == 0 ? $t('hotelorder.uploadGuest') : $t('upload.reload')"></q-btn>
                </n-upload>
              </div>
            </div>
          </div>
        </div>
        <div class="mobile-only row items-center justify-between" v-if="$q.platform.is.mobile">
          <div class="text-negative">
            <svg-icon color=" svg-red" icon="Code/Warning-1-circle.svg" :size="16"></svg-icon>
            <span class="q-ml-sm">{{ $t('hotelorder.warn') }}</span>
          </div>
          <q-btn color="grey" @click="setShowWarnHander(x.OrderId)" dense size="sm" flat
            :label="expendsOrderId == x.OrderId ? $t('expends.off') : $t('expends.on')" />
        </div>
        <div class="col desktop-only"></div>
        <div class="rounded-borders bg-grey-2 q-pa-md"
          :class="{ 'q-mx-md': $q.platform.is.desktop, 'q-mt-md': $q.platform.is.mobile }">
          <div class="row items-center justify-between q-mb-sm q-pb-sm" style="border-bottom: 1px dashed #ddd">
            <div class="f12 text-grey">{{ $t('hotelorder.orderMoney') }}</div>
            <div class="dark q-ml-xl">
              <!-- <span class="f12">{{ $t('unit.jpc') }}</span> -->
              <span class="din text-subtitle1">{{ moneyFormat(x.Money) }}</span>
              <span class="f12">{{ $t('unit.jp') }}</span>
            </div>
          </div>
          <div class="row items-center justify-between q-mb-sm q-pb-sm" style="border-bottom: 1px dashed #ddd"
            v-if="x.CustomerPayType == 1 || x.CustomerPayType == 3">
            <div class="f12 text-grey">{{ $t('hotelorder.payType.t1') }}</div>
            <div class="dark">
              <span class="f12">{{ moneyFormat(x.SelfPayMoney) }}</span>
              <span class="f12">{{ $t('unit.jp') }}</span>
            </div>
          </div>
          <div class="row items-center justify-between" v-if="x.CustomerPayType == 2 || x.CustomerPayType == 3">
            <div class="f12 text-grey">{{ $t('hotelorder.payType.t2') }}</div>
            <div class="dark">
              <span class="f12">{{ moneyFormat(x.BeforeMoney) }}</span>
              <span class="f12">{{ $t('unit.jp') }}</span>
            </div>
          </div>
        </div>
        <div class="rounded-borders q-pa-sm justify-between"
          :class="{ column: $q.platform.is.desktop, 'row items-center': $q.platform.is.mobile, 'bg-green-1': x.OrderStatus != 1, 'bg-grey-2': x.OrderStatus == 1 }">
          <q-list dense v-if="x.OrderStatus == 1"
            :class="{ 'row items-center justify-between full-width': $q.platform.is.mobile }">
            <q-item class="text-negative" clickable v-close-popup @click="cancelConfirmHandler(x.OrderId)">
              <q-item-section>
                <q-item-label>{{ $t('hotelorder.opera.cancel') }}</q-item-label>
              </q-item-section>
            </q-item>
            <q-item class="text-primary" clickable v-close-popup @click="modify(x.OrderId)">
              <q-item-section>
                <q-item-label>{{ $t('hotelorder.opera.edit') }}</q-item-label>
              </q-item-section>
            </q-item>
            <q-item class="text-positive" clickable v-close-popup @click="goUrl(x.OrderId)">
              <q-item-section>
                <q-item-label>{{ $t('v101.Listofquotation.baojiadan') }}</q-item-label>
              </q-item-section>
            </q-item>
            <!-- <q-item class="text-dark" clickable v-close-popup>
              <q-item-section>
                <q-item-label>{{ $t('hotelorder.opera.view') }}</q-item-label>
              </q-item-section>
            </q-item> -->
          </q-list>
          <div v-else>
            <div class="f12 text-green-4">{{ $t('hotelorder.payed') }}</div>
            <div class="text-subtitle1 din text-green-14">
              {{ x.OrderIncome.toFixed(2) }}
              <span class="text-green-4 f12">{{ $t('unit.jp') }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="x.OrderStatus == 3">
        <div class="q-mt-md q-pa-sm row items-center rounded-borders bg-orange-1"
          style="border-width: 0 5px; border-style: solid; border-color:#ffb74d;">
          <div class="text-subtitle2 text-weight-bolder text-grey-900">{{ $t('v101.cancelRemark') }}：</div>
          <div class="f12 text-grey-600 q-ml-sm col">{{ x.CancelRemark ? x.CancelRemark : $t('v101.selfCancle') }}</div>
          <div class="f12 text-grey-900">{{ x.CancelEmpName }} {{ x.CancelTime }}</div>
        </div>
      </div>
    </q-card>
    <q-card class="light-shadow q-pa-md bg-white rounded-borders q-mb-md" v-if="pages.pageCount > 0" flat>
      <q-pagination class="full-width justify-end" v-model="pages.pageIndex" color="primary" :max="pages.pageCount"
        :input="true" @update:model-value="changePageHandler" />
    </q-card>
    <q-inner-loading :showing="loading" :label="$t('loading')" label-class="text-grey-6 f12" />
  </div>
  <div class="text-center q-mt-xl" v-if="(!orders || orders.length == 0) && !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>
  <!-- <q-dialog v-model="PaymentDialog">
    <div class="rounded-borders bg-white q-pb-lg q-pt-lg" style="width: 450px">
      <div class="orderListDialog-title row justify-center q-pb-xs">
        <span class="text-weight-bold">{{ $t('hotelorder.dialog.title') }}</span>
        <q-icon class="orderListDialog-close text-grey" name="close" @click="PaymentDialog = false"></q-icon>
      </div>
      <div class="orderListDialog-bg column rounded-borders q-ma-lg q-py-lg q-px-lg">
        <div class="orderListDialog-img">
          <div class="row items-end q-pb-md">
            <span class="text-grey-3">{{ $t('hotelorder.dialog.AccountName') }}：</span>
            <span class="text-weight-bold text-white" style="font-size: 18px">株式会社ピースインターナショナル</span>
          </div>
          <div class="q-pb-sm" :class="{'row items-center justify-between':$q.platform.is.desktop}">
            <div :class="{'q-mb-sm':$q.platform.is.mobile,'col':$q.platform.is.desktop}" >
              <span class="text-grey-3">{{ $t('hotelorder.dialog.account') }}：</span>
              <span class="text-cyan-12 text-weight-bold din" style="font-size: 18px">593-1070078</span>
            </div >
            <q-btn :class="{'q-ml-xl':$q.platform.is.mobile}" unelevated size="xs" class="bg-blue-11 text-white" v-if="copyId != -1" :label="$t('hotelorder.dialog.copy')" @click="setCopyHandler(null,'開戶名：張三，帳戶：7489 3272 7942 311')"></q-btn>
            <q-btn :class="{'q-ml-xl':$q.platform.is.mobile}" icon="check" unelevated size="xs" class="bg-blue-11 text-white"  :label="$t('hotelorder.copyed')" v-else></q-btn>
          </div>
        </div>
      </div>
      <div class="row justify-center q-pb-lg">
        <span class="text-center f12 text-grey-6 q-px-lg">{{ $t('hotelorder.dialog.prompt') }}</span>
      </div>
    </div>
  </q-dialog> -->
  <q-dialog v-model="showBankAccount">
    <BankAccount @change="showBankAccount=false"></BankAccount>
  </q-dialog>
</template>

<script lang="ts">
import { DirtionmaryHelper } from '../../../../config/dictionary'
import { defineComponent, inject, reactive, toRefs, watch } from 'vue'
import HotelService from '../../../../api/hotel'
import { ApiResult } from '../../../../@types/enumHelper'
import message from '../../../../utils/message'
import { RoomType, StandardStatus } from '../../../../@types'
import { getHotelOrderStatus, getHotelRoomType, moneyFormat } from '../../../../utils/tools'
import { useI18n } from 'vue-i18n'
import svgIcon from '../../../global/svg-icon.vue'
import { copyToClipboard, useQuasar } from 'quasar'
import { currentRouter } from '../../../../router'
import { UploadFileInfo, NTag, NUpload } from 'naive-ui'
import { slice } from 'lodash'
import BankAccount from '../../../BankAccount.vue'

export default defineComponent({
  components: { svgIcon, NTag, NUpload, BankAccount },
  setup(props) {
    const search = inject(DirtionmaryHelper.HOTEL_ORDER_SEARCH) as any
    const { t } = useI18n()
    const $q = useQuasar()

    watch(search, (n, o) => {
      if (data.loading) return
      data.loading = true
      data.pages.pageIndex = 1
      data.orders = []
      methods.initOrders()
    })

    const data = reactive({
      PaymentDialog: false,
      orders: [] as Array<any>,
      status: [] as Array<StandardStatus>,
      rooms: [] as Array<RoomType>,
      uploadOrderId: 0,
      showBankAccount: false,
      pages: {
        pageIndex: 1,
        pageSize: 10,
        pageCount: 0
      },
      loading: true,
      copyId: 0,
      expendsOrderId: 0,
      cols: [
        { name: 'Date', label: t('hotelorder.col.d'), field: (row: any) => row.Date, align: 'left' },
        { name: 'HotelName', label: t('hotelorder.col.hn'), field: (row: any) => row.HotelName, align: 'left' },
        { name: 'Room', label: t('hotelorder.col.r'), align: 'left' },
        { name: 'RoomNo', label: t('hotelorder.col.n'), align: 'left' },
        { name: 'Tax', label: t('hotelorder.col.t'), field: (row: any) => (row.TaxesPrice ? `${(row.PeopleNum * row.TaxesPrice).toFixed(2)}` : t('hotelorder.col.noneTax')), align: 'left' },
        { name: 'Tax2', label: t('hotelorder.col.t2'), field: (row: any) => (row.PriceInTangTax ? `${(row.PeopleNum * row.PriceInTangTax).toFixed(2)}` : t('hotelorder.col.noneTax')), align: 'left' },
        { name: 'Money', label: t('hotelorder.col.m'), field: (row: any) => row.HotelMoeny.toFixed(2), align: 'left' },
        { name: 'PayType', label: t('hotelorder.col.pt'), field: (row: any) => (row.PayType == 1 ? t('hotelorder.payType.t1') : t('hotelorder.payType.t2')), align: 'left' },
        { name: 'HandFittingFee', label: t('hotelorder.hands'), align: 'left' }
      ] as any,
      importFileUrl: 'https://mallApi.oytour.com/api/File/UploadTencent?MallBaseId=1'
    })

    const methods = {
      goUrl(id: number) {
        currentRouter.push('/hotel/offer/' + id)
      },
      ViewPayment() {
        data.showBankAccount = true
      },
      initOrders() {
        let param = Object.assign(data.pages, search)
        //data.orders = []
        HotelService.GetHotelOrders(param)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              r.data.data.pageData.forEach((x: any) => {
                x.typeInfo = data.status.find(y => y.StatusId == x.OrderStatus) ?? data.status[1]
                x.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]
                    PeopleNum += z.PeopleNumber
                  })
                  console.log(PeopleNum)
                  y.PeopleNum = PeopleNum
                })
              })
              data.orders = r.data.data.pageData
              data.pages.pageCount = r.data.data.pageCount
            } else {
              message.errorMsg(r.data.message)
            }
            data.loading = false
          })
          .catch(e => {
            message.errorMsg(e.message)
            data.loading = false
          })
      },
      cancelConfirmHandler(orderId: number) {
        $q.dialog({
          title: t('dialog.titles.horder'),
          message: t('dialog.contents.horder'),
          cancel: true,
          persistent: true
        }).onOk(() => {
          methods.cancelOrderHandler(orderId)
        })
      },
      cancelOrderHandler(orderId: number) {
        if (data.loading) return
        data.loading = true
        HotelService.CancelHotelOrder(orderId)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              data.pages.pageIndex = 1
              this.initOrders()
            }
            data.loading = false
            message.errorMsg(r.data.message)
          })
          .catch(e => {
            message.errorMsg(e.message)
            data.loading = false
          })
      },
      setShowWarnHander(id: number) {
        data.expendsOrderId = id == data.expendsOrderId ? 0 : id
      },
      changePageHandler(n: any) {
        data.pages.pageIndex = n
        methods.initOrders()
      },
      uploadHandleChange(orderId: number) {
        data.uploadOrderId = orderId
        data.loading = true
      },
      init() {
        data.status = getHotelOrderStatus()
        data.rooms = getHotelRoomType()
        methods.initOrders()
      },
      modify(id: number) {
        currentRouter.push('/hotel/modify/' + id)
      },
      handleFinish(options: { file: UploadFileInfo; event?: ProgressEvent }) {
        data.loading = false
        let r = (options.event?.target as XMLHttpRequest).response
        if (r) {
          let res = JSON.parse(r)
          if (res.resultCode == ApiResult.SUCCESS && res.data) {
            methods.setGuestListHandler(res.data)
          } else {
            message.errorMsg(t('upload.failed'))
            data.loading = false
          }
        } else {
          message.errorMsg(t('upload.failed'))
          data.loading = false
        }
      },
      setGuestListHandler(url: string) {
        HotelService.SetGuestFile(data.uploadOrderId, url)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              message.successMsg(t('upload.success'))
              let order = data.orders.find(x => x.OrderId == data.uploadOrderId)
              order.GuestFileList = [url]
            } else {
              message.errorMsg(t('upload.failed'))
            }
            data.loading = false
          })
          .catch(r => {
            data.loading = false
            message.errorMsg(r.message)
          })
      },
      setCopyHandler(order: any, ctx?: string) {
        if (ctx) {
          data.copyId = -1
          copyToClipboard(ctx)
        } else {
          data.copyId = order.OrderId
          copyToClipboard(order.OrderNo)
        }

        setTimeout(() => {
          data.copyId = 0
        }, 2000)
      },
    }

    methods.init()
    return {
      ...toRefs(data),
      ...methods,
      moneyFormat
    }
  }
})
</script>

<style>
.light-border table,
.light-border table td,
.light-border .q-table__middle,
.light-border.borders,
.light-border table th {
  border-color: #eee !important;
}

.light-border .room-item {
  height: 28px;
  line-height: 28px;
  border-bottom: 1px solid #eee;
}

.light-border .room-item:last-child {
  border-bottom: none;
}

.light-border .max-hotelname {
  width: 140px;
  height: 28px;
  line-height: 28px;
}

.orderListDialog-title {
  position: relative;
}

.orderListDialog-title span {
  font-size: 20px;
}

.orderListDialog-close {
  position: absolute;
  right: 0;
  top: -10px;
  font-size: 26px;
}

.orderListDialog-bg {
  background: #5098FF;
  border-radius: 10px;
}

.orderListDialog-img {
  background: url('../../../../assets/images/wallet.png')no-repeat right #5098FF;
  background-size: 97px 100%;
}
</style>
