<template>
	<view class="con-body">
		<view class="con-bg">
			<!-- 头部 -->
			<customHeader ref="customHeaderRef" :title="'人员变化添加'" :leftFlag="true" :rightFlag="true">
				<template #right>
					<view class="head-right" @click="submitForm">
						<uni-icons custom-prefix="iconfont" type="icon-phonebaocun" size="22"
							color="#B7D2FF"></uni-icons>保存
					</view>
				</template>
			</customHeader>

			<!-- 高度来避免头部遮挡 -->
			<view class="top-height"></view>

			<!-- 正文内容 -->
			<view class="white-bg">
				<view class="form-con">
					<uni-forms ref="formRef" :model="formData" :rules="rules" label-width="100px">
						<uni-forms-item label="客户名称" name="cusName" class="f-c-right">
							<view @click="chooseCustomer" class="form-item-container">
								<text class="name">{{ formData.cusName || '点击选择客户' }}</text>
							</view>
						</uni-forms-item>
						<uni-forms-item label="客户人员" name="cusUserName" class="f-c-right">
							<uni-easyinput v-model="formData.cusUserName" placeholder="请选择客户人员" name="input"
								@focus="chooseClientUser"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="原职务" name="originalPosition" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.originalPosition"
								placeholder="请输入原职务" class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="现职务" name="currentPosition" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.currentPosition"
								placeholder="请输入现职务" class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="现职务是否与我司业务相关" name="positionOfOurCompany" class="f-c-right">
							<picker @change="onpoSitionOfOurCompanyChange" :value="positionOfOurCompanyIndex"
								:range="array" :range-key="'name'">
								<view class="picker">
									{{ array[positionOfOurCompanyIndex]?.name || '请选择机会类型' }}
									<uni-icons type="right" size="20" color="#A0A0A0"></uni-icons>
								</view>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="公关力度" name="developmentEfforts" class="f-c-right">
							<picker @change="onDevelopmentEffortsChange" :value="developmentEffortsIndex"
								:range="array1" :range-key="'name'">
								<view class="picker">
									{{ array1[developmentEffortsIndex]?.name || '请选择公关力度' }}
									<uni-icons type="right" size="20" color="#A0A0A0"></uni-icons>
								</view>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="继任者" name="successor" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.successor" placeholder="请输入继任者"
								class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="备注" name="remark" class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.remark" placeholder="请输入备注"
								class="form-texarea" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		onUnmounted,
		computed
	} from 'vue'
	import customHeader from '@/components/customHeader.vue'
	import cache from '@/utils/cache'
	import {
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		getGuestList
	} from '@/api/business.js'
	import {
		isEmpty
	} from '@/utils/validate.js'
	import {
		crmMarketInformationAdd
	} from '@/api/crm/api_ys.js'


	let customerUser = reactive({})
	// 客户相关
	const guestList = ref([])
	const guestArr = ref([])
	const guestIndex = ref(0)

	// 表单数据
	const formData = ref({
		cusId: null,
		cusName: null,
		cusUserName: null, //客户人员名称
		originalPosition: null, //原职务
		currentPosition: null, //现职务
		positionOfOurCompany: '是', //现职务是否与我公司业务相关
		developmentEfforts: '加强', //攻关力度
		successor: null, //继任者
		remark: "", //、备注
		picture: "", //、图片
		photos: null,
		cusPersonnel: '',
		informationType: "人员变化信息" //信息类型
	})

	// 表单验证规则
	const rules = {
		cusName: {
			rules: [{
				required: true,
				errorMessage: '请选择客户'
			}]
		},
		cusUserName: {
			rules: [{
				required: true,
				errorMessage: '请选择客户人员'
			}]
		},
		originalPosition: {
			rules: [{
				required: true,
				errorMessage: '请输入原职务'
			}]
		},
		currentPosition: {
			rules: [{
				required: true,
				errorMessage: '请输入现职务'
			}]
		},
		positionOfOurCompany: {
			rules: [{
				required: true,
				errorMessage: '请选择现职务是否与我公司业务相关'
			}]
		},
		developmentEfforts: {
			rules: [{
				required: true,
				errorMessage: '请选择公关力度'
			}]
		},
		successor: {
			rules: [{
				required: true,
				errorMessage: '请输入继任者'
			}]
		},
	}
	const imgList = ref([])

	// picker 相关
	const index = ref(0)
	const array = ref([{
			id: 0,
			name: '是'
		},
		{
			id: 1,
			name: '否'
		}
	])

	const array1 = ref([{
			id: 0,
			name: '加强'
		},
		{
			id: 1,
			name: '维持'
		},
		{
			id: 2,
			name: '减弱'
		}

	])
	const opportunityTypeIndex = ref(0)
	const positionOfOurCompanyIndex = ref(0)
	const developmentEffortsIndex = ref(0)
	// 表单引用 & 客户选择器引用
	const formRef = ref(null)
	const customHeaderRef = ref(null)
	// 选择客户页面跳转
	function chooseCustomer() {
		uni.navigateTo({
			url: '/pages/business/CRM/marketActivity/chooseCus'
		})
	}
	//定义数据接收的值
	let selectedCustomer = reactive(null)

	//监听时间
	onMounted(() => {
		uni.$on('onCustomerSelected', handleCustomerSelected)
	})
	//取消监听
	onUnmounted(() => {
		uni.$off('onCustomerSelected', handleCustomerSelected)
	})

	//处理 接收数据
	const handleCustomerSelected = (data) => {
		formData.value.cusName = data.cusName
		formData.value.cusId = data.cusId
		console.log("收到客户数据的值：", customerUser)
	}

	//选择客户人员
	function chooseClientUser() {
		console.log('点击了输入框', formData.value.cusName);
		uni.navigateTo({
			url: '/pages/business/CRM/customerUserList?cusName=' + formData.value.cusName
		})
	}
	//页面渲染完成后，查询catch的get
	onShow(() => {

		if (cache.get('checkedRCClientList') != null && cache.get('checkedRCClientList') != []) {
			formData.value.cusUserName = cache.get('checkedRCClientList')
		}

	})
	//页面卸载之后，删除缓存信息
	onUnload(() => {
		handleDeleteLocal()
	})

	//删除缓存
	let handleDeleteLocal = () => {
		cache.remove('checkedRCClientList');
	}

	// 提交表单
	const submitForm = async () => {
		try {
			// 表单校验
			await formRef.value.validate()
			const cusUserName1 = formData.value.cusUserName;
			const stringOfNames = cusUserName1.join(",")
			formData.value.cusUserName = stringOfNames
			const res = await crmMarketInformationAdd(formData.value);
			console.log(res)
			uni.showToast({
				title: '提交成功',
				icon: 'success'
			})
			uni.$emit('refreshMarketList');
			setTimeout(() => {
				uni.navigateBack(1);
			}, 1500);

		} catch (err) {
			console.log('表单验证失败:', err)
		}
	}

	const onOpportunityTypeChange = (e) => {
		opportunityTypeIndex.value = e.detail.value
		console.log('opportunityTypeIndex:', array.value[e.detail.value]?.name)
		formData.value.opportunityType = array.value[e.detail.value]?.name || ''
	}

	const onpoSitionOfOurCompanyChange = (e) => {
		positionOfOurCompanyIndex.value = e.detail.value
		console.log('positionOfOurCompanyIndex:', array.value[e.detail.value]?.name)
		formData.value.positionOfOurCompany = array.value[e.detail.value]?.name || ''
	}

	const onDevelopmentEffortsChange = (e) => {
		developmentEffortsIndex.value = e.detail.value
		console.log('developmentEffortsIndex:', array1.value[e.detail.value]?.name)
		formData.value.opportunityType = array1.value[e.detail.value]?.name || ''
	}
	// 如果你原来在 onShow 中做了类似这样：
	// let res = currPage.data.cusData; 判断是否传入了客户信息
	// 那么在 Vue3 中通常是通过路由参数或者 Vuex/Pinia 等状态管理获取
	// 暂时不做，如你后续需要可继续补充
</script>

<style scoped>
	.white-bg {
		width: 750rpx;
		padding: 30rpx 0 0;
		margin-bottom: 0;
		border-radius: 8px 8px 0 0;
	}

	.form-con {
		/* #ifdef APP-PLUS */
		height: calc(120vh - 100px)
			/* #endif */
			/* #ifndef APP-PLUS */
			height:calc(120vh - 80px)
			/* #endif */
	}

	:deep(.uni-date-x) {
		display: block;
	}

	:deep(.uni-date-x .icon-calendar) {
		float: right;
		margin-top: 15rpx;
		margin-right: 20rpx;
		background: url('../../../static/images/business/icon-date.png') no-repeat;
		background-size: 32rpx 35rpx;
		width: 32rpx;
		height: 35rpx;
	}

	:deep(.uni-date-x .icon-calendar::before) {
		display: none;
	}

	:deep(.uni-date-x .uni-date__x-input) {
		padding-left: 20rpx;
		color: #919191;
	}
</style>