<template>
	<view class="con-body">
		<view class="con-bg">
			<!-- 头部 -->
			<customHeader ref="customHeaderRef" :title="'市场信息管理'" :leftFlag="true" :rightFlag="true">
				<template #right>
					<view class="head-right" @click="handleAdd">
						<uni-icons type="plus" size="24" color="#B7D2FF"></uni-icons>新增
					</view>
				</template>
			</customHeader>

			<!-- 高度来避免头部遮挡 -->
			<view class="top-height" :style="{ paddingTop: navBarPaddingTop + 'px' }"></view>

			<!-- 正文内容 -->
			<view class="all-body market-con">
				<view class="nav-list">
					<view class="nav-item" :class="{active:index==activeTab}" v-for="(item,index) in tabList"
						:key="index" @click="handleNav(index)">{{ item }}</view>
				</view>

				<!-- 分页部分  -->
				<mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
					:up="upOption" :down="downOption" :fixed="false" textColor="#ffffff" bgColor="#ffffff"
					class="scroll-h" :class="{'loading-scroll':cssFlag}">
					<!-- 市场机会信息 -->
					<block v-if="activeTab === 0">
						<view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index"
							@click="itemClick(item)">
							<view class="report-list">
								<view class="title r-list">
									<view class="r-left" style="font-size:38rpx;">{{ item.cusName }}</view>
									<view class="r-right btn-gray flex-auto" :class="{'btn-blue':item.state==='完成'}"
										size="mini" @click.stop="itemView(item)">{{ item.state }}</view>
								</view>
								<view style="padding:0rpx 0 10rpx">
									<view class="font-bold" style="padding-bottom:10rpx">机会类型:{{item.opportunityType}}
									</view>
									<view class="font-bold" style="padding-bottom:10rpx">
										机会所处状态:{{item.opportunityStatus}}</view>
									<!-- <view class="font-gray">{{ item.desc }}</view>灰色样式 -->
								</view>
							</view>
						</view>
					</block>
					<!-- 重大事项信息 -->
					<block v-if="activeTab === 1">
						<view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index" @click="itemClick(item)">
							<view class="report-list">
								<view class="title r-list">
									<view class="r-left" style="font-size:38rpx;">{{ item.cusName }}</view>
									<view class="r-right btn-gray flex-auto" :class="{'btn-blue':item.state==='完成'}"
										size="mini" @click.stop="itemView(item)">{{ item.state }}</view>
								</view>
								<view style="padding:0rpx 0 10rpx">
									<view class="font-bold" style="padding-bottom:10rpx">
										产生的影响:{{item.theImpactGenerated}}</view>
									<view class="font-bold" style="padding-bottom:10rpx">
										重大事项类型:{{item.opportunityType}}</view>
									<!-- <view class="font-gray">{{ item.desc }}</view> -->
								</view>
							</view>
						</view>
					</block>
					<!-- 竞争对手信息 -->
					<block v-if="activeTab === 2">
						<view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index" @click="itemClick(item)">
							<view class="report-list">
								<view class="title r-list">
									<view class="r-left" style="font-size:38rpx;">{{ item.competitiveUnits }}</view>
									<view class="r-right btn-gray flex-auto" :class="{'btn-blue':item.state==='完成'}"
										size="mini" @click.stop="itemView(item)">{{ item.state }}</view>
								</view>
								<view style="padding:0rpx 0 10rpx">
									<view class="font-bold" style="padding-bottom:10rpx">
										竞争对手一级标签:{{item.competitorLevelOne}}</view>
									<view class="font-bold" style="padding-bottom:10rpx">
										竞争对手二级标签:{{item.competitorLevelTwo}}</view>
									<!-- <view class="font-gray">{{ item.desc }}</view> -->
								</view>
							</view>
						</view>
					</block>
					<!-- 人员变化信息 -->
					<block v-if="activeTab === 3">
						<view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index" @click="itemClick(item)">
							<view class="report-list">
								<view class="title r-list">
									<view class="r-left" style="font-size:38rpx;">{{ item.cusName }}</view>
									<view class="r-right btn-gray flex-auto" :class="{'btn-blue':item.state==='完成'}"
										size="mini" @click.stop="itemView(item)">{{ item.state }}</view>
								</view>
								<view style="padding:0rpx 0 10rpx">
									<view class="font-bold" style="padding-bottom:10rpx">客户人员名称:{{item.cusUserName}}
									</view>
									<view class="font-bold" style="padding-bottom:10rpx">原职务:{{item.originalPosition}}
									</view>
									<view class="font-bold" style="padding-bottom:10rpx">现职务:{{item.currentPosition}}
									</view>
									<!-- <view class="font-gray">{{ item.desc }}</view> -->
								</view>
							</view>
						</view>
					</block>
					<!-- 重点型号任务信息 -->
					<block v-if="activeTab === 4">
						<view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index" @click="itemClick(item)">
							<view class="report-list">
								<view class="title r-list">
									<view class="r-left" style="font-size:38rpx;">{{ item.cusName }}</view>
									<view class="r-right btn-gray flex-auto" :class="{'btn-blue':item.state==='完成'}"
										size="mini" @click.stop="itemView(item)">{{ item.state }}</view>
								</view>
								<view style="padding:0rpx 0 10rpx">
									<view class="font-bold" style="padding-bottom:10rpx">重点型号:{{item.keyModels}}</view>
									<view class="font-bold" style="padding-bottom:10rpx">目前状态:{{item.currentStatus}}
									</view>
									<view class="font-gray">{{ item.desc }}</view>
								</view>
							</view>
						</view>
					</block>
					<!-- 通用表单 -->
					<block v-if="activeTab === 5">
						<view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index" @click="itemClick(item)">
							<view class="report-list">
								<view class="title r-list">
									<view class="r-left" style="font-size:38rpx;">{{ item.cusName }}</view>
									<view class="r-right btn-gray flex-auto" :class="{'btn-blue':item.state==='完成'}"
										size="mini" @click.stop="itemView(item)">{{ item.state }}</view>
								</view>
								<view style="padding:0rpx 0 10rpx">
									<view class="font-bold" style="padding-bottom:10rpx">标签:{{item.generalFormType}}
									</view>

									<view class="font-gray">内容:{{ item.informationContent }}</view>
								</view>
							</view>
						</view>
					</block>
				</mescroll-uni>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import customHeader from '@/components/customHeader.vue'
	import MescrollUni from 'mescroll-uni/mescroll-uni.vue';
	import {
		getNavBarPaddingTop
	} from '@/utils/system.js'
	import {
		mattersList
	} from '@/api/business.js'
	import {
		CrmMarketInformationList,
		handleCrmMarketInfo
	} from '@/api/crm/api_ys.js' 
	// 获取导航栏高度用于内容区域padding
	const navBarPaddingTop = ref(0);
	onMounted(() => {
		navBarPaddingTop.value = getNavBarPaddingTop() * 2;
		uni.$on('refreshMarketList', handleRefreshList);
	})
	onUnmounted(() => {
	  // 移除事件监听
	  uni.$off('refreshMarketList', handleRefreshList);
	});
	const mescrollInstance = ref(null);
	const activeTab = ref(0); // 默认市场机会
	const tabList = ['市场机会', '重大事项信息', '竞争对手信息', '人员变化信息', '重点型号任务信息', '通用表单'];
	let handleNav = (index) => {
		console.log(index + " 切换列表");
		activeTab.value = index;

		// 先重置列表（可选，避免新旧数据混在一起）
		list.value = [];

		// 手动触发 mescroll 下拉刷新，重新加载当前 tab 的数据
		if (mescrollInstance.value) {
			mescrollInstance.value.triggerDownScroll(); // 关键！触发下拉刷新，会调用 downCallback
		}
	}
	// 新增
	let handleAdd = () => {
		if (activeTab.value == 0) {
			console.log("市场机会")
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/marketOpportunities'
			})
		} else if (activeTab.value == 1) {
			console.log("重大机会事项")
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/majorMatter'
			})
		} else if (activeTab.value == 2) {
			console.log("竞争对手信息")
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/competitor'
			})
		} else if (activeTab.value == 3) {
			console.log("人员变化信息")
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/personnelChanges'
			})
		} else if (activeTab.value == 4) {
			console.log("重点型号任务信息")
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/keyModelTasks'
			})
		} else if (activeTab.value == 5) {
			console.log("通用表单")
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/beCurrent'
			})
		} else {
			console.log("其他？")
		}
		// uni.navigateTo({ url: '/pages/business/CRM/visitorReportAdd' })
	}

	// 查询列表
	let list = ref([]);
	const mescrollRef = ref(null);
	const upOption = ref({
		page: {
			num: 0,
			size: 10
		},
		noMoreSize: 5,
		empty: {
			tip: '~ 空空如也 ~',
			icon: "../../../../static/images/mescroll-empty.png"			
		},
		textLoading: '加载中...',
		textNoMore: '已经到底了'
	});

	const downOption = ref({
		auto: false,
		textInOffset: '下拉刷新',
		textOutOffset: '释放更新',
		textLoading: '刷新中...'
	});

	let cssFlag = ref(false); //控制样式
	const mescrollInit = (mescroll) => {
		cssFlag.value = true;
		mescrollRef.value = mescroll;
		mescrollInstance.value = mescroll;
	};

	// 下拉刷新
	const downCallback = async (mescroll) => {
		try {
			const pageNo = 1;
			const pageSize = upOption.value.size;
			const type = activeTab.value + 1; // 当前tab索引
			const description = tabList[activeTab.value]; // 当前tab文字

			const res = await getCrmMarketInformationList(pageNo, pageSize, type, description);
			list.value = res.list;
			mescroll.resetUpScroll();
		} catch (error) {
			mescroll.endErr();
		} finally {
			mescroll.endSuccess();
		}
	}
	// 上拉加载更多
	const upCallback = async (mescroll) => {
		try {
			const pageNo = mescroll.num;
			const pageSize = mescroll.size;
			const type = activeTab.value; // 当前tab索引
			const description = tabList[activeTab.value]; // 当前tab文字

			const res = await getCrmMarketInformationList(pageNo, pageSize, type, description);
			if (mescroll.num === 1) {
				list.value = res.list;
			} else {
				list.value.push(...res.list);
			}
			mescroll.endBySize(res.list.length, res.total);
		} catch (error) {
			mescroll.endErr();
		}
	}

	// 获取数据列表
	const getCrmMarketInformationList = async (pageNo, pageSize, type, description) => {
		const param = {
			pageNo,
			pageSize,
			type,
			description
		};

		const res = await CrmMarketInformationList(param);
		return {
			list: res.rows,
			total: res.total
		};
	}

	const itemView = async (item) => {
		const state = (item.state || "").trim().toLowerCase()
		if (state === "待提交" || state === "驳回") {
			uni.showModal({
				title: '操作确认',
				content: '是否为商业航天行业板块信息？',
				confirmText: '是',
				cancelText: '否',
				success: async (res) => {
					if (res.confirm) {
						item.commercialAerospace = "是"
						try {
							const res = await handleCrmMarketInfo(item)
							if (res.code == 200) {
								uni.showToast({
									title: '提交成功',
									duration: 2000
								})
								handleRefreshList();
							} else {
								uni.showToast({
									title: res.msg || '操作失败',
									icon: 'none'
								})
							}
							
						} catch {
							uni.showToast({
								title: '提交失败，请重试',
								icon: 'none'
							})
						}
					} else if (res.cancel) {
						item.commercialAerospace = "否"
						try {
							const res = await handleCrmMarketInfo(item)
							if (res.code == 200) {
								uni.showToast({
									title: '提交成功',
									duration: 2000
								})
								handleRefreshList();
							} else {
								uni.showToast({
									title: res.msg || '操作失败',
									icon: 'none'
								})
							}
							
						} catch {
							uni.showToast({
								title: '提交失败，请重试',
								icon: 'none'
							})
						}
					}
				}
			})
		} else {
			uni.showToast({
				title: "当前状态不可操作",
				icon: "none",
				duration: 2000
			})
		}
	}



	const itemClick = async (item) => {
		if(item.informationType=='市场机会'){
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/marketOpportunitiesDetail?informationId='+ item.informationId
			})
		}else if(item.informationType=='重大事项信息'){
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/majorMatterDetail?informationId='+ item.informationId
			})
			
		}else if(item.informationType=='竞争对手信息'){
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/competitorDetail?informationId='+ item.informationId
			})
		}else if(item.informationType=='人员变化信息'){
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/personnelChangesDetail?informationId='+ item.informationId
			})
		}else if(item.informationType=='重点型号任务信息'){
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/keyModelTasksDetail?informationId='+ item.informationId
			})
		}else if(item.informationType=='通用表单'){
			uni.navigateTo({
				url: '/pages/business/CRM/marketInformation/beCurrentDetail?informationId='+ item.informationId
			})
		}
		
		else{
			console.log("其他")
		}
		// console.log(item)
		// uni.navigateTo({ url: '/pages/business/CRM/visitorReportAdd' })
	}
	const handleRefreshList = () => {
	  if (mescrollInstance.value) {
	    mescrollInstance.value.triggerDownScroll();
	  }
	};
	
	
</script>

<style scoped>
	.all-body {
		/* #ifdef APP-PLUS */
		top: 88rpx;
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef APP-PLUS */
		top: 100rpx;
		height: calc(100vh - 48px);
		/* #endif */
	}

	/*.market-con{

} */

	.nav-list {
		display: flex;
		flex-wrap: wrap;
		/* #ifdef APP-PLUS */
		padding: 80rpx 30rpx 0;
		/* #endif */
		/* #ifndef APP-PLUS */
		padding: 20rpx 30rpx 0;
		/* #endif */
	}

	.nav-list .nav-item {
		background-color: #05A3F4;
		border-radius: 10rpx;
		color: #FFFFFF;
		font-size: 28rpx;
		text-align: center;
		padding: 10rpx 25rpx;
		margin-right: 15rpx;
		margin-bottom: 20rpx;
	}

	.nav-list .nav-item:nth-child(3n) {
		margin-right: 0;
	}

	.nav-list .nav-item.active {
		background-color: #fff;
		color: #3384DF;
		font-weight: bold;

	}

	.report-list .r-list {
		align-items: flex-start;
	}


	.scroll-h {
		/* #ifdef APP-PLUS */
		height: calc(100vh - 155px);
		/* #endif */
		/* #ifndef APP-PLUS */
		height: calc(100vh - 135px);
		/* #endif */
	}

	.white-bg {
		padding-top: 10rpx;
		padding-bottom: 10rpx;
	}

	.report-list .title {
		display: flex;
	}
	.btn-blue {
	  background-color: #3384DF; /* 蓝色背景 */
	  color: #ffffff;
	}
</style>