<template>
  <div class="fix-height-subpage column no-wrap" v-if="detailsObj">
    <div class="row q-pa-md" style="min-width: 375px; margin: 0 auto" :style="{ width: $q.screen.lt.xl ? '100%' : '1320px' }" :class="{'row':$q.screen.width>=1200 && $q.platform.is.desktop,'column':$q.screen.width<1200 || $q.platform.is.mobile}">
      <div class="col">
        <q-card class="q-pa-md" flat>
          <div class="text-h6 q-mb-md">{{ $t('v102.ticket.ti') }}</div>
          <div class="row q-pb-md q-mb-md" style="border-bottom: 1px solid #f1f1f1">
            <div class="q-mr-md">
              <q-img v-if="detailsObj.PicPathList&&detailsObj.PicPathList.length>0" :src="detailsObj.PicPathList[0]" :ratio="16 / 9" spinner-color="grey" spinner-size="50px" width="100px" fit="cover" class="rounded-borders">
                <template v-slot:error>
                  <div class="absolute-full flex flex-center bg-blue-1 text-dark fz12">
                    {{$t('v102.ticket.load')}}
                  </div>
                </template>
              </q-img>
            </div>
            <div class="col">
              <div class="text-subtitle1 text-weight-bolder cursor-pointer" @click="showCardHandler">{{detailsObj.Name}}</div>
              <div class="f14 text-grey-600">
                {{ $t('v102.ticket.ordertip') }}
              </div>
            </div>
          </div>
          <div>
            <div :class="{ 'q-px-lg': $q.platform.is.desktop }">
              <div class="q-mt-lg" :class="{'column q-mb-md':($q.screen.width<1200 || $q.platform.is.mobile),'row items-center':!($q.screen.width<1200 || $q.platform.is.mobile)}">
                <div class="f12 text-dark" :class="{ 'col-2': $q.platform.is.desktop, 'col-3': $q.platform.is.mobile,'q-mb-md':($q.screen.width<1200 || $q.platform.is.mobile) }">{{ $t('v102.ticket.pt') }}：</div>
                <div class="text-subtitle2 text-weight-bolder">
                  <q-field standout :model-value="msg.UseDate" class="text-dark cursor-pointer">
                    <template v-slot:control>
                      <div class="self-center full-width no-outline" tabindex="0">{{ msg.UseDate }}</div>
                    </template>
                    <q-popup-proxy :offset="[0, 10]" ref="qDateProxy">
                      <q-date v-model="msg.UseDate" :options="optionsFn" mask="YYYY/MM/DD" @update:model-value="getInfo"></q-date>
                    </q-popup-proxy>
                  </q-field>
                </div>
              </div>
            </div>
            <div :class="{ 'q-px-lg': $q.platform.is.desktop }">
              <div :class="{'column':($q.screen.width<1200 || $q.platform.is.mobile),'row items-center':!($q.screen.width<1200 || $q.platform.is.mobile)}">
                <div class="f12 text-dark" :class="{ 'col-2': $q.platform.is.desktop, 'col-3': $q.platform.is.mobile }">{{ $t('v102.ticket.tt') }}：</div>
                <div class="row items-center col wrap q-mt-md">
                  <div class="q-pa-sm rounded-borders q-mr-md q-mb-md cursor-pointer row items-center" :class="{ 'bg-grey-2': !x.checked, 'bg-primary text-white': x.checked }" @click="changeDetailListHandler(x)" v-for="x in types">
                    <template v-if="x.RemainingInventory>0">
                      <span style="border-right: 1px solid #eee" class="q-mr-sm q-pr-sm">{{ x.TicketName }}</span>
                      <span>{{ x.B2BPrice.toFixed(2) }}</span>
                    </template>
                  </div>
                </div>
              </div>
            </div>
            <div :class="{ 'q-px-lg': $q.platform.is.desktop }">
              <div class="row">
                <div class="f12 text-grey-900" :class="{ 'col-2': $q.platform.is.desktop, 'col-3': $q.platform.is.mobile }">{{ $t('v102.ticket.bc') }}：</div>
                <div v-if="isCheck">
                  <template v-for="x in types">
                    <q-input style="width: 100%" v-if="x.checked" class="q-mb-md" @update:model-value="changePeople" v-model="x.num" mask="#" reverse-fill-mask dense standout>
                      <template v-slot:prepend>
                        <q-btn color="primary" size="sm" class="q-px-none" flat icon="remove" @click="addPeople(x, 0)" />
                      </template>
                      <template v-slot:append>
                        <div class="q-mr-sm f12">{{ $t('v102.ticket.unit') }} {{ x.name }}</div>
                        <q-btn color="primary" size="sm" class="q-px-none" flat icon="add" @click="addPeople(x, 1)" />
                      </template>
                    </q-input>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </q-card>

        <q-card class="q-pa-md q-mt-lg" flat>
          <div>
            <div class="text-h6 q-mb-md">{{ $t('v102.ticket.gi') }}</div>
            <div class="row items-center">
              <span class="f12 text-grey-900 text-subtitle2 text-weight-bold" :class="{ 'col-2': $q.platform.is.desktop, 'col-3': $q.platform.is.mobile }">{{ $t('v102.ticket.gi') }}：</span>
              <span class="col f12">
                <q-radio v-model="msg.MailingState" checked-icon="task_alt" unchecked-icon="panorama_fish_eye" val="1" :label="$t('v102.ticket.zq')" />
                <q-radio v-model="msg.MailingState" checked-icon="task_alt" unchecked-icon="panorama_fish_eye" val="2" :label="$t('v102.ticket.yj')" />
              </span>
            </div>
            <div v-if="msg.MailingState == '1'" class="bg-light-blue-1 q-pa-md fz14 rounded-borders q-mt-md">
              <div class="text-weight-bold">{{ $t('v102.ticket.zqs') }}</div>
              <div class="text-grey-900 q-mt-sm f12">{{ $t('v102.ticket.zqd') }}</div>
            </div>
            <div>
              <div class="q-mt-md">
                <span class="f12 text-grey-900 text-subtitle2 text-weight-bold">{{ msg.MailingState==1?$t('v102.ticket.sj'):$t('v102.ticket.youji') }}</span>
              </div>
              <div class="row items-center q-mt-md text-grey-600 q-mb-md" v-if="$q.platform.is.desktop">
                <div class="col q-mr-md">{{ $t('v102.ticket.sjc.c1') }}</div>
                <div class="col q-mr-md">{{ $t('v102.ticket.sjc.c2') }}</div>
                <div class="col-2 q-mr-md">{{ $t('v102.ticket.sjc.c3') }}</div>
                <div class="col q-mr-md">{{ $t('v102.ticket.sjc.c4') }}</div>
                <div class="col-4" v-if="msg.MailingState == '2'">{{ $t('v102.ticket.sjc.c5') }}</div>
              </div>
              <div style="border-top: 1px dashed #eee" :class="{'row items-center':$q.platform.is.desktop,'column':$q.platform.is.mobile}">
                <q-input dense standout v-model="msg.Name" class="col q-mt-md" :class="{'q-mr-md':$q.platform.is.desktop}" :placeholder="$t('v102.ticket.sjcp.c1')"  :rules="[ val => val && val.length > 0 || ' ']" ref="guestName"/>
                <q-input dense standout v-model="msg.EName" class="col q-mt-md" :class="{'q-mr-md':$q.platform.is.desktop}"  :placeholder="$t('v102.ticket.sjcp.c2')" :rules="[ val => val && val.length > 0 || ' ']" ref="guestEName"/>
                <div class="col-2 q-mr-md">
                <q-radio v-model="msg.Sex" checked-icon="task_alt" unchecked-icon="panorama_fish_eye" val="1" :label="$t('v102.ticket.sex.man')" />
                <q-radio v-model="msg.Sex" checked-icon="task_alt" unchecked-icon="panorama_fish_eye" val="2" :label="$t('v102.ticket.sex.women')" />
              </div>
                <q-input dense standout v-model="msg.Mobile" class="col q-mt-md" :class="{'q-mr-md':$q.platform.is.desktop}"  :placeholder="$t('v102.ticket.sjcp.c4')" :rules="[ val => val && val.length == 11 || ' ']" ref="guestMobile"/>
                <q-input v-if="msg.MailingState == '2'" dense standout v-model="msg.MailingAddress" class="col-4 q-mt-md"  :placeholder="$t('v102.ticket.sjcp.c5')" :rules="[ val => val && val.length > 0 || ' ']" ref="guestAddress"/>
              </div>
            </div>
            <div class="q-mt-md">
              <q-input v-model="msg.Remark" standout autogrow :label="$t('v102.ticket.or') " />
            </div>
          </div>
        </q-card>

        <div class="q-mt-lg" v-if="!($q.screen.width<1200 || $q.platform.is.mobile)">
          <div class="bg-orange-1 q-pa-md rounded-borders fz14" style="border: 1px dashed orange">
            <div class="text-weight-bold">{{ $t('v102.ticket.d5') }}</div>
            <div class="text-grey-700 q-mt-sm">
              {{detailsObj.BookingInfo}}
            </div>
          </div>
        </div>
      </div>

      <div class="" :class="{'q-ml-lg':!($q.screen.width<1200 || $q.platform.is.mobile),'q-mt-lg':($q.screen.width<1200 || $q.platform.is.mobile)}">
        <div class="rounded-borders bg-white q-pa-md" style="width: 300px" :style="{'width':($q.screen.width<1200 || $q.platform.is.mobile)?'100%':'300px'}">
          <div class="text-h6 text-grey-900">{{ $t('v102.ticket.st') }}</div>
          <div class="q-mt-md q-mb-lg">
            <div class="bg-red-1 q-pa-sm rounded-borders fz14" style="border: 1px dashed var(--q-negative)">
              <div class="text-grey-900 text-subtitle2 text-weight-bold">{{ $t('v102.ticket.rtt') }}</div>
              <div class="text-grey-700 q-mt-sm f12">{{ $t('v102.ticket.rtc') }}</div>
            </div>
          </div>
          <div class="q-pt-md q-mb-lg" style="border-top: 1px dashed #eee">
            <div class="text-grey-900 text-subtitle2 text-weight-bold">{{ $t('v102.ticket.ms') }}</div>
            <div v-if="isCheck">
              <template v-for="x in types">
                <div class="row items-center q-mt-md" v-if="x.checked">
                  <q-badge color="grey-3" style="padding: 5px 8px" text-color="info" :label="x.TicketName" />
                  <div class="col f12 text-right">{{x.B2BPrice.toFixed(2)}} x {{x.num}}{{ $t('v102.ticket.unit') }}</div>
                </div>
              </template>
            </div>
            <div v-else class="text-center text-grey-600 q-py-lg">{{ $t('v102.ticket.nt') }}</div>
          </div>
          <div class="q-pt-md q-mb-lg text-right" style="border-top: 1px dashed #eee">
            <span class="f12 text-dark q-mr-md">
              {{ $t('v102.ticket.ds') }}：
            </span>
            <span class="text-h6 text-negative">
              {{ msg.Money.toFixed(2) }}
            </span>
          </div>
          <div class="text-right">
            <q-btn color="primary" unelevated class="q-px-lg" :disable="!isCheck" :label="$t('v102.ticket.sb')" @click="submit"/>
          </div>
        </div>
      </div>

      <div class="q-mt-lg" v-if="($q.screen.width<1200 || $q.platform.is.mobile)">
          <div class="bg-orange-1 q-pa-md rounded-borders fz14" style="border: 1px dashed orange">
            <div class="text-weight-bold">{{ $t('v102.ticket.d5') }}</div>
            <div class="text-grey-700 q-mt-sm">
              {{detailsObj.BookingInfo}}
            </div>
          </div>
        </div>
    </div>
  </div>
  <q-dialog v-model="showDetails">
    <ticket-card :ticket="detailsObj"></ticket-card>
  </q-dialog>
</template>

<script lang="ts">
import { useRouter } from 'vue-router'
import { ApiResult } from 'src/@types/enumHelper'
import TicketService from '../../api/ticket'
import message from '../../utils/message'
import { currentRouter } from 'src/router'
import { ref, inject, provide, reactive, toRefs, defineComponent, watch } from 'vue'
import useMetaModule from '../../module/meta/metaModule'
import { useI18n } from 'vue-i18n'
import { DirtionmaryHelper } from '../../config/dictionary'
import TicketCard from '../../components/ticket/TicketCard.vue'
import { date } from 'quasar'
export default defineComponent({
  components: { TicketCard },
  setup(props) {
    const $router = useRouter()
    let { setTitle } = useMetaModule()
    const { t } = useI18n()
    const pageTitle = inject(DirtionmaryHelper.PAGE_TITLE_KEY) as any
    pageTitle.value = t('v102.ticket.preview.pageTitle')
    setTitle(pageTitle.value)

    const data = reactive({
      showDetails: false,
      loading: false,
      msg: {
        OrderId: 0,
        Money: 0.0,
        Remark: '',
        MailingState: '1',//邮寄状态 1自取 2邮寄
        MailingAddress: '',//MailingState =2 填写邮寄
        UseDate:'',//门票日期
        Name:'',
        EName:'',
        Sex: '1',//1男2女
        Birthday: '',
        Mobile:'',
        CouponsId:'',//景点id
        DetailList:[] as any,
      },
      types: [],
      isCheck: false,
      OpenTime: '',
      detailsObj: {} as any,
    })
    const guestName = ref(null) as any
    const guestEName = ref(null) as any
    const guestMobile = ref(null) as any
    const guestAddress = ref(null) as any
    let time = currentRouter.currentRoute.value.params.Time
    data.OpenTime = time.substring(0,4)+'-'+time.substring(4,6)+'-'+time.substring(6,8)
    
    data.msg.CouponsId = currentRouter.currentRoute.value.params.ticketId
    // date.formatDate(date.addToDate(new Date(), { days: 1 }), 'MM月DD日 ddd')
    data.msg.UseDate = date.formatDate(date.addToDate(new Date(), { days: 0 }), 'YYYY/MM/DD')
    
    const menu = inject(DirtionmaryHelper.MENU_KEYS) as any
    menu.value = 8
    const methods = {
      getInfo(value:String, reason:any, details:any){
        if(data.OpenTime||value){
          let param = {
            CouponsId:data.msg.CouponsId,
            OpenTime: value?value:data.OpenTime
          }
          TicketService.getTicketInfo(param)
            .then(r => {
              if (r.data.resultCode == ApiResult.SUCCESS) {
                data.detailsObj = r.data.data
                let addList = function (arr) {
                    arr.forEach(item => {
                      item.checked = false
                      item.num = 1
                    });
                };
                addList(r.data.data.TicketPriceList);
                data.types = r.data.data.TicketPriceList
                if(data.types&&data.types.length==0){
                  message.errorMsg(`${t('v102.ticket.nobj')}`)
                }
              } else {
                message.errorMsg(r.data.message)
              }
            }).catch(e => {
              message.errorMsg(e.message)
              data.isCheck = false
            })
        }
      },
      submit(){
        methods.getNum()
        if(!data.isCheck) return
        if(data.loading) return
        data.loading = true
        let flag = false
        guestName.value.validate()
        guestEName.value.validate()
        guestMobile.value.validate()
          if(data.msg.MailingState=='2'){
            guestAddress.value.validate()
            flag = !guestName.value.hasError && !guestEName.value.hasError && !guestMobile.value.hasError && !guestAddress.value.hasError
          }else{
            flag = !guestName.value.hasError && !guestEName.value.hasError && !guestMobile.value.hasError
            data.msg.MailingAddress = ''
          }
          if(!flag) return
          data.msg.DetailList = [] as any
          data.types.forEach(x=>{
            if(x.checked){
              let y = {
                TicketType: x.TicketCouponsType,
                TicketName: x.TicketName,
                Unit_Price: x.B2BPrice,
                Num: x.num,
                Money: x.B2BPrice*x.num,
                TicketId: x.TicketID
              }
              data.msg.DetailList.push(y)
            }
          })
        let param = Object.assign(data.msg)
        TicketService.setTicketOrder(param)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              message.successMsg(`${t('success')}`)
              $router.push({ path:'/ticket/order' })
            } else {
              message.errorMsg(r.data.message)
            }
            methods.getInfo()
            data.loading = false
          }).catch(e => {
            data.loading = false
            message.errorMsg(e.message)
          })
      },
      showCardHandler() {
        data.showDetails = true
      },
      optionsFn(cd: any) {
        return cd >= date.formatDate(date.addToDate(new Date(), { days: 0 }), 'YYYY/MM/DD')
      },
      changeDetailListHandler(e: any) {
        if (e.checked) {
          e.num = 1
        }
        e.checked = !e.checked
        data.isCheck = data.types.findIndex(x => x.checked) > -1
        if(data.isCheck){
          methods.calcMoneyHandler()
        }else{
          data.msg.Money=0.0
        }
      },
      addPeople(item: any, type: any) {
        if (type == 1) {
          item.num++
        } else if (type == 0 && item.num > 1) {
          item.num--
        }
        item.num = item.num != '' ? item.num : '1'
        methods.calcMoneyHandler()
      },
      changePeople(val: string) {
        methods.getNum()
      },
      getNum(){
        data.types.forEach(x=>{
            if(x.num>x.RemainingInventory){
              x.num = x.RemainingInventory
            }
        })
        setTimeout(()=>{
          methods.calcMoneyHandler()
        },50)
      },
      calcMoneyHandler(){
        data.msg.Money=0.0
        data.types.forEach(x=>{
          if(x.checked){
            data.msg.Money+=x.B2BPrice*x.num
          }
        })
      }
    }
    methods.getInfo()

    return {
      ...toRefs(data),
      ...methods,
      guestName,
      guestEName,
      guestMobile,
      guestAddress
    }
  }
})
</script>

<style></style>
