<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="opportunityType" class="f-c-right">
							<picker @change="onOpportunityTypeChange" :value="opportunityTypeIndex" :range="array"
								:range-key="'name'">
								<view class="picker">
									{{ array[opportunityTypeIndex]?.name || '请选择机会类型' }}
									<uni-icons type="right" size="20" color="#A0A0A0"></uni-icons>
								</view>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="了解途径" name="understandTheWay" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.understandTheWay"
								placeholder="请输入了解途径" class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="机会描述" name="opportunityDescription" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.opportunityDescription"
								placeholder="请输入机会描述" class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="机会所处状态" name="opportunityStatus" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.opportunityStatus"
								placeholder="请输入机会所处状态" class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="预测金额情况" name="predictedAmount" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.predictedAmount"
								placeholder="请输入预测金额或情况" class="form-texarea" />
						</uni-forms-item>
						<uni-forms-item label="竞争情况" name="competitionSituation" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.competitionSituation"
								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 class="footer-con">
					    <button class="btn-default" type="default" @click="handleDelete" size="mini">删 除</button>
					    <button class="btn-primary" type="primary" @click="submitForm" size="mini">保存/修改</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		 ref, onMounted, reactive, onUnmounted, computed ,watch
	} from 'vue'
	import customHeader from '@/components/customHeader.vue'
	import {
		getGuestList
	} from '@/api/business.js'
	import { isEmpty } from '@/utils/validate.js'
	import { onLoad } from '@dcloudio/uni-app'
	import {crmMarketInformationAdd,crminformationItemForDetail,crmMarketInformationDelete } from '@/api/crm/api_ys.js'
	import { useMessage } from '@/utils/message.js'
	import cache from '@/utils/cache.js'
	
	const message = useMessage();
	let customerUser = reactive({})
	// 客户相关
	const guestList = ref([])
	const guestArr = ref([])
	const guestIndex = ref(0)

	// 表单数据
	const formData = ref({
		cusId: null,
		cusName: null,
		opportunityType: "", // 机会类型
		understandTheWay: "", // 了解途径
		opportunityDescription: "", // 机会描述
		opportunityStatus: "", // 机会所处状态
		predictedAmount: "", // 预测金额或情况
		competitionSituation: "", // 竞争情况
		remark: "", // 备注
		picture: "", // 图片
		informationType: "市场机会" // 信息类型
	})

	// 表单验证规则
	const rules = {
		cusName: {
			rules: [{
				required: true,
				errorMessage: '请选择客户'
			}]
		},
		opportunityType: {
			rules: [{
				required: true,
				errorMessage: '请选择机会类型'
			}]
		},
		understandTheWay: {
			rules: [{
				required: true,
				errorMessage: '请输入了解途径'
			}]
		},
		opportunityDescription: {
			rules: [{
				required: true,
				errorMessage: '请输入机会描述'
			}]
		},
		opportunityStatus: {
			rules: [{
				required: true,
				errorMessage: '请输入机会所处状态'
			}]
		},
		predictedAmount: {
			rules: [{
				required: true,
				errorMessage: '请输入预测金额或情况'
			}]
		},
		competitionSituation: {
			rules: [{
				required: true,
				errorMessage: '请输入竞争情况'
			}]
		},
	}
	const imgList = ref([])

	// picker 相关
	const index = ref(0)
	const array = ref([{
			id: 0,
			name: '新产品需求'
		},
		{
			id: 1,
			name: '新客户开发'
		},
		{
			id: 2,
			name: '批产任务'
		},
		{
			id: 3,
			name: '新研任务'
		},
		{
			id: 4,
			name: '二筛服务'
		},
		{
			id: 5,
			name: '对手失利'
		},
		{
			id: 6,
			name: '其它'
		}
	])
	const form = ref({
		cusId: null,
		cusName: null,
		opportunityType: "", // 机会类型
		understandTheWay: "", // 了解途径
		opportunityDescription: "", // 机会描述
		opportunityStatus: "", // 机会所处状态
		predictedAmount: "", // 预测金额或情况
		competitionSituation: "", // 竞争情况
		remark: "", // 备注
		picture: "", // 图片
		informationType: "市场机会" // 信息类型
	})

	// picker 选项
	const opportunityTypeOptions = ref([{
			id: 0,
			name: '新产品需求'
		},
		{
			id: 1,
			name: '新客户开发'
		},
		{
			id: 2,
			name: '批产任务'
		},
		{
			id: 3,
			name: '新研任务'
		},
		{
			id: 4,
			name: '二筛服务'
		},
		{
			id: 5,
			name: '对手失利'
		},
		{
			id: 6,
			name: '其它'
		}
	])
	const opportunityTypeIndex = 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)
	}
//定义查询参数
const queryParams = ref({
    informationId: 0
})
onMounted(() => {
    crminformationItemForDetail1()
})
	onLoad(options => {
	    queryParams.value.informationId = options.informationId
	})
	const dataList = ref([])
	function crminformationItemForDetail1() {
	    crminformationItemForDetail(queryParams.value).then(res => {
	       formData.value = res.rows[0]
	    })
	}
	
	// 提交表单
	const submitForm = async () => {
		try {
			// 表单校验
			await formRef.value.validate()
            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)
		}
	}
	// 根据ID删除表单
	const handleDelete = async () => {
		try {

	        const res = await crmMarketInformationDelete (formData.value);
			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 || ''
	}
</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(100vh - 95px) !important;
		/* #endif */
		/* #ifndef APP-PLUS */
		height:calc(100vh - 68px) !important;
		/* #endif */
		overflow-y: auto;
	}

	: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>