<template>
    <div class="fix-height-subpage column no-wrap">
        <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.vehicle.tuanduixinxi')}}</div>
              <div class="row q-pb-md q-mb-md" style="border-bottom: 1px solid #f1f1f1">
                <div class="col">
                  <div class="fz14 text-grey-600">
                    {{ $t('v102.CharteredBus.ordertip') }}
                  </div>
                </div>
              </div>
              <div>
                <div class="row items-center">
                    <q-input type="number" dense standout v-model="search.PeopleNum" class="" :class="{'col q-mr-md':$q.platform.is.desktop,'col-12 q-mt-sm':$q.platform.is.mobile}" :placeholder="$t('v102.vehicle.title6')" :rules="[ val => val && val > 0 || ' ']" ref="guestPeopleNum" @update:model-value="checkPeopleNum"/>
                    <q-field :class="{'q-py-md':$q.platform.is.desktop,'q-pt-sm':$q.platform.is.mobile}" standout :model-value="search.StartDate" class="col height text-dark cursor-pointer q-mr-md" ref="guestStartDate">
                    <template v-slot:control>
                        <div class="self-center full-width no-outline" tabindex="0">
                        <template v-if="search.StartDate">{{search.StartDate}}</template>
                        <span v-else class="text-grey-6">{{$t('v102.vehicle.title7') }}</span>
                        </div>
                    </template>
                    <q-popup-proxy :offset="[0, 10]" ref="qDateProxy">
                        <q-date v-model="search.StartDate" :options="optionsFn" mask="YYYY-MM-DD"
                            @update:model-value="dateRangeHandler">
                        </q-date>
                    </q-popup-proxy>
                    </q-field>
                    <q-input type="number" dense standout v-model="search.UseDayNum" class="col" :class="{'q-pt-sm':$q.platform.is.mobile}" :placeholder="$t('v102.vehicle.title8')" :rules="[ val => val && val > 0 || ' ']" @update:model-value="checkInteger" ref="guestUseDayNum"/>
                  </div>
                  <div class="row items-center">
                    <q-input dense standout v-model="search.GoFlightInfo" class="col q-mr-md" :class="{'q-mt-sm':$q.platform.is.mobile}"  :placeholder="$t('v102.vehicle.title4')" :rules="[ val => val && val.length > 0 || ' ']" ref="guestGoFlightInfo"/>
                    <q-input dense standout v-model="search.BackFlightInfo" class="col" :class="{'q-mr-md':$q.platform.is.desktop,'q-mt-sm':$q.platform.is.mobile}" :placeholder="$t('v102.vehicle.title5')"  :rules="[ val => val && val.length > 0 || ' ']" ref="guestBackFlightInfo"/>
                    <q-input dense standout v-model="search.PickUpInfo" class="" :class="{'col':$q.platform.is.desktop,'col-12 q-mt-sm':$q.platform.is.mobile}" :placeholder="$t('v102.vehicle.title3')" :rules="[ val => val && val.length > 0 || ' ']" ref="guestPickUpInfo"/>
                  </div>
                  <div class="row items-center">
                    <q-input dense standout v-model="search.GuideInfo" class="col q-mr-md" :class="{'q-pt-md':$q.platform.is.desktop,'q-pt-sm':$q.platform.is.mobile}" :placeholder="$t('v102.vehicle.title10')"  :rules="[ val => val && val.length > 0 || ' ']" ref="guestGuideInfo"/>
                    <q-input dense standout v-model="search.TeamName" class="col" :class="{'q-pt-md':$q.platform.is.desktop,'q-mr-md':$q.platform.is.desktop,'q-pt-sm':$q.platform.is.mobile}"  :placeholder="$t('v102.vehicle.title11')" :rules="[ val => val && val.length > 0 || ' ']" ref="guestTeamName"/>
                    <q-select class="q-pb-md" :class="{'col q-pt-md':$q.platform.is.desktop,'col-12 q-pt-sm':$q.platform.is.mobile}"  unelevated v-model="search.BusType" dense :options="vehicletop" filled emit-value option-label="labelName" option-value="Id" map-options :label="$t('v102.vehicle.title13')" standout :rules="[ val => val || '']" ref="guestUseBusType">
                    </q-select>
                  </div>
              </div>
            </q-card>
    
            <q-card class="q-pa-md q-mt-lg" flat>
              <div>
                <div class="text-h6 q-mb-md">{{ $t('v102.vehicle.dindanxinxi') }}</div>
                <q-table separator="cell" :hide-bottom="search.details.length>0?true:false" :pagination="{ rowsPerPage: 100000 }" :rows="search.details" bordered :columns="cols" class="sticky-right-column-table light-border col no-shadow">
                    <template v-slot:body-cell-UseDate="props">
                        <q-td :props="props" style="width: 160px;">
                            {{props.row.UseDate}}
                            <span class="q-pl-sm text-grey-6">{{$t('v102.vehicle.di')}}{{props.row.DayNum}}{{$t('v102.vehicle.tian')}}</span>
                        </q-td>
                    </template>
                    <template v-slot:body-cell-UseType="props">
                        <q-td :props="props" style="width: 150px;">
                            <q-select unelevated v-model="props.row.UseType" dense :options="listvehicle" emit-value option-label="Name" option-value="Id" map-options :label="$t('v102.vehicle.title9')" standout :rules="[ val => val || '']" :ref="guestUseType" >
                            </q-select>
                        </q-td>
                    </template>
                    <template v-slot:body-cell-TripInfo="props">
                        <q-td :props="props">
                            <!-- <div class="ellipsis w100">{{props.row.TripInfo?props.row.TripInfo:$t('v102.CharteredBus.sjcp.c9')}}</div> -->
                            <q-input dense standout autofocus v-model="props.row.TripInfo" readonly :placeholder="$t('v102.CharteredBus.sjcp.c9')" :rules="[ val => val && val.length > 0 || ' ']" :ref="guestTripInfo" />
                            <q-popup-edit v-model="props.row.TripInfo" buttons>
                                <q-input type="textarea" dense standout autofocus v-model="props.row.TripInfo" :placeholder="$t('v102.CharteredBus.sjcp.c9')" /> 
                            </q-popup-edit>
                        </q-td>
                    </template>
                    <template v-slot:body-cell-operation="props">
                        <q-td :props="props" style="width: 90px;">
                            <q-btn class="q-ml-sm" color="warning" size="sm" unelevated :label="$t('v102.vehicle.tatle.th6')" @click="deleteLine(props.rowindex)"/>
                        </q-td>
                      </template>
                </q-table>
                <div class="q-mt-lg">
                    <q-input v-model="search.CreateRemark" 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">
                    
                  </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.vehicle.ms') }}</div>
              <div class="q-pt-md q-mb-lg" style="border-top: 1px dashed #eee">
                <div v-if="isCheck">
                  <template v-for="x in search.details">
                    <div class="row items-center q-mt-md">
                      <q-badge color="grey-3" style="padding: 5px 8px" text-color="info" :label="`${x.UseDate}${x.UseType&&listvehicle.length>0&&listvehicle.filter(y => y.Id==x.UseType)[0].Name}`" />
                      <div class="col f12 text-right">
                        {{ $t('v102.vehicle.di') }}{{x.DayNum}}{{ $t('v102.vehicle.tian') }}
                      </div>
                    </div>
                  </template>
                </div>
                <div v-else class="text-center text-grey-600 q-py-lg">{{ $t('v102.vehicle.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.vehicle.ds') }}：
                </span>
                <span class="text-h6 text-negative">
                  {{ search.details.length }}
                </span>
              </div>
              <div class="text-right">
                <q-btn :loading="loading" color="primary" unelevated class="q-px-lg" :disable="!isCheck" :label="`${!search.Id?$t('v102.ticket.sb'):$t('v102.CharteredBus.bianji')}`" @click="submit"/>
              </div>
            </div>
          </div>
    
        </div>
      </div>
</template>
<script lang="ts">
import useMetaModule from '../../module/meta/metaModule'
import HotelService from '../../api/vehicle'
import { DirtionmaryHelper } from '../../config/dictionary'
import { defineComponent, toRefs, watch, reactive, inject, ref, onMounted } from 'vue'
import { ApiResult } from '../../@types/enumHelper'
import useScrollModule from '../../module/scrollbar/scrollModule'
import { date } from 'quasar'
import { useI18n } from 'vue-i18n'
import message from '../../utils/message'
import { currentRouter } from 'src/router'
import { useRouter } from 'vue-router'
import Store from '../../store'
export default defineComponent({
    // props: {
    //     Id: {
    //         type: Number,
    //         default: 0,
    //         require: true
    //     }
    // },
    setup(props, context) {
        const $router = useRouter()
        const qDateProxy = ref(null) as any
        const guestUseCompName = ref(null) as any
        const guestUseName = ref(null) as any
        const guestPickUpInfo = ref(null) as any
        const guestGoFlightInfo = ref(null) as any
        const guestBackFlightInfo = ref(null) as any
        const guestPeopleNum = ref(null) as any
        const guestStartDate = ref(null) as any
        const guestUseDayNum = ref(null) as any
        const guestGuideInfo = ref(null) as any
        const guestTeamName = ref(null) as any
        const guestUseBusType = ref(null) as any

        const refArr = ref([]);
        const guestUseType = (el) => {
            refArr.value.push(el);
        };
        const refArrB = ref([]);
        const guestTripInfo = (el) => {
            refArrB.value.push(el);
        };

        const { t } = useI18n()
        let { setTitle } = useMetaModule()
        const pageTitle = inject(DirtionmaryHelper.PAGE_TITLE_KEY) as any
        pageTitle.value = t('v102.vehicle.pageTitle2')
        setTitle(pageTitle.value)
        const data = reactive({
            isCheck: false,
            timeData: null,
            loading: false,
            carTypes: [] as any,
            search: {
                Id: 0,
                UseCompName: "",//订车单位
                UseName: "",//订车人
                PickUpInfo: "",//接机信息
                GoFlightInfo: "",//去程航班
                BackFlightInfo: "",//回程航班
                PeopleNum: null as Number,//用车人数
                UseDayNum: null as Number,//行程天数
                StartDate: "",//开始日期
                BusType: null,//用车类型(接口返下拉列表)
                GuideInfo: "",//导游信息
                TeamName: "",//团队信息
                CreateRemark: "",//备注
                details: [
                    // {
                    //     DayNum: null,//第几天
                    //     UseDate: "",//日期
                    //     UseType: null,//用车类型（接口返下拉列表）
                    //     TripInfo: "",//行程信息
                    // }
                ] as Array<any>
            },
            vehicletop: [],//上面车辆
            listvehicle: [],//车辆类型
            OpenTime: '',
            dateRangeFormat: '',
            h: {} as any,
            scrollStyle: {} as any,
            pages: '',
            cols: [
                { name: 'UseDate', label: t('v102.vehicle.tatle.th1'), field: (row: any) => row.UseDate, align: 'left' },
                // { name: 'DayNum', label: t('v102.vehicle.tatle.th2'), field: (row: any) => row.DayNum, align: 'left' },
                { name: 'UseType', label: t('v102.vehicle.tatle.th3'), field: (row: any) => row, align: 'left' },
                { name: 'TripInfo', label: t('v102.vehicle.tatle.th4'), field: (row: any) => row, align: 'left' },
                { name: 'operation', label: t('v102.vehicle.tatle.th5'), field: (row: any) => row, align: 'left' }
            ] as any[],
            SeatNum: 0
        })
        if (currentRouter.currentRoute && currentRouter.currentRoute.value.params.Id) {
            data.search.Id = currentRouter.currentRoute.value.params.Id
        }

        // data.pages = currentRouter.currentRoute.value.params.pages
        // 获取车型下拉
        onMounted(() => {
            methods.vehicleinit()
            methods.vehicleList()
            if (data.search.Id && data.search.Id > 0) {
                setTimeout(()=>{
                    methods.details()
                },100)
            }
            let userDetail = Store.state.user.userDetail
            let salesBaseInfo = Store.state.user.userDetail.salesBaseInfo
            data.search.UseCompName  = salesBaseInfo.groupName //订车单位
            data.search.UseName  = userDetail.name//订车人
        })
        const methods = {
            // 删除
            deleteLine(index){
                data.search.details.splice(index,1)
                data.search.UseDayNum = data.search.details.length
            },
            // 获取车型座位数
            getBusType(){
                return
                if(data.vehicletop&&data.vehicletop.length>0){
                    data.vehicletop.forEach(x=>{
                    if(x.Id===data.search.BusType){
                        data.SeatNum = x.SeatNum
                        if(data.search.PeopleNum>x.SeatNum){
                            data.search.PeopleNum = x.SeatNum
                        }
                    }
                    })
                }
            },
            checkPeopleNum(){
                data.vehicletop.forEach((x:any)=>{
                    x.disable = x.SeatNum<data.search.PeopleNum?true:false
                })
                // if(data.search.PeopleNum>data.SeatNum){
                //     data.search.PeopleNum = data.SeatNum
                // }
            },
            // 获取修改详情
            details() {
                HotelService.VehicleDetails(data.search.Id)
                    .then(r => {
                        if (r.data.resultCode == ApiResult.SUCCESS) {
                            let userDetail = Store.state.user.userDetail
                            let salesBaseInfo = Store.state.user.userDetail.salesBaseInfo
                            
                            data.search.UseCompName = r.data.data.UseCompName?r.data.data.UseCompName:salesBaseInfo.groupName
                            data.search.UseName = r.data.data.UseName?r.data.data.UseName:userDetail.name
                            data.search.PickUpInfo = r.data.data.PickUpInfo
                            data.search.GoFlightInfo = r.data.data.GoFlightInfo
                            data.search.BackFlightInfo = r.data.data.BackFlightInfo
                            data.search.PeopleNum = String(r.data.data.PeopleNum)
                            data.search.UseDayNum = String(r.data.data.UseDayNum)
                            data.search.StartDate = r.data.data.StartDate.slice(0, 10)
                            data.search.BusType = r.data.data.BusType
                            data.search.GuideInfo = r.data.data.GuideInfo
                            data.search.TeamName = r.data.data.TeamName
                            data.search.details = r.data.data.details
                            data.search.CreateRemark = r.data.data.CreateRemark
                            data.isCheck = true
                            methods.getBusType()
                        }else{
                            message.errorMsg(r.data.message)
                        }
                    })
                    .catch(e => {
                        message.errorMsg(e.message)
                    })
            },
            // 获取车型下拉
            async vehicleinit() {
                await HotelService.TypeVehicle({})
                    .then(r => {
                        if (r.data.resultCode == ApiResult.SUCCESS) {
                            r.data.data.forEach((x:any)=>{
                                x.labelName = `${x.Name}(${x.SeatNum}${t('v102.vehicle.zuo')})`
                                    
                            })
                            data.vehicletop = r.data.data
                        } else {
                            message.errorMsg(r.data.message)
                        }
                    })
                    .catch(e => {
                        message.errorMsg(e.message)
                    })
            },
            // 获取列表用车类型
            vehicleList() {
                HotelService.listTypeVehicle({})
                    .then(r => {
                        if (r.data.resultCode == ApiResult.SUCCESS) {
                            data.listvehicle = r.data.data
                        } else {
                            message.errorMsg(r.data.message)
                        }
                    })
                    .catch(e => {
                        message.errorMsg(e.message)
                    })
            },
            // 获取时间
            getDay(set: any, day: any) {
                var today = new Date(set);
                var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
                today.setTime(targetday_milliseconds); //注意，这行是关键代码

                var tYear = today.getFullYear();
                var tMonth = today.getMonth();
                var tDate = today.getDate();
                tMonth = methods.doHandleMonth(tMonth + 1);
                tDate = methods.doHandleMonth(tDate);
                return tYear + "-" + tMonth + "-" + tDate;
            },
            doHandleMonth(month: any) {
                var m = month;
                if (month.toString().length == 1) {
                    m = "0" + month;
                }
                return m;
            },
            // 时间计算
            getDiffDate(start: any, end: any) {
                const startTime = methods.getDate(start);
                const endTime = methods.getDate(end);
                const dateArr = [];
                while ((endTime.getTime() - startTime.getTime()) > 0) {
                    const year = startTime.getFullYear();
                    const month = startTime.getMonth().toString().length === 1 ? '0' + (parseInt(startTime.getMonth().toString(), 10) + 1) : (startTime.getMonth() + 1);
                    const day = startTime.getDate().toString().length === 1 ? '0' + startTime.getDate() : startTime.getDate();
                    dateArr.push(year + '-' + month + '-' + day);
                    startTime.setDate(startTime.getDate() + 1);
                }
                return dateArr;
            },
            getDate(datestr: any) {
                const temp = datestr.split('-');
                if (temp[1] === '01') {
                    temp[0] = parseInt(temp[0], 10) - 1;
                    temp[1] = '12';
                } else {
                    temp[1] = parseInt(temp[1], 10) - 1;
                }
                const date = new Date(temp[0], temp[1], temp[2]);
                return date;
            },
            // 点击时间选项
            dateRangeHandler(e: any) {
                if (qDateProxy.value) qDateProxy.value.hide()
                methods.checkInteger()
            },
            // 测试
            // 天数失去焦点时间
            checkInteger() {
                if(data.search.UseDayNum<data.search.details.length){
                    for (let i = 0; i < (data.search.details.length-data.search.UseDayNum); i++){
                        data.search.details.splice(data.search.details.length-1,1)
                    }
                }else{
                    let details2 = [] as any
                    let timelist = [] as any
                    if (data.search.UseDayNum && data.search.UseDayNum > 0) {
                        let list = methods.getDay(data.search.StartDate, data.search.UseDayNum)
                        if (list) {
                            timelist = methods.getDiffDate(data.search.StartDate, list)
                            if (timelist && timelist.length > 0) {
                                timelist.forEach((item: any, i: any) => {
                                    let dataObj = {
                                        DayNum: i + 1,
                                        UseDate: item,//日期
                                        UseType: '',//用车类型（接口返下拉列表）
                                        // UseTime: '',//接送机时间
                                        TripInfo: '',//行程信息
                                    }
                                    details2.push(dataObj)
                                    if(data.search.details&&data.search.details.length==0){
                                        data.search.details = details2
                                    }else{
                                        let UseDateArr = data.search.details.map(x=>{return x.UseDate})
                                        if(UseDateArr.indexOf(item)==-1){
                                            data.search.details.push(dataObj)
                                            data.search.details.sort((a,b)=>{
                                                let obj1 = a['UseDate']
                                                let obj2 = b['UseDate']
                                                const val1 = Math.floor(new Date(obj1).getTime() / 1000)
                                                const val2 = Math.floor(new Date(obj2).getTime() / 1000)
                                                return val1 - val2
                                            })
                                        }
                                    }
                                })
                                
                                
                            }
                        }
                    }
                }
                
                if(data.search.details.length>0){
                    data.isCheck = true
                }
                // console.log('时间差2', details2)
            },
            // 关闭
            down() {
                $router.push({ path: `/vehicle/order/0/0` })
            },
            // 确定
            submit() {
                guestPickUpInfo.value.validate()
                guestGoFlightInfo.value.validate()
                guestBackFlightInfo.value.validate()
                guestPeopleNum.value.validate()
                guestStartDate.value.validate()
                guestUseDayNum.value.validate()
                guestGuideInfo.value.validate()
                guestTeamName.value.validate()
                guestUseBusType.value.validate()

                let flag = false
                // !guestUseCompName.value.hasError && !guestUseName.value.hasError &&
                flag = !guestPickUpInfo.value.hasError && !guestGoFlightInfo.value.hasError && !guestBackFlightInfo.value.hasError && !guestPeopleNum.value.hasError && !guestStartDate.value.hasError && !guestUseDayNum.value.hasError && !guestGuideInfo.value.hasError && !guestTeamName.value.hasError && !guestUseBusType.value.hasError

                let guestRefArr = false
                for(let i=0;i<data.search.details.length;i++){
                    refArr.value[i].validate()
                    refArrB.value[i].validate() 
                    guestRefArr= !refArr.value[i].hasError&&!refArrB.value[i].hasError
                }

                if(!flag) return
                if(!guestRefArr) return
                data.loading = true
                HotelService.vehicletripbus(data.search)
                    .then(r => {
                        data.loading = false
                        if (r.data.resultCode == ApiResult.SUCCESS) {
                            data.isCheck = false
                            context.emit('refresh')
                            $router.push({ path: '/vehicle/order/0/0' })
                        } else {
                            message.errorMsg(r.data.message)
                        }
                    })
                    .catch(e => {
                        data.loading = false
                        message.errorMsg(e.message)
                    })

            },
            optionsFn(cd: any) {
                return cd >= date.formatDate(date.addToDate(new Date(), { days: 1 }), 'YYYY/MM/DD')
            },
        }
        return { ...toRefs(data), ...methods, 
            qDateProxy,
            guestUseCompName,
            guestUseName,
            guestPickUpInfo,
            guestGoFlightInfo,
            guestBackFlightInfo,
            guestPeopleNum,
            guestStartDate,
            guestUseDayNum,
            guestGuideInfo,
            guestTeamName,
            guestUseBusType,
            guestUseType,
            guestTripInfo,
        }
    }

})
</script>
<style scoped>
.flex2 {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

}

.td-title {
    font-size: 12px;
    font-weight: 400;
    color: #a8a8b3;
}
:deep(.height.q-field--auto-height .q-field__control){
    min-height: 40px !important;
}
:deep(.height.q-field--auto-height .q-field__native){
    min-height: 40px !important;
}
:deep(.q-field--with-bottom){
    padding-bottom: 0;
}
:deep(.scroll){
    /* overflow: inherit; */
}
:deep(.q-field--dense .q-field__bottom){
    display: none;
}
</style>