<template>
	<view class="post_item" @click.stop="handlePostRootClick">
		<view class="post_top">
			<view class="top_left">{{ item.name }}
				&nbsp;&nbsp;&nbsp;
				<view v-if="item.price" class="price">
					<u-icon name="rmb-circle"></u-icon>
					{{ item.price }}
					<view class="more" v-if="item.hasMoreInquiryPrice" @click.stop="handleInquiry(item)">
						更多
					</view>
				</view>
			</view>
			<view class="top_right">{{ item.assignStateCode === '1' ? "已分配" : "未分配" }}</view>
		</view>
		<view class="post_info">
			<view class="telPhone">
				<view class="phone">
					<text>电话:</text>
					<show-real-text :real="item.telephone" :type='type'
						:style="{ color: item.repetitionOperationName ? 'red' : 'black' }"></show-real-text>
					<template v-if="item.telAddr">
						({{ item.telAddr }})
					</template>
					<text v-if="item.repetitionOperationName">( 撞 : {{ item.repetitionOperationName }})</text>
				</view>
				<view class="copy_btn" @click.stop="handleCopy(item)" v-if="type != '1'">复制</view>
			</view>
			<view class="info" v-if="item.weixin">
				<text>微信:</text>
				<view class="phone">
					<text :style="{ color: item.repetitionOperWeixinName ? 'red' : 'black' }">{{ item.weixin }}</text>
					<text v-if="item.repetitionOperWeixinName">( 撞 : {{ item.repetitionOperWeixinName }})</text>
				</view>
			</view>
			<view class="info">
				<view class="createTime">{{ item.createTime }}</view>
			</view>
			<view class="info">
				<view>{{ item.appName }}</view>
			</view>
			<view class="info">
				<view class="owner">所属人:{{ item.clueOwnerName ? item.clueOwnerName : "-" }}</view>
			</view>
			<view class="info">
				<view class="operation">运营人:{{ item.clueOperationName ? item.clueOperationName : "-" }}</view>
			</view>
			<view class="info latest_follow_row" @click.stop="handleShowFollowDetail(item)">
				<view class="label">最新跟进记录:</view>
				<view class="latest_follow_content">
					<text class="latest_follow_text">{{ item.latestDynamicData || '暂无' }}</text>
					<text class="latest_follow_time" v-if="item.latestDynamicTime">{{ item.latestDynamicTime }}</text>
				</view>
				<!-- <view class="latest_follow_add" @click.stop="handleAddFollow(item)">增加</view> -->
			</view>
		</view>
		<view class="clue_state_wrap">
			<view class="clue_state">
				<view class="state_wrap">
					<view class="label">线索阶段:</view>{{ crm_clue_phase(item.clueState) }}
				</view>
				<view class="clueTag">
					<view class="label">线索标签:</view>
					<u-tag :text="tag.name" plain plainFill borderColor="#fff" size="mini"
						v-for="(tag) in item.clueTags" :key="tag.id" style="margin-right: 10px;" :bgColor="tag.color"
						color="#fff"></u-tag>
				</view>
			</view>
		</view>
		<view class="sendOrder_wrap">
			<view class="sendOrder inquiry" @click.stop="handleInquiry(item)">
				<image src='/static/publicClue/inquiry.png' mode="aspectFit" class="sendOrder_img"></image>
				<view>询价</view>
			</view>
			<view class="sendOrder" @click.stop="handleSendOrder(item)">
				<image src='/static/publicClue/littlePlane.png' mode="aspectFit" class="sendOrder_img"></image>
				<view>发单</view>
			</view>
		</view>
		<add-inquiry-dialog ref="inquiryDialog" :clueId="clueId" :isShowChart="isShowChart" :isClue="true" :editOrAdd="editOrAdd" :editInfo="editInfo" title="询价" @cancel="handleInquiryCancel" :type="1"/>
		<!-- 最新跟进记录详情弹窗；关闭时记时间戳，避免蒙层点击冒泡触发详情跳转 -->
		<u-popup :show="followPopupVisible" mode="bottom" round="16" @close="onFollowPopupClose"
			:closeOnClickOverlay="true" @open="loadFollowList">
			<view class="follow_popup">
				<view class="follow_popup_title">跟进记录</view>
				<scroll-view scroll-y class="follow_popup_list" v-if="followList.length">
					<view class="follow_item" v-for="f in followList" :key="f.id">
						<view class="follow_top">
							<text class="person_name">{{ f.createNickname || f.createNickName || '-' }}</text>
							<text class="follow_time">{{ f.createTime }}</text>
						</view>
						<view class="follow_content">{{ f.content }}</view>
					</view>
				</scroll-view>
				<view class="follow_popup_empty" v-else-if="!followLoading">{{ followListError || '暂无跟进记录' }}</view>
				<view class="follow_popup_loading" v-else>加载中...</view>
				<!-- <view class="follow_popup_footer">
					<u-button type="primary" @click="handleAddFollowFromPopup">增加跟进</u-button>
				</view> -->
			</view>
		</u-popup>
	</view>
</template>

<script>
import addInquiryDialog from '@/components/add-inquiry-dialog/index.vue'
import {
	selectDictLabel
} from "@/utils/util";
export default {
	components: {
		addInquiryDialog
	},
	props: {
		item: {
			type: Object,
			required: true
		},
		dicts: {
			type: Object,
			required: true
		},
		type: {
			type: [String, Number],
			required: true
		},
	},
	data() {
		return {
			caseStatusDicts: [],
			clueId: '',
			editOrAdd: 'add',
			editInfo: {},
			followPopupVisible: false,
			followList: [],
			followLoading: false,
			followListError: '',
			currentFollowClue: null,
			closedFollowPopupAt: 0,
			isShowChart: false
		}
	},
	methods: {
		// 字典翻译
		crm_clue_phase(caseStatus) {
			return selectDictLabel(this.dicts.caseStatusDicts, caseStatus);
		},
		handleCopy(item) {
			uni.setClipboardData({
				data: item.telephone,
				success: function () {
					uni.$u.toast("复制成功");
				}
			});
		},
		// 主页面的发单
		async handleSendOrder(item) {
			console.log(item);
			const {
				data: count
			} = await uni.$u.api.getClueSendFormCountByClueId({
				clueId: item.id
			});
			console.log(count);
			if (count > 0) {
				uni.showModal({
					title: '该线索已发单是否再次发单？',
					success: (res) => {
						if (res.confirm) {
							this.toOrderForm(item)
						}
					}
				});
			} else {
				this.toOrderForm(item)
			}
		},
		toOrderForm(item) {
			console.log(item);
			const {
				id,
				ownLatestDynamicTime,
				createTime,
				clueOwnerId
			} = item;
			if (this.$store.state.user.userInfo.userId === clueOwnerId) {
				uni.navigateTo({
					url: `/pages/orderForm/index?clueId=${id}`
				})
			} else {
				// 确定用于判断的目标时间（ownLatestDynamicTime，为null则用createTime）
				const date = ownLatestDynamicTime || createTime

				const twoDaysLater = new Date(date)
				twoDaysLater.setDate(twoDaysLater.getDate() + 2) // 日期加2天

				// 是否大于当前时间 小于可以发单
				let isOrderForm = false
				if (twoDaysLater) {
					isOrderForm = twoDaysLater.getTime() <= new Date().getTime()
				}
				if (isOrderForm) {
					uni.navigateTo({
						url: `/pages/orderForm/index?clueId=${id}`
					})
				} else {
					uni.$u.toast('非所属人需两天内无跟进记录才可发单')
				}
			}
		},
		// 询价
		async handleInquiry(item) {
			this.clueId = item.id
			if(Number(item.count) > 0 || item.count === '0'){//null:未生成询价数据 0:已生成询价数据但是没有询过价 >0:询过价人数
				const data = {
					clueId: item.id,
					type:1
				}
				this.editOrAdd = 'editForm'
				uni.$u.api.inquiryDetail(data).then(res=>{
					if(res.code === 200){
						this.$nextTick(()=>{
							this.editInfo = res.data
							if(Number(item.count) === 0){
								this.isShowChart = false
							}else{
								this.isShowChart = true
							}
							this.$refs.inquiryDialog.showDialog()
						})
					}
				})
			}else if(!item.count){
				this.editOrAdd = 'add'
				this.isShowChart = false
				this.editInfo = {
					dictLabel:'',
					model:'',
					code:'',
					imgsUrl:[],
					price:'',
					remark:'',
				}
				this.$refs.inquiryDialog.showDialog()
			}
		},
		// 询价取消
		handleInquiryCancel() {
			this.$refs.inquiryDialog.closeDialog()
		},
		// 卡片根节点点击：若刚因点蒙层关闭弹窗则不跳转，否则通知父组件跳转详情
		handlePostRootClick() {
			if (Date.now() - this.closedFollowPopupAt < 400) return
			this.$emit('to-detail', this.item)
		},
		onFollowPopupClose() {
			this.followPopupVisible = false
			this.closedFollowPopupAt = Date.now()
		},
		// 点击最新跟进记录，打开详情弹窗
		handleShowFollowDetail(item) {
			this.currentFollowClue = item
			this.followPopupVisible = true
			this.followList = []
			this.followListError = ''
		},
		// 弹窗打开时加载该线索的跟进列表
		async loadFollowList() {
			if (!this.currentFollowClue || !this.currentFollowClue.id) return
			this.followLoading = true
			this.followListError = ''
			try {
				const res = await uni.$u.api.getClueFollowListByClueId({ clueId: this.currentFollowClue.id })
				this.followList = (res.data || res) || []
			} catch (e) {
				console.error('获取跟进记录失败', e)
				this.followListError = '加载失败'
				this.followList = []
			} finally {
				this.followLoading = false
			}
		},
		// 增加跟进：跳转添加跟进页
		handleAddFollow(item) {
			const id = (item && item.id) || (this.currentFollowClue && this.currentFollowClue.id)
			if (!id) return
			uni.navigateTo({
				url: `/pages/addFollow/index?clueId=${id}`
			})
			this.followPopupVisible = false
		},
		// 弹窗内点击「增加跟进」
		handleAddFollowFromPopup() {
			this.handleAddFollow(this.currentFollowClue)
		},
	},
}
</script>

<style lang="scss" scoped>
.post_item {
	background: #fff;
	border-radius: 20px;
	padding: 20px;
	margin-bottom: 20px;
	position: relative;

	.post_top {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;

		.top_left {
			font-size: 18px;
			display: flex;
			.price{
				display: flex;
				align-items: center;
				gap: 8rpx;
				.more{
					font-size: 20rpx;
					border: 1px solid #3c9cff;
					border-radius:10rpx;
					padding: 3rpx 8rpx;
					color: #3c9cff;
				}
			}
		}

		.top_right {
			color: #87bf66;
		}
	}

	.post_info {
		font-size: 14px;
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 10rpx;
		.telPhone {
			display: flex;
			grid-column: 1 / -1;

			.copy_btn {
				color: #4fa5fe;
				margin-left: 10px;
			}
		}

		.info {
			display: flex;
			// margin-bottom: 10px;
			overflow: hidden;

			> view {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex: 1;
			}

			.createTime {
				margin-right: 10px;
			}

			.copy_btn {
				display: flex;
				flex-wrap: wrap;
			}
		}

		.latest_follow_row {
			align-items: flex-start;
			flex-wrap: wrap;
			grid-column: 1 / -1;

			.label {
				flex: 0 0 90px;
			}

			.latest_follow_content {
				flex: 1;
				min-width: 0;
				display: flex;
				gap: 4px;
				flex-direction: column;
			}

			.latest_follow_text {
				font-size: 13px;
				word-break: break-all;
			}

			.latest_follow_time {
				font-size: 12px;
			}

			.latest_follow_add {
				flex-shrink: 0;
				color: #4fa5fe;
				font-size: 14px;
				margin-left: 8px;
			}
		}
	}

	.clue_state_wrap {
		font-size: 14px;
		background: #f8f9fb;
		padding: 10px;
		color: #9b9aa2;
		overflow: hidden;

		.state_wrap {
			display: flex;
			margin-bottom: 10px;
		}

		.label {
			flex: 0 0 66px;
		}

		.clueTag {
			display: flex;
		}
	}


	.sendOrder_wrap {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;
		.sendOrder {
			width: 50%;
			height: 40px;
			background-color: rgb(36, 98, 234);
			color: #fff;
			border-radius: 20rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 20rpx;
			font-size: 28rpx;
			font-weight: 700;
			font-family: "uicon";
			margin-top: 10rpx;
			.sendOrder_img {
				width: 20px;
				height: 20px;
			}
		}
	
		.inquiry {
			right: 140rpx;
			color: #2563eb;
			border: 1px solid #2563eb;
			background-color: #fff;
		}
	}
	
}

.follow_popup {
	padding: 24rpx 30rpx 40rpx;
	max-height: 70vh;
	display: flex;
	flex-direction: column;

	.follow_popup_title {
		font-size: 34rpx;
		font-weight: 600;
		margin-bottom: 24rpx;
		text-align: center;
	}

	.follow_popup_list {
		flex: 1;
		max-height: 50vh;
		margin-bottom: 24rpx;
	}

	.follow_item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;

		&:last-child {
			border-bottom: none;
		}

		.follow_top {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 12rpx;
			font-size: 24rpx;

			.person_name {
				color: #333;
				font-weight: 500;
			}

			.follow_time {
				color: #999;
			}
		}

		.follow_content {
			font-size: 26rpx;
			color: #666;
			line-height: 1.5;
			word-break: break-all;
		}
	}

	.follow_popup_empty,
	.follow_popup_loading {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 60rpx 0;
	}

	.follow_popup_footer {
		padding-top: 20rpx;
	}
}
</style>