<template>
	<view class="page">
		<u-navbar title="车辆管理" :border-bottom="false" :background="bgc" title-color='#000' title-size='36'
			height='45'></u-navbar>
		<view class="tap">
		</view>
		<view class="" style="background: #FFFFFF;width: 750rpx;padding-top: 20rpx;box-sizing: border-box;">
			<view class="top_box">
				<view class="sear_ipt">
					<input type="text"  v-model="searchKeyword" placeholder="请输入SN码或车牌号" class="input" @input="search" placeholder-style="color:#C7CDD3" >
					<!-- <view class="" @click="search">
						搜索
					</view> -->
				</view>
			</view>
		</view>
		<view class="stause_box">
			<view class="stause_li" @click="show = true">
				{{ tit }}
				<view class="iconfont icon-xiangxia1"></view>
			</view>
			<view class="stause_li" style="margin-left: 20rpx;" @click="showtype = true">
				{{ typeSortLabel == '' ? '请选择' : typeSortLabel}}
				<view class="iconfont icon-xiangxia1"></view> 
			</view> 
			<view class="stause_li" style="margin-left: 20rpx;" @click="showdsc = true">
				{{ sctit == '' ? '请选择' : sctit }}
				<view class="iconfont icon-xiangxia1"></view>
			</view>
		</view>
		<scroll-view @scrolltolower="handqixing" scroll-y refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing" refresher-default-style="black" style="height: 66vh;">
			 <view class="info_card" style="margin-top: 20rpx;" v-for="(item, index) in filteredList" :key="index"
			 	@click.stop="todetail(item)">
			 	<view class="info_tit" style="margin-left: 36rpx;">
					<view class="" style="display: flex;align-items: center;">
						<view class="tit_right" :style="{ color: getStatusColors(item) }"
			 			    style="margin-left: 0rpx;margin-right: 20rpx;">
			 			    <view class="yuan" :style="{ background: getStatusColors(item) }"></view>
			 			    {{ statuss(item) }}
			 		   </view>
					   <span v-if="item.vehicleNum"> 车牌号：{{ item.vehicleNum }}</span>
					   <span v-if="!item.vehicleNum"> 车牌号：--</span>
					</view>
			 		
			 		<view class="tit_left" v-if="stepindex == 1">
			 			<image src="https://lxnapi.ccttiot.com/bike/img/static/uTuWiPEViwzaPPHAgjdN" mode="aspectFit"
			 				v-if="!isSelected(item.id)" @click.stop="selectItem(item.id)"></image>
			 			<image src="https://lxnapi.ccttiot.com/bike/img/static/uGY25CNyW7Vz0LJcOYtS" mode="aspectFit"
			 				v-if="isSelected(item.id)" @click.stop="deselectItem(item.id)"></image>
			 		</view>
			 		<view class="" style="display: flex;align-items: center;">
			 			<view class="tit_right" style="margin-left: 10rpx;" :style="{ color: getStatusColor(item) }">
			 				<view class="yuan" :style="{ background: getStatusColor(item) }"></view>
			 				{{ status(item) }}
			 			</view>
			 		</view>
			 		
			 	</view>
			 	<view class="lines"></view>
			 	<view class="cont">
			 		<view class="info_li">
						<view class="half_infoli">
							SN：
							<span v-if="item.sn"> {{ item.sn }}</span>
							<span v-else> --</span>
						</view>
			 			<view class="half_infoli">
			 				MAC：
			 				<span v-if="item.mac"> {{ item.mac }}</span>
			 				<span v-if="!item.mac"> --</span>
			 			</view>
			 		</view>
			 		<view class="info_li">
			 			<view class="half_infoli">
			 				电量：
			 				<span> {{ item.remainingPower == null ? 0 : item.remainingPower}}%</span>
			 			</view>
			 			<view class="half_infoli">
			 				型号：
			 				<span v-if="item.modelName"> {{ item.modelName }}</span>
			 				<span v-else> --</span>
			 			</view>
			 		</view>
			 	</view>
			 </view>
			 <view class="" style="width: 100%;text-align: center;color: #ccc;margin-top: 30rpx;">
			 	当前没有更多车辆咯...
			 </view>
		</scroll-view>
		
		<view class="bot_box">
			<view class="step1" v-if="stepindex == 0" style="padding:  20rpx;">
				<view class="step1_left">
					设备总数：<span>{{ total }}</span>
				</view>
				<view class="right_box" @click="stepindex = 1">
					批量操作
				</view>
			</view>
			<view class="step2" v-if="stepindex == 1">
				<view class="top">
					<view class="top_left" @click="selectAll">
						<image
							:src="isAllSelected ? 'https://lxnapi.ccttiot.com/bike/img/static/uGY25CNyW7Vz0LJcOYtS' : 'https://lxnapi.ccttiot.com/bike/img/static/uTuWiPEViwzaPPHAgjdN'"
							mode="aspectFit"></image>
						{{ isAllSelected ? '取消全选' : '全选' }}
					</view>
					<view class="top_right">
						已选设备：{{ selectedItems.length }}
					</view>
				</view>
				<view class="bot_btn">
					<!-- 	<view class="btn">
						返仓
					</view> -->
					<view class="btn" @click="ban()">
						车辆禁用
					</view>
					<view class="btn" @click="pick()">
						车辆解禁
					</view>
					<view class="btn" @click="gohome()">
						车辆回仓
					</view>
					<view class="btn" @click="livehome()">
						车辆出仓
					</view>
					<view class="btn" @click="closestep()">
						退出操作
					</view>
				</view>
			</view>
		</view>
		<view class="bottom" style="width: 100%;">
		</view>
		<u-select v-model="show" :list="list" title='设备状态' @confirm="confirm"></u-select>
		<u-select v-model="showdsc" :list="lists" title='排序方式' @confirm="confirms"></u-select>
		<u-select v-model="showtype" :list="sortTypeList" title='排序选择' @confirm="confirmSortType"></u-select>
	</view>
</template>

<script>
export default {
	data() {
		return {
			curtitidx: 0,
			bgc: {
				backgroundColor: "#fff",
			},
			showdsc: false,
			sctit: '从高到低',
			scidx: 'desc',
			isRefreshing: false,
			show: false,
			showtype: false,
			typeSort: 'remainingPower',
			typeSortLabel: '电量排序',
			// 添加排序类型列表
			sortTypeList: [{
				value: 'sn',
				label: 'SN码排序'
			},
			{
				value: 'modelName',
				label: '车型排序'
			},
			{
				value: 'vehicleNum',
				label: '车牌号排序'
			},
			{
				value: 'remainingPower',
				label: '电量排序'
			}],
			lists: [{
				value: 'desc',
				label: '从高到低'
			},
			{
				value: 'asc',
				label: '从低到高'
			},
			],
			list: [{
				value: '',
				label: '全部'
			},
			{
				value: '0',
				label: '未上架'
			},
			{
				value: '1',
				label: '待租'
			},
			{
				value: '2',
				label: '预约中'
			},
			{
				value: '3',
				label: '骑行中'
			},
			{
				value: '4',
				label: '临时锁车'
			},
			{
				value: '8',
				label: '下线'
			},{
				value: '9',
				label: '强制锁车'
			}],
			tit: '全部',
			typeidx: '',
			deviceList: [],
			stepindex: 0,
			selectedItems: [],
			searchKeyword: '',
			filteredList: [],
			areaId: 0,
			pageNum:1,
			total:'',
			sousuoflag:true,
			searchKeyword: '',
			searchTimer: null,
		}
	},
	onLoad() {
		
	},
	onShow() {
		if(uni.getStorage('typeSort')){
			uni.getStorage({
			    key: 'typeSort',
			   success: (res) => {
			        this.typeSort = res.data;
			    }
			})
			uni.getStorage({
			    key: 'typeSortLabel',
			    success: (res) => {
			        this.typeSortLabel = res.data
			    }
			})
		}
		if(uni.getStorage('sctit')){
			uni.getStorage({
			    key: 'sctit',
			    success:(res) => {
			        this.sctit = res.data
			    }
			})
			uni.getStorage({
			    key: 'scidx',
			    success:(res) => {
			        this.scidx = res.data
			    }
			})
		}
		setTimeout(()=>{
			if (uni.getStorageSync('adminAreaid')) {
				this.areaId = uni.getStorageSync('adminAreaid')
				this.pageNum = 1
				this.getDevice()																								
			}
		},10)
	},
	computed: {
		isAllSelected() {
			if (this.selectedItems.length == this.deviceList.length) {
				return true
			} else {
				return false
			}
		},
	},
	methods: {
		// 下拉刷新
		onRefresh() {
			this.isRefreshing = true
			this.pageNum = 1
			this.getDevice()
			setTimeout(() => {
				this.isRefreshing = false
			}, 1000)
		},
		search() {
		    // 清除之前的定时器
		    clearTimeout(this.searchTimer)
		    // 设置新的定时器（500ms后执行）
		    this.searchTimer = setTimeout(() => {
		      this.doSearch()
		    }, 500)
		  },
		  // 实际执行搜索的方法
		    doSearch() {
		      this.pageNum = 1
		      let data = {
		        isAsc: this.scidx,
		        status: this.typeidx,
		        areaId: this.areaId,	
		        orderByColumn: this.typeSort,
		        refresh: true,
		        Keyword: this.searchKeyword
		      } 
		      
		      this.selectedItems = []
		      this.$u.get(`//bst/device/all`, data).then((res) => {
		        if (res.code == 200) {
		          this.total = res.data.length 
		          this.deviceList = res.data
		          this.filteredList = res.data
		        } else {
		          uni.showToast({
		            title: res.msg,
		            icon: 'none',
		            duration: 2000
		          })
		        }
		      })
		    },

		todetail(item) {
			if (this.stepindex == 0) {
				console.log(item.id,item);
				uni.navigateTo({
					url: '/page_shanghu/guanli/device_detail?id=' + item.id
				})
			}
		},
		// 添加新的排序类型确认方法
		confirmSortType(e) {
			this.typeSort = e[0].value
			this.typeSortLabel = e[0].label
			uni.setStorage({
			    key: 'typeSort',
			    data: e[0].value,
			})
			uni.setStorage({
			    key: 'typeSortLabel',
			    data: e[0].label,
			})
			// this.pageNum = 1
			this.getDevice()
		},
		// 车辆禁用
		ban() {
			let data = this.selectedItems
			this.$u.put(`/bst/device/disable`,data).then((res) => {
				if (res.code == 200) {
					this.closestep()
					this.pageNum = 1
					this.getDevice()
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		pick() {
			let data = this.selectedItems
			this.$u.put(`/bst/device/enable`,data).then((res) => {
				if (res.code == 200) {
					this.closestep()
					this.pageNum = 1
					this.getDevice()
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		gohome() {
			let data = this.selectedItems
			this.$u.put(`/bst/device/in`,data).then((res) => {
				if (res.code == 200) {
					this.closestep()
					this.pageNum = 1
					this.getDevice()
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		livehome() {
			let data = this.selectedItems
			this.$u.put(`/bst/device/out`,data).then((res) => {
				if (res.code == 200) {
					this.closestep()
					this.pageNum = 1
					this.getDevice()
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		confirms(e) {
			this.scidx = e[0].value
			this.sctit = e[0].label
			uni.setStorage({
			    key: 'scidx',
			    data: e[0].value,
			})
			uni.setStorage({
			    key: 'sctit',
			    data: e[0].label,
			})
			this.pageNum = 1
			this.getDevice()
		},
		getStatusColor(item) {
			if (item.status == 0 || item.status == 8) {
				return '#979797' // 下线和未上架状态为灰色
			} else if (item.status == 1) {
				return '#4c97e7' // 待租状态为绿色
			} else if (item.status == 2) {
				return '#28c445' // 预约中状态为橙色
			} else if (item.status == 3) {
				return '#ffc757' // 骑行中状态为蓝色
			} else if (item.status == 4) {
				return '#ff7429' // 临时锁车中状态为黄色
			} else if (item.status == 6) {
				return '#986cf0' // 调度中状态为紫色
			} else if (item.status == 7) {
				return '#343a40' // 未绑定状态为黑色
			}else if (item.status == 9) {
				return '#ff7429' // 未绑定状态为黑色
			}
		},
		getStatusColors(item) {
			if (item.onlineStatus == 0) {
				return '#dc3545' // 离线状态为红色
			} else {
				return '#28a745' // 在线状态为绿色
			}
		},
		closestep() {
			this.selectedItems = []
			this.stepindex = 0
		},
		isSelected(sn) {
			return this.selectedItems.includes(sn)
		},
		selectItem(sn) {
			this.selectedItems.push(sn)
			// 更新 isAllSelected
			console.log(this.selectedItems, '选择')
		},
		deselectItem(sn) {
			this.selectedItems = this.selectedItems.filter(item => item !== sn)
			// 更新 isAllSelected
			console.log(this.selectedItems, '删除')
		},
		selectAll() {
			if (this.selectedItems.length === this.deviceList.length) {
				this.selectedItems = []
			} else {
				this.selectedItems = this.deviceList.map(item => item.id)
			}
		},
		status(item) {
			if (item.status == 0) {
				return '仓库中'
			} else if (item.status == 1) {
				return '待租'
			} else if (item.status == 2) {
				return '预约中'
			} else if (item.status == 3) {
				return '骑行中'
			} else if (item.status == 4) {
				return '临时锁车中'
			} else if (item.status == 6) {
				return '调度中'
			} else if (item.status == 7) {
				return '未绑定'
			} else if (item.status == 8) {
				return '禁用中'
			} else if (item.status == 9) {
				return '强制锁车'
			}
		},
		statuss(item) {
			if (item.onlineStatus == 0) {
				return '离线'
			} else {
				return '在线'
			}
		},
		//上拉加载更多
		handqixing(){
			if(this.total > this.filteredList.length){
				this.getDevice()
			}
			console.log(11);
		},
		getDevice() {
			console.log(this.typeSort)
			let data = {
				// isAsc: this.scidx,
				status: this.typeidx,
				areaId: this.areaId,	
				// orderByColumn: this.typeSort,
				// refresh:true,
				Keyword:this.searchKeyword
			}
			this.selectedItems = []
			this.$u.get(`/bst/device/all`, data).then((res) => {
				if (res.code == 200) {
					this.total = res.data.length
					this.deviceList = res.data
					this.filteredList = res.data
					if (!this.filteredList || this.filteredList.length === 0) return;
					    
					    // 如果没有设置排序字段或方向，使用默认值
					    const sortField = this.typeSort || 'remainingPower';
					    const isDesc = this.scidx === 'desc';
					    
					    this.filteredList.sort((a, b) => {
					      // 获取比较值（处理可能不存在的字段）
					      let valueA = a[sortField] || '';
					      let valueB = b[sortField] || '';
					      
					      // 特殊处理数字类型（如电量）
					      if (sortField === 'remainingPower') {
					        valueA = parseFloat(valueA) || 0;
					        valueB = parseFloat(valueB) || 0;
					      }
					      
					      // 执行比较
					      if (isDesc) {
					        // 降序排列
					        if (valueA > valueB) return -1;
					        if (valueA < valueB) return 1;
					      } else {
					        // 升序排列
					        if (valueA < valueB) return -1;
					        if (valueA > valueB) return 1;
					      }
					      return 0;
					    });
					    
					    // 更新视图
					    this.$forceUpdate();
					// if(this.pageNum == 1){
					// 	this.deviceList = res.rows
					// 	this.filteredList = res.rows
					// }else{
					// 	this.deviceList = this.deviceList.concat(res.rows) 
					// 	this.filteredList = this.filteredList.concat(res.rows)
					// }
					// this.pageNum++
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		confirm(e) {
			this.typeidx = e[0].value
			this.tit = e[0].label
			this.pageNum = 1
			this.getDevice()
		},
		changeidx(idx) {
			this.curtitidx = idx
		},
	}
}
</script>
<style lang="scss">
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
.sear_ipt {
        display: flex;
        align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		box-sizing: border-box;
		view{
			width: 120rpx;
			height: 60rpx;
			text-align: center;
			line-height: 60rpx;
			border-radius: 50rpx;
			background-color: #4c97e7;
			color: #fff;
		}
        .input {
          width:680rpx !important;
          font-size: 28rpx;
          color: #1a1a1a;
		  border: 1px solid #ccc;
		  margin: auto;
		  height: 60rpx;
		  line-height: 60rpx;
          padding-left: 16rpx;
		  border-radius: 50rpx;
        }
      }
.page {
  width: 100%;
  background-color: #f5f7fa;
  
  /* 搜索区域 */
  .search-container {
    padding: 24rpx 32rpx;
    background: #fff;
    
    .top_box {
      width: 100%;
      height: 88rpx;
      background: #f8f9fa;
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      padding: 0 32rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
  //     .sear_ipt {
  //       display: flex;
  //       align-items: center;
  //       justify-content: space-between;
		// width: 100%;
		// view{
		// 	width: 120rpx;
		// 	height: 60rpx;
		// 	text-align: center;
		// 	line-height: 60rpx;
		// 	border-radius: 50rpx;
		// 	background-color: #4c97e7;
		// 	color: #fff;
		// }
  //       input {
  //         height: 580rpx;
  //         font-size: 28rpx;
  //         color: #1a1a1a;
		//   margin: auto;
		//   height: 60rpx;
		//   line-height: 60rpx;
  //         padding-left: 16rpx;
  //       }
  //     }
    }
  }
  
  /* 筛选区域 */
  .stause_box {
    display: flex;
    padding: 24rpx 32rpx;
    background: #fff;
    border-bottom: 1rpx solid #f0f2f5;
    
    .stause_li {
      display: flex;
      align-items: center;
      padding: 12rpx 24rpx;
      background: #f8f9fa;
      border-radius: 40rpx;
      font-size: 26rpx;
      color: #4a4a4a;
      transition: all 0.3s;
      
      &:active {
        background: #e9ecef;
      }
      
      .icon-xiangxia1 {
        margin-left: 8rpx;
        font-size: 24rpx;
        color: #9aa4b1;
      }
    }
  }
  
  /* 车辆卡片 */
  .info_card {
    margin: 24rpx 32rpx;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    overflow: hidden;
    transition: transform 0.3s, box-shadow 0.3s;
    &:active {
      transform: translateY(-2rpx);
      box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
    }
    
    .info_tit {
      display: flex;
      align-items: center;
      padding: 28rpx 0;
	  padding-right: 30rpx;
	  box-sizing: border-box;
      position: relative;
      justify-content: space-between;
      .tit_left {
        flex: 1;
        font-size: 30rpx;
        color: #1a1a1a;
        font-weight: 500;
        display: flex;
		align-items: center;
        image {
          width: 40rpx;
          height: 40rpx;
          margin-right: 16rpx;
        }
      }
      
      .tit_right {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        padding: 6rpx 12rpx 6rpx 8rpx;
        border-radius: 20rpx;
        background: rgba(0, 0, 0, 0.02);
        
        .yuan {
          width: 12rpx;
          height: 12rpx;
          border-radius: 50%;
          margin-right: 8rpx;
        }
      }
    }
    
    .lines {
      height: 1rpx;
      background: #f0f2f5;
      margin: 0 32rpx;
    }
    
    .cont {
      padding: 24rpx 32rpx;
      
      .info_li {
        display: flex;
        margin-bottom: 20rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .half_infoli {
          flex: 1;
          font-size: 26rpx;
          color: #9aa4b1;
          
          span {
            color: #4a4a4a;
            margin-left: 8rpx;
          }
        }
      }
    }
  }
  
  /* 底部操作栏 */
  .bot_box {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
    padding: 24rpx 32rpx;
    z-index: 100;
    
    .step1 {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .step1_left {
        font-size: 28rpx;
        color: #6b7785;
        
        span {
          color: #4c97e7;
          font-weight: 500;
        }
      }
      
      .right_box {
        padding: 16rpx 32rpx;
        background: #4c97e7;
        color: #fff;
        border-radius: 40rpx;
        font-size: 28rpx;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(76, 151, 231, 0.3);
      }
    }
    
    .step2 {
      .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 24rpx;
        
        .top_left {
          display: flex;
          align-items: center;
          font-size: 28rpx;
          color: #4a4a4a;
          
          image {
            width: 36rpx;
            height: 36rpx;
            margin-right: 12rpx;
          }
        }
        
        .top_right {
          font-size: 28rpx;
          color: #6b7785;
        }
      }
      
      .bot_btn {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        
        .btn {
          width: 30%;
          margin-bottom: 16rpx;
          padding: 18rpx 0;
          text-align: center;
          background: #f8f9fa;
          border-radius: 8rpx;
          font-size: 26rpx;
          color: #4a4a4a;
          transition: all 0.3s;
          
          &:active {
            background: #e9ecef;
          }
          
          &:nth-child(3n) {
            margin-right: 0;
          }
          
          &:last-child {
            background: #f8f9fa;
            color: #ff4d4f;
          }
        }
      }
    }
  }
  
  .bottom {
    height: 200rpx;
  }
}

/* 状态颜色 */
.status-online {
  color: #28a745 !important;
}

.status-offline {
  color: #dc3545 !important;
}

.status-warehouse {
  color: #979797 !important;
}

.status-available {
  color: #4c97e7 !important;
}

.status-reserved {
  color: #28c445 !important;
}

.status-riding {
  color: #ffc757 !important;
}

.status-locked {
  color: #ff7429 !important;
}

.status-dispatching {
  color: #986cf0 !important;
}

.status-unbound {
  color: #343a40 !important;
}

.status-disabled {
  color: #343a40 !important;
}
</style>