<template>
	<view class="all_path">
		<view class="headers">
			<text>专业力必修图</text>
			<view class="go_to" @click="goSearch">
				<text class="text">筛选</text>
				<image class="img" src="../../static/images/search2.png" mode=""></image>
			</view>
		</view>
		<view class="path">
			<view class="item">
				<image style="width: 40rpx;height: 36rpx;" class="img" src="../../static/images/learnpath/thispath.png" mode=""></image>
				<text class="text">当前任务</text>
			</view>
			<view class="item" style="margin-left: 80rpx;">
				<image style="width: 40rpx;height: 36rpx;" class="img" src="../../static/images/learnpath/otherpath.png" mode=""></image>
				<text class="text">其他任务</text>
			</view>
			<!-- <view class="item">
				<image class="img" src="../../static/images/learnpath/notpath.png" mode=""></image>
				<text class="text">其他任务(无权限)</text>
			</view> -->
		</view>
		<view class="table">
			<view class="table-container">
			    <table style="width: 100%;border-collapse: collapse;border: 2rpx solid #F0F6FC;">
			      <thead>
			        <tr style="background: #F0F6FC;display: flex;align-items: center;">
			          <th style="display: block;text-align: center;" class="first" align="center">
						  <view style="width: 212rpx;border-collapse: collapse;" class="text"></view>
					  </th>
			          <th style="width: 156rpx;
								  min-height: 100rpx;
								  text-align: center;
								  border: 2rpx solid #F0F6FC;
								  background: #F0F6FC;
								  font-weight: bold;
								  color: #387DF7;
								  font-weight: bold;
								  border-collapse: collapse;
								  display: flex;
								  justify-content: center;
								  align-items: center;" class="item1" v-for="item in titleList" align="center">{{ item.title }}</th>
			        </tr>
			      </thead>
			      <tbody>
			        <tr style="display: flex;align-items: center;border: 1rpx solid #F0F6FC;" v-for="item,index in preparedData" :key="index">
			          <td style="display: block;text-align: center;" class="first" align="center">
						  <view class="text"  style="width: 212rpx;border-collapse: collapse;">
							{{ item.isOtherPosition == 1 ? item.positionName + '(' + item.organizationName + ')' : item.positionName }}
						  </view>
					  </td>
			          <td style="width: 156rpx;
								  min-height: 120rpx;
								  text-align: center;
								  border: 2rpx solid #F0F6FC;
								  border-bottom: none;
								  background-color: #ffffff;
								  color: #333333;
								  font-weight: 400;
								  font-size: 28rpx;
								  border-collapse: collapse;
								  display: flex;
								  justify-content: center;
								  align-items: center;" :style="{width: 158 * t.number + 'rpx'}" class="item" align="center" v-for="t,i in item.bandCodes">
			            <image 
			               v-if="(t && t.isMajorPosition) "
			              src="@/static/images/learnpath/thispath.png" 
			              mode="aspectFit"
						  style="width: 40rpx;height: 36rpx;"
			            />
			            <image 
			              v-else-if="(t && t.permission)"
			              src="@/static/images/learnpath/otherpath.png" 
			              mode="aspectFit"
						  @click="goOtherPath(t)"
						  style="width: 40rpx;height: 36rpx;"
			            />
			           <!-- <image 
			              v-else-if="!(t && t.permission)"
			              src="@/static/images/learnpath/notpath.png" 
			              mode="aspectFit"
			            /> -->
						<text v-else></text>
			          </td>
			        </tr>
			      </tbody>
			    </table>
			  </view>
		</view>
		<u-popup :show="showSearch" :duration="0" mode="top" >
			<view class="searchs">
				<view class="item">
					<view class="title updown">
						岗位
						<view v-if="!isTrue" @click="listslice" class="up">
							收起
							<image class="img" src="../../static/images/learnpath/updown.png" mode=""></image>
						</view>
					</view>
					<view class="check">
						<view style="display: flex;flex-wrap: wrap;">
							<view :style="{marginRight:index/2!=0||index==0?'12rpx':''}" :class="indexs.includes(index)?'items':'item'" @click="searchItem(item,index)" v-for="(item,index) in posiLists" :key="index" class="item">
								{{item.positionName}}
							</view>
							<view v-if="startList.length > 9 && isTrue" class="item" @click="allList">
								<text class="text">查看更多</text>
								<image class="img" src="../../static/images/learnpath/uotdown.png" mode=""></image>
							</view>
							
						</view>
					</view>
				</view>
				<view class="item" style='margin-bottom: 180rpx;'>
					<view class="title">
						职级
					</view>
					<view class="downlist">
						<view class="title">
							<view @click="downList" class="btn">
								<text>{{bandFirst || '职级'}}</text>
								<img class="img" src="../../static/images/learnpath/uotdown.png" alt="">
							</view>
							<text class="line"></text>
							<view @click="downList" class="btn">
								<text>{{bandEnd || '职级'}}</text>
								<img class="img" src="../../static/images/learnpath/uotdown.png" alt="">
							</view>
						</view>
						<view v-if="bandShow" class="body">
							<view @click="isBand(item,index)" :class=" {'item2': bandIndexs.includes(index),'disabled-item': isDisabled(index)}" v-for="(item,index) in bandLists" :key="index" class="item">
								{{item.bandCode}}
							</view>
						</view>
					</view>
				</view>
				<view class="footers">
					<view class="btn left" @click="reach">
						重置
					</view>
					<view class="btn right" @click="goAllPath">
						确定
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import { getFullJobPath,getAllPosition,getAllBandInfo } from "@/api/modules/growth.js"
	export default {
		data() {
			return {
				bandCodeList: '',
				positionIdList: '',
				posiLists: [],
				startList: [],
				isTrue: true,
				indexs: [],
				posiData: [],
				bandLists: [],
				bandShow: false,
				bandIndexs: [],
				bandItem: [],
				bandFirst: '',
				bandEnd: '',
				showSearch: false,
				 gridData: [{
					 name: '市场企划岗',
					 marketStatus: 0,
					 saleStatus: 1,
					 productStatus: 2,
					 FAEStatusL: 0,
					 salesManagement: 1
				   }, {
					 name: '销售岗',
					 marketStatus: 1,
					 saleStatus: 2,
					 productStatus: 1,
					 FAEStatusL: 0,
					 salesManagement: 1
				   }, {
					 name: '产品企划岗',
					 marketStatus: 2,
					 saleStatus: 0,
					 productStatus: 0,
					 FAEStatusL: 0,
					 salesManagement: 1
				   }, {
					 name: 'FAE岗',
					 marketStatus: 0,
					 saleStatus: 1,
					 productStatus: 2,
					 FAEStatusL: 0,
					 salesManagement: 1
				   }, {
					 name: '销售管理岗位',
					 marketStatus: 1,
					 saleStatus: 2,
					 productStatus: 0,
					 FAEStatusL: 0,
					 salesManagement: 1
				}],
				pathData: [],
				titleList: [],
				preparedData: [],
			}
		},
		 onShow: function(options) {
			 //  const bandCodeList = uni.getStorageSync('bandCodeList');
			 //  const positionIdList = uni.getStorageSync('positionIdList');
				// getFullJobPath({
				// 	positionIdList: positionIdList || '',
				// 	bandCodeList: bandCodeList || ''
				// }).then(res=>{
				//   if(res.code == 200){
				// 	this.pathData = res.data
				// 	this.titleList = this.pathData.allBandCodeList
				// 	this.preparedData = this.integrateTableData(this.pathData);
				// 	this.titleList = this.titleList.map(item=>({
				// 	  title: item,
				// 	}))
				// 	// this.titleList.unshift({
				// 	//   title: ''
				// 	// })
				// 	console.log(this.titleList,'titleList')
				//   }
				// })
				this.getPosiList()
				this.getFullJobPaths()
		  },
		onLoad() {
		},
		methods: {
			getFullJobPaths(){
				getFullJobPath({
					positionIdList: this.positionIdList || '',
					bandCodeList: this.bandCodeList || ''
				}).then(res=>{
				  if(res.code == 200){
					this.pathData = res.data
					this.titleList = this.pathData.allBandCodeList
					this.preparedData = this.integrateTableData(this.pathData);
					this.titleList = this.titleList.map(item=>({
					  title: item,
					}))
					// this.titleList.unshift({
					//   title: ''
					// })
					console.log(this.titleList,'titleList')
				  }
				})
			},
			goOtherPath(item){
				console.log(item,'item')
				uni.navigateTo({
					url: '/pages/learnPath/learnPath?growId='+item.growId+'&name='+item.growName + '&isAllPath=' + false
				});
			},
			integrateTableData(data) {
			    const { growFullPositionPathBoItemList, allBandCodeList } = data;
			    const bandCodeIndexMap = new Map(allBandCodeList.map((code, index) => [code, index]));
			    const integratedDataMap = new Map();
			    growFullPositionPathBoItemList.flat().forEach(item => {
			        const key = `${item.positionName}-${item.organizationName}-${item.isOtherPosition}`;
			
			        if (!integratedDataMap.has(key)) {
			          integratedDataMap.set(key, {
			            positionName: item.positionName,
			            organizationName: item.organizationName,
			            isOtherPosition: item.isOtherPosition,
			            bandCodes: new Array(allBandCodeList.length).fill(null),
			          });
			        }
			        item.bandCodes.split(',').forEach(code => {
			          const codeTrimmed = code.trim();
			          const index = bandCodeIndexMap.get(codeTrimmed);
			          if (index !== undefined) {
			            integratedDataMap.get(key).bandCodes[index] = { growId: item.growId, permission: item.permission ,isMajorPosition:item.isMajorPosition,growName:item.growName };
			          }
			        });
			      });
			      const integratedDataArray = Array.from(integratedDataMap.values());
				  const mergeById = (array) => {
					  const result = [];
					  let currentGroup = null;
			  
					  array.forEach(item => {
						if (item === null) {
						  if (currentGroup && currentGroup.growId !== null) {
							result.push(currentGroup);
							currentGroup = null;
						  }
						  if (!currentGroup) {
							currentGroup = { growId: null, number: 1, ...item };
						  } else {
							currentGroup.number++;
						  }
						} else {
						  if (!currentGroup || currentGroup.growId !== item.growId) {
							if (currentGroup) {
							  result.push(currentGroup);
							}
							currentGroup = { growId: item.growId, number: 1, ...item };
						  } else {
							currentGroup.number++;
						  }
						}
					  });
					  if (currentGroup) {
						result.push(currentGroup);
					  }
			  
					  return result;
					};
					integratedDataArray.forEach(item => {
					  item.bandCodes = mergeById(item.bandCodes);
					});
			      console.log(integratedDataArray,'integratedDataArray')
			      return integratedDataArray;
			},
			goSearch(){
				// let positionId = this.preparedData.map(item => item.positionName).join(',')
				// uni.navigateTo({
				// 	url: `/pages/learnPath/pathSearch`
				// })
				this.showSearch = true
			},
			reach(){
				this.bandIndexs = []
				this.bandItem = []
				this.indexs = []
				this.posiData = []
				this.bandFirst = ''
				this.bandEnd = ''
				this.bandCodeList = ''
				this.positionIdList = ''
			},
			goAllPath(){
				this.bandCodeList = this.bandItem.map(item => item.bandCode).join(',')
				this.positionIdList = this.posiData.map(item => item.positionId).join(',')
				// uni.setStorageSync('bandCodeList', bandCodeList);
				// uni.setStorageSync('positionIdList', positionIdList);
				// uni.navigateBack({
				//   delta: 1
				// });
				this.showSearch = false
				this.getFullJobPaths()
			},
			getPosiList(){
				getAllPosition().then(res=>{
					this.startList = res.data
					if(res.code == 200 ){
						const majorItem = res.data.find(item => item.isMajor === 1);
						if (majorItem) {
						  const index = res.data.indexOf(majorItem);
						  res.data.splice(index, 1);
						  res.data.unshift(majorItem);
						}
						this.posiLists = res.data
						// const positionName = this.preparedData.map(item => item.positionName).join(',')
						// const positionNames = positionName.split(',');
						// const matchedItemsWithIndexes = positionNames.flatMap((item, index) => {
						//   // 先找到匹配的项
						//   const matches = this.posiLists
						//     .map((listItem, listItemIndex) => listItem.positionName === item ? { listItem, listItemIndex } : null)
						//     .filter(match => match !== null);
						//   return matches.map(match => ({ 
						//     matchedItem: match.listItem, 
						//     indexInPosiLists: match.listItemIndex 
						//   }));
						// });
						// this.posiData = matchedItemsWithIndexes.map(item=> item.matchedItem)
						// this.indexs = matchedItemsWithIndexes.map(item=> item.indexInPosiLists)
						if(this.posiLists.length > 9){
							this.posiLists = this.posiLists.slice(0, 9)
						}
					}
				})
				getAllBandInfo().then(res=>{
					if(res.code == 200){
						this.bandLists = res.data
					}
				})
			},
			allList(){
				this.posiLists = this.startList
				this.isTrue = false
			},
			listslice(){
				this.posiLists = this.startList.slice(0, 9)
				this.isTrue = true
			},
			searchItem(item,index){
				const indexToRemove = this.indexs.indexOf(index);
				if (indexToRemove !== -1) {
				    this.indexs.splice(indexToRemove, 1);
				} else {
				    this.indexs.push(index);
				}
				console.log(this.indexs,'this.indexs')
				this.posiData = this.indexs.map(index => this.startList[index]);
			},
			downList(){
				this.bandShow = !this.bandShow
			},
			isDisabled(index) {
			    if (this.bandIndexs.length == 1) {
			      const firstClickIndex = this.bandIndexs[0];
			      const allowedRangeEnd = firstClickIndex + 2;
			      return index < firstClickIndex - 2 || index > allowedRangeEnd;
			    }
				if (this.bandIndexs.length == 2) {
				  const firstClickIndex = this.bandIndexs[0];
				  const allowedRangeEnd = firstClickIndex + 2;
				  return index < firstClickIndex - 1 || index > allowedRangeEnd;
				}
				if (this.bandIndexs.length == 3) {
					const firstClickIndex = Math.min(...this.bandIndexs);
					const allowedRangeEnd = Math.max(...this.bandIndexs);
				  return index < firstClickIndex || index > allowedRangeEnd;
				}
			    return false;
			},
			isBand(item,index){
				console.log(this.bandIndexs.length)
				if (this.bandIndexs.length == 1) {
					const firstClickIndex = this.bandIndexs[0];
					const allowedRangeEnd = firstClickIndex + 2;
					if (index < firstClickIndex - 2 || index > allowedRangeEnd) {
						return;
					}
				}
				if (this.bandIndexs.length == 2) {
					const firstClickIndex = this.bandIndexs[0];
					const allowedRangeEnd = firstClickIndex + 2;
					if (index < firstClickIndex - 1 || index > allowedRangeEnd) {
						return;
					}
				}
				if (this.bandIndexs.length == 3) {
					const firstClickIndex = Math.min(...this.bandIndexs);
					const allowedRangeEnd = Math.max(...this.bandIndexs);
				  if (index < firstClickIndex  || index > allowedRangeEnd) {
				  	return;
				  }
				}
				this.bandIndexs.sort((a, b) => a - b);
				 if (this.bandIndexs.length === 3 && this.bandIndexs.includes(index) && this.bandIndexs.indexOf(index) == 1) {
					// 删除最后一个元素
					this.bandIndexs.sort((a, b) => a - b);
					this.bandIndexs.pop();
					this.bandItem = this.bandIndexs.map(index => this.bandLists[index])
					this.bandItem = this.bandItem.sort((a, b) => parseInt(a.bandId, 10) - parseInt(b.bandId, 10));
					this.bandFirst = this.bandItem[0].bandCode
					if(this.bandItem && this.bandItem.length > 1){
						this.bandEnd = this.bandItem[this.bandItem.length - 1].bandCode
					}
					return;
				}
				let currentIndex = index;
				let firstClickIndex = this.bandIndexs[0];
				
				if (this.bandIndexs.length === 0) {
					this.bandIndexs.push(currentIndex);
					this.bandItem = this.bandIndexs.map(index => this.bandLists[index])
					this.bandItem = this.bandItem.sort((a, b) => parseInt(a.bandId, 10) - parseInt(b.bandId, 10));
					this.bandFirst = this.bandItem[0].bandCode
					return;
				}
				const indexToRemove = this.bandIndexs.findIndex(index => index === currentIndex);
				if (indexToRemove !== -1) {
				    this.bandIndexs.splice(indexToRemove, 1);
				} else {
				    // 如果索引不存在于数组中，则需要检查是否需要填充连续索引
				    const start = Math.min(firstClickIndex, currentIndex);
				    const end = Math.max(firstClickIndex, currentIndex);
				    console.log(start,end,'end')
				    for (let i = start; i <= end; i++) {
				        if (!this.bandIndexs.includes(i)) {
				            this.bandIndexs.push(i);
				        }
				    }
				}
				if(this.bandIndexs.length == 0){
					this.bandFirst = ''
					this.bandItem = []
					return
				}
				if(this.bandIndexs.length == 1){
					this.bandEnd = ''
				}
				this.bandItem = this.bandIndexs.map(index => this.bandLists[index])
				this.bandItem = this.bandItem.sort((a, b) => parseInt(a.bandId, 10) - parseInt(b.bandId, 10));
				this.bandFirst = this.bandItem[0].bandCode
				if(this.bandItem && this.bandItem.length > 1){
					this.bandEnd = this.bandItem[this.bandItem.length - 1].bandCode
				}
			},
		}
	}
</script>

<style>
.all_path{
	padding: 0 30rpx;
	padding-top: 38rpx;
	background: #fff;
	height: 100vh;
	.table {
	  .table-container {
	    /* width: 100%; */
	    overflow-x: auto;
	  }
	  /* table {
	    width: 100%;
	    border-collapse: collapse;
		border: 2rpx solid #F0F6FC;
	  } */
	  
	 /* th {
	    padding: 12px 20px;
	    text-align: center;
	    border: 2rpx solid #F0F6FC;
	    background: #F0F6FC;
	  } */
	 /* td{
		  padding: 12px 16px;
		  text-align: center;
		  border: 2rpx solid #F0F6FC;
		  color: #333333;
		  font-weight: 400;
		  font-size: 28rpx;
	  } */
	  
	  /* th {
	    font-weight: bold;
	    color: #387DF7;
	  } */
	  /* .first{
		  display: block;
	  	  text-align: center;
		  .text{
			width: 212rpx;
			border-collapse: collapse;
		  }
	  } */
	 /* .item1{
		  width: 156rpx;
		  min-height: 100rpx;
		  text-align: center;
		  border: 2rpx solid #F0F6FC;
		  background: #F0F6FC;
		  font-weight: bold;
		  color: #387DF7;
		  font-weight: bold;
		  border-collapse: collapse;
		  display: flex;
		  justify-content: center;
		  align-items: center;
	  } */
	 /* .item{
		  width: 156rpx;
		  min-height: 120rpx;
		  text-align: center;
		  border: 2rpx solid #F0F6FC;
		  border-bottom: none;
		  background-color: #ffffff;
		  color: #333333;
		  font-weight: 400;
		  font-size: 28rpx;
		  border-collapse: collapse;
		  display: flex;
		  justify-content: center;
		  align-items: center;
	  } */
	  /* tbody tr:nth-child(odd) {
	    background-color: #ffffff;
	  } */
	  
	  /* tbody tr:hover {
	    background-color: rgba(0, 0, 0, .05);
	  } */
	  
	  /* image {
	    width: 40rpx;
	    height: 36rpx;
	    vertical-align: middle;
	  } */
	}
	
	.headers{
		/* margin-top: 38rpx; */
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 40rpx;
		font-weight: 500;
		font-size: 36rpx;
		color: #333333;
		.go_to{
			display: flex;
			align-items: center;
			position: absolute;
			right: 0;
			top: 0;
			.text{
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				line-height: 40rpx;
				text-align: left;
				margin-right: 16rpx;
			}
			.img{
				width: 24rpx;
				height: 24rpx;
			}
		}
	}
	.path{
		display: flex;
		/* justify-content: space-between; */
		align-items: center;
		margin-bottom: 30rpx;
		.item{
			display: flex;
			align-items: center;
			.img{
				width: 40rpx;
				height: 36rpx;
				margin-right: 8rpx;
			}
			.text{
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
				line-height: 40rpx;
				text-align: left;
			}
		}
	}
}
.searchs{
	background: #fff;
	min-height: 100vh;
	overflow: auto;
	padding: 56rpx 56rpx 0 38rpx;
	.item{
		
		.downlist{
			margin: 0 auto;
			.body{
				display: flex;
				flex-wrap: wrap;
				.item{
					margin-right: 18rpx;
					width: 190rpx;
					margin-bottom: 28rpx;
					height: 60rpx;
					background: #F7F7F7;
					border-radius: 34rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #666666;
					text-align: center;
					line-height: 60rpx;
				}
				.item2{
					background: #EAF2FF;
					border: 2rpx solid #387DF7;
					font-weight: 400;
					font-size: 28rpx;
					color: #387DF7;
				}
				.disabled-item {
				  background-color: #ccc;
				}
			}
			.title{
				display: flex;
				justify-content: center;
				align-items: center;
				.line{
					width: 16rpx;
					border: 2rpx solid #979797;
					margin-left: 6rpx;
					margin-right: 6rpx;
				}
				.btn{
					width: 316rpx;
					height: 60rpx;
					background: #F7F7F7;
					border-radius: 34rpx;
					padding: 0 32rpx 0 40rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-weight: 400;
					font-size: 28rpx;
					color: #666666;
					.img{
						width: 20rpx;
						height: 10rpx;
					}
				}
			}
		}
		.updown{
			display: flex;
			justify-content: space-between;
			.up{
				margin-right: 18rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				.img{
					width: 24rpx;
					height: 16rpx;
					margin-left: 10rpx;
				}
			}
		}
		.title{
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
			line-height: 44rpx;
			text-align: left;
			margin-bottom: 34rpx;
		}
			.check{
				display: flex;
				justify-content: center;
				flex-wrap: wrap;
				margin-bottom: 34rpx;
				.item{
					margin-bottom: 28rpx;
					width: 240rpx;
					height: 60rpx;
					padding: 0 30rpx 0 34rpx;
					border-radius: 34rpx;
					background: #F7F7F7;
					line-height: 60rpx;
					text-align: center;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					font-weight: 400;
					font-size: 28rpx;
					color: #666666;
					.text{
						font-weight: 400;
						font-size: 28rpx;
						color: #666666;
						line-height: 40rpx;
					}
					.img{
						width: 24rpx;
						height: 16rpx;
						margin-left: 14rpx;
					}
				}
				.items{
					width: 240rpx;
					height: 60rpx;
					background: #EAF2FF;
					border-radius: 34rpx;
					border: 1rpx solid #387DF7;
					font-weight: 400;
					font-size: 28rpx;
					color: #387DF7;
				}
			}
		
	}
	.footers{
		width: 100%;
		height: 120rpx;
		position: fixed;
		bottom: 0;
		left: 50%;
		transform: translate(-50%, 0%);
		display: flex;
		justify-content: center;
		/* align-items: center; */
		background: #fff;
		.btn{
			width: 284rpx;
			height: 96rpx;
			line-height: 96rpx;
			border-radius: 48rpx;
			text-align: center;
		}
		.left{
			border: 2rpx solid #387DF7;
			font-weight: 500;
			font-size: 28rpx;
			color: #387DF7;
			margin-right: 36rpx;
		}
		.right{
			background: linear-gradient( 112deg, #5491FD 0%, #2A58FA 100%);
			font-weight: 500;
			font-size: 28rpx;
			color: #FFFFFF;
		}
	}
}

</style>
