<template>
    <view>
        <view class="arrow-up">
            <u-icon class="icon" name="arrow-up" @click="isShow=true" color="#2979ff" size="26"></u-icon>
        </view>
    <u-popup :show="isShow" @close="close" :closeOnClickOverlay="true">
        <!-- <view class="popup-icon">
            <u-icon class="icon" name="arrow-up" @click="isShow=false" color="#2979ff" size="26"></u-icon>
        </view> -->
		<view class="munes">
			<view v-for="(item,index) in typeList" :key="index"
				class="munes-item"
				:class="{
					'munes-item-active': item.value == tabStyle
				}"
				@click="handleActive(item)"
			>
				<text>{{item.label}}</text>
			</view>
		</view>
		<view class="container">
			<u--form label-width="auto" labelAlign="right"
				ref="uForm"
				:model="model"
				:rules="rules"
				:labelStyle="{
					fontSize: '28rpx',
					fontWeight: '500',
				}"
			>
				<u-cell-group :border="false">

					<view v-if="tabStyle == 'vehicle'" key="vehicle">
						<u-cell title="车辆" :border="true" :isLink="true" 
							@click="$refs.carChooseRef.show()"
						>						
							<view slot="value">
								<u-form-item label="" prop="form.vehicleId">
									{{renderItem(model.form,'plate','')}}
								</u-form-item>
							</view>	
						</u-cell>
						<tq-car-user ref="carChooseRef"
							:isGetIcon="true"
							@confirm="(data) => {
								$store.dispatch('setMapImg',data.img)
								model.form.vehicleId = data.id
								model.form.plate = data.label
								$refs.uForm.validateField('form.vehicleId')
							}"
							@onDataLoad="handleDataLoad"
						>
						</tq-car-user>
					</view>
					
					<view v-else-if="tabStyle == 'personnel'" key="personnel">
						<u-cell title="人员" :border="true" :isLink="true" 
							@click="$refs.userChooseRef.show()"
						>						
							<view slot="value">
								<u-form-item label="" prop="form.userId">
									{{renderItem(model.form,'userName','')}}
								</u-form-item>
							</view>	
						</u-cell>
						<tq-car-user ref="userChooseRef"
							:isGetIcon="true"
							:queryType="1"
							@confirm="(data) => {
								$store.dispatch('setMapImg',data.img)
								model.form.userId = data.id
								model.form.userName = data.label
								$refs.uForm.validateField('form.userId')
							}"
							@onDataLoad="handleDataLoad"
						>
						</tq-car-user>
					</view>
					
					<template>
						<u-cell title="开始时间" :border="true" :isLink="true"
							@click="$refs.startTimeRef.show()"
						>
							<view slot="value">
								<u-form-item label="" prop="form.startTime">
									{{renderItem(model.form,'startTime','')}}
								</u-form-item>
							</view>	
						</u-cell>
						<tq-date-time ref="startTimeRef"
							:disEndDate="renderItem(model.form,'endTime','')"
							@confirm="(data) => {
								model.form.startTime = data
								$refs.uForm.validateField('form.startTime')
                                computetimeArr()
							}"
						>
						</tq-date-time>
					</template>
					
					<template>
						<u-cell title="结束时间" :border="true" :isLink="true"
							@click="$refs.endTimeRef.show()"
						>
							<view slot="value">
								<u-form-item label="" prop="form.endTime">
									{{renderItem(model.form,'endTime','')}}
								</u-form-item>
							</view>	
						</u-cell>
						<tq-date-time ref="endTimeRef"
							:disStartDate="renderItem(model.form,'startTime','')"
							@confirm="(data) => {
								model.form.endTime = data
								$refs.uForm.validateField('form.endTime')
                                computetimeArr()
							}"
						>
						</tq-date-time>
					</template>
					
					<template>
						<u-cell title="播放速度" :border="true" :isLink="true"
							@click="$refs.selectRef.show()"
						>
							<view slot="value">
								<u-form-item prop="form.playSpeed">
									{{renderItem(model.form,'playSpeedName','')}}
								</u-form-item>
							</view>	
						</u-cell>
						
						<tq-select ref="selectRef"
							:columns = "speedList"
							@confirm="(data) => {
								model.form.playSpeed = data.value
								model.form.playSpeedName = data.label
								$refs.uForm.validateField('form.playSpeed')
							}"
						>
						</tq-select>
					</template>
				</u-cell-group>
				
				<u-row style="margin-top: 20rpx;">
					<u-col :span="12" style="padding: 20rpx 30rpx;">
						<u-checkbox-group v-model="filterList" placement="column">
							<u-checkbox name="position" label="过滤未定位"></u-checkbox>
							<u-checkbox name="speed" label="过滤速度为0" v-if="tabStyle == 'vehicle'"></u-checkbox>
							<u-checkbox name="parkRecord" label="停车记录" v-if="tabStyle == 'vehicle'"></u-checkbox>
							<u-checkbox name="warning" label="车辆报警" v-if="tabStyle == 'vehicle'"></u-checkbox>
						</u-checkbox-group>
					</u-col>
				</u-row>
				
				<u-row style="margin-top: 20rpx;">
					<u-col :span="12" style="padding: 0 30rpx;">
						<u-button type="primary" shape="" v-if="timeArr.length" :custom-style="{
								width: '100%',
							  }" @click="handleSubmit" :disabled="getMoreDataText==='全部加载完成'">{{getMoreDataText}}
						</u-button>
                        <u-button type="primary" v-else shape="" :custom-style="{
								width: '100%',
							  }" @click="handleSubmit">查询
						</u-button>
					</u-col>	
				</u-row>
				<u-row style="margin-top: 20rpx;">
					<u-col :span="12" style="padding: 0 30rpx;">
						<u-button shape="" :custom-style="{
								width: '100%',
							  }" @click="handleReset">重置
						</u-button>
					</u-col>
				</u-row>
				
			</u--form>
		</view>
		
	</u-popup>
    </view>
</template>

<script>
import {isArray,clone,isObject } from 'lodash'
import {getImages} from '@/plugins/images'
import { trackRecord, monthHistory,userTrackRecord,userMonthHistory,getAlarmVehicleHisList,vehStopQueryList } from "@/api/pastRoute";
import {copyProps,clearProps} from '@/utils/gdtq.js'

export default {
    data() {
        return {
			isShow: false,
			model: {
				  form: {
					vehicleId: "",
					plate: "",
					userId: "",
					userName: "",
					startTime: "",
					endTime: "",
					playSpeed: 500,
					playSpeedName: '正常',
				  }
			},
			filterList: ['position','speed'],
			rules: {
				'form.vehicleId': {
					type: 'string',
					required: true,
					message: '请选择车辆',
					trigger: ['blur', 'change']
				},
				'form.userId': {
					type: 'string',
					required: true,
					message: '请选择人员',
					trigger: ['blur', 'change']
				},
				'form.startTime': {
					type: 'string',
					required: true,
					message: '请选择开始时间',
					trigger: ['blur', 'change']
				},
				'form.endTime': {
					type: 'string',
					required: true,
					message: '请选择结束时间',
					trigger: ['blur', 'change']
				},
				'form.playSpeed': {
					type: 'number',
					required: true,
					message: '请选择播放速度',
					trigger: ['blur', 'change']
				},
				
			},
			
			speedList: [
				{label: '极速',value: 100},
				{label: '较快',value: 300},
				{label: '正常',value: 500},
				{label: '较慢',value: 700},
			],
			
			
			
			trackRecordList: [], //
			playState: 0, //0未开始 1开始播放中 2暂停播放中 3继续播放中
			
			tabStyle: 'vehicle',
			typeList: [
				{label: '车辆',value: 'vehicle'},
				{label: '人员',value: 'personnel'},
			],

            pageIdx:0,
            timeArr:[],
            trackRecordListMoreData:[]

        }
    },
    computed:{
        getMoreDataText(){
            if(this.pageIdx===0){
                return '查询前7天数据'
            }else if(this.pageIdx===this.timeArr.length) {
                return '全部加载完成'
            }else{
                return '加载更多'
            }
        }
    },
    mounted() {
		let { tabStyleType } = this.$store.state.pastRoute.params
		if(tabStyleType) {
			this.tabStyle = tabStyleType
			this.$store.dispatch('setTabStyle',tabStyleType)
			this.show()
			
			 uni.showLoading({
				title: '加载中...',
				mask: true, // 使用 mask 参数来禁用用户交互
			});
		}
	},
	
	onReady() {
		this.$refs.uForm.setRules(this.rules)
		
	},
	
    methods: {
        computetimeArr(){
            this.timeArr = []
            this.pageIdx = 0
            this.trackRecordListMoreData = []
            //超过7天后按七天分段
            // 解析日期字符串
            const startDate = this.dayjs(this.model.form.startTime + ':00');
            const endDate = this.dayjs(this.model.form.endTime + ':59');

            // 计算天数差
            const daysDiff = endDate.diff(startDate, 'day');

            // 超过7天后按七天分段

            if (daysDiff > 7) {
                const numSegments = Math.ceil(daysDiff / 7);
                for (let i = 0; i < numSegments; i++) {
                    const start = startDate.add(i * 7, 'day');
                    const end = i === numSegments - 1 ? endDate : start.add(6, 'day').endOf('day');
                    this.timeArr.push([start.format('YYYY-MM-DD HH:mm:ss'), end.format('YYYY-MM-DD HH:mm:ss')]);
                }

            }
            console.log('分段是', this.timeArr)
        },
		handleActive(item) {
			if(this.tabStyle == item.value) return
			this.$store.dispatch('setTabStyle',item.value)
			
			this.handleReset()
			this.tabStyle = item.value
			
		},
		show() {
			this.isShow= true;	
		},
		close() {
		    this.isShow = false
		},
		
		getParams(allTreeList) {
			let { tabStyleType, vehicleId, userId, time } = this.$store.state.pastRoute.params
			
			// console.log( this.$store.state.pastRoute.params,' this.$store.state.pastRoute.params')
			if (!tabStyleType) return
			this.$nextTick(e => {
				if (tabStyleType == 'vehicle') {
					this.model.form.vehicleId = vehicleId
					if(allTreeList.length>0) {
						let res = allTreeList.filter((e) => vehicleId == e.id)
						if(res.length>0) {
							this.model.form.plate = res[0].label
							this.$store.dispatch('setMapImg',res[0].img)
						}
					}
				} else if (tabStyleType == 'personnel') {
					this.model.form.userId = userId
					if(allTreeList.length>0) {
						let res = allTreeList.filter((e) => userId == e.id)
						if(res.length>0) {
							this.model.form.userName = res[0].label
							this.$store.dispatch('setMapImg',res[0].img)
						}
					}
					
				}
				this.model.form.startTime = time[0]
				this.model.form.endTime = time[1]
				
				this.$store.dispatch('setParams',{})
				
				uni.hideLoading();

			})
		},
		
		handleDataLoad(allTreeList) {
			this.getParams(allTreeList)
		},
		
		resetAll() {
			this.playState = 0;
            this.trackRecordList = []
			this.$store.dispatch('setTrackRecordArr',[])
		},
		// 提交
		async handleSubmit() {
			  this.$refs.uForm.validate().then(async res => {
				  if (this.tabStyle === 'vehicle') {
					  let ajaxData = {
						  ...this.model.form,
							position: this.filterList.includes('position')?1:0,
						    speed: this.filterList.includes('speed')?1:0,
							startTime:this.timeArr.length ? this.timeArr[this.pageIdx][0] : this.model.form.startTime + ':00',
							endTime:this.timeArr.length ? this.timeArr[this.pageIdx][1] : this.model.form.endTime + ':59',
					  }
					  let { data, code } = await trackRecord(ajaxData) 
					  
                      if (code == 0) {
                          this.resetAll()
                          let list = data.map(e => {
                              return {
                                  ...e,
                                  engineStatusName: e.engineStatus === '1' ? '开' : '关',
                                  positionName: Number(e.position) === 1 ? '已定位' : '未定位'
                              }
                          })
                          if (this.timeArr.length) {  // 分段
                            this.pageIdx++
                            this.trackRecordListMoreData = this.trackRecordListMoreData.concat(list)
                              this.trackRecordList = this.trackRecordListMoreData
                          } else {
                              if (list.length > 0) { //有数据
                                  this.trackRecordList = list
                              } else {
                                  this.$modal.msg("没有轨迹信息！")
                              }
                          }
                          //赋值轨迹数据
                          if (this.trackRecordList.length) {
                              this.trackRecordList[0].duration = this.model.form.playSpeed
                              this.trackRecordList[0].tabStyle = this.tabStyle
                              this.$store.dispatch('setTrackRecordArr', this.trackRecordList)
                              this.close()
                          }

                          console.log('轨迹数据',this.trackRecordList)
                      } else {
                          this.$modal.msg("获取失败！")
                      }
                      //查询停车记录
                      if(this.filterList.includes('parkRecord')){
                        let ajaxData = {
                            ...this.model.form,
                            startTime: this.model.form.startTime + ':00',
							endTime: this.model.form.endTime + ':59',
                        }
                        delete ajaxData.time
                        let { data: vedata, code: vecode } = await vehStopQueryList(ajaxData)
                        if (vecode === 0) {
                            // pastRoute.setVehStopArr(vedata)
                            this.$store.dispatch('setVehStopArr',vedata)
                        }
                      }

                      //查询车辆报警明细
                      if(this.filterList.includes('warning')){
                            let { data: avData, code: avCode } = await getAlarmVehicleHisList({
                                startTime: this.model.form.startTime + ':00',
                                endTime: this.model.form.endTime + ':59',
                                objId: this.model.form.vehicleId
                            })
                            if (avCode === 0) {
                                // pastRoute.setVeAlarm(avData)
                                this.$store.dispatch('setVeAlarm',avData)
                            }
                        }

					  //人员轨迹
					} else if (this.tabStyle === 'personnel') {
						
						let ajaxData = {
							...this.model.form,
							position: this.filterList.includes('position')?1:0,
							startTime:this.timeArr.length ? this.timeArr[this.pageIdx][0] : this.model.form.startTime + ':00',
							endTime:this.timeArr.length ? this.timeArr[this.pageIdx][1] : this.model.form.endTime + ':59',
						}
						let { data, code } = await userTrackRecord(ajaxData) 
						
                      if (code == 0) {
                          this.resetAll()
                          let list = data.map(e => {
                              return {
                                  ...e,
                                  engineStatusName: e.engineStatus === '1' ? '开' : '关',
                                  positionName: Number(e.position) === 1 ? '已定位' : '未定位'
                              }
                          })

                          if (this.timeArr.length) {  // 分段
                              this.pageIdx++
                              this.trackRecordListMoreData = this.trackRecordListMoreData.concat(list)
                              this.trackRecordList = this.trackRecordListMoreData
                          } else {
                              if (data.length > 0) { //有数据
                                this.trackRecordList = list
                                  
                              } else {
                                  this.$modal.msg("没有轨迹信息！")
                              }
                          }
                          //赋值轨迹数据
                          if (this.trackRecordList.length) {
                                      this.trackRecordList[0].duration = this.model.form.playSpeed
                                      this.trackRecordList[0].tabStyle = this.tabStyle
                                      this.$store.dispatch('setTrackRecordArr', this.trackRecordList)
                                      this.close()
                                  }
                                  console.log('轨迹数据',this.trackRecordList)
                      } else {
                          this.$modal.msg("获取失败！")
                      }
					}
                    
                     //同步更新查询信息
                     this.$store.dispatch('setPastRouteParams', {
                            ...this.model.form,
                            startTime: this.model.form.startTime + ':00',
							endTime: this.model.form.endTime + ':59',
                        })
                        
                }).catch(errors => {
				  console.log('校验失败',errors)
			  })
		},
		
		// 播放
		play() {
		    switch (this.playState) {
		        case 0:
		            this.$emit('startAnimation') //开始播放
		            this.playState = 1
		            break;
		        case 1:
		            this.$emit('pauseAnimation') //暂停
		            this.playState = 2
		            break;
		        case 2:
		            this.$emit('resumeAnimation') //继续
		            this.playState = 3
		            break;
		        case 3:
		            this.$emit('pauseAnimation') //暂停
		            this.playState = 2
		            break;
		    }
		},
		
		handleReset () {
			clearProps(this.model.form)
			this.model.form.playSpeed = 500
			this.model.form.playSpeedName = '正常'
			
			this.filterList = ['position','speed']
			
			this.resetAll()
            this.computetimeArr()
		}
		
    }

}
</script>

<style lang="scss" scoped>
.arrow-up{
    // height: 40px;
    // line-height: 40px;
    width: 100%;
    display: flex;
    justify-content: center;
    // background: rgba($color: #fff, $alpha: 0.6);
    // padding:0 20px;
    position: absolute;
    bottom:0;
    .icon{
        background: rgba($color: #fff, $alpha: 0.68);
        padding:0 14px;
    }
}
.popup-icon{
    width: 100%;
    display: flex;
    justify-content: center;
    position: absolute;
    // background: rgba($color: #fff, $alpha: 1);
    top:-25px;
    height: 26px;
    .icon{
        background: rgba($color: #fff, $alpha: 0.68);
        padding:0 6px;
        //旋转180度
        transform: rotate(180deg);
    }
}
	.munes {
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		.munes-item {
			flex: 1;
			height: 100%;
			background: #F2f2f2;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 30rpx;
			font-weight: bold;
		}
		.munes-item-active {
			background: #fff;
			color: #3c9cff;
		}
	}
	.container {
		background: #fff;
		padding: 0rpx 0 20rpx 0;
		font-size: 28rpx;
		min-height: 700rpx;
	}
	
	::v-deep {
		.container {
			.u-form-item__body {
				padding: 0;
			}
			.u-checkbox-group--column {
				.u-checkbox {
					&+.u-checkbox {
						margin-top: 20rpx;
					}
				}
			}
		}
	}
		
</style>
