<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="competitiveUnits" class="f-c-right">
							<picker @change="onCompetitiveUnitsChange" :value="competitiveUnitsIndex" :range="array"
								:range-key="'name'">
								<view class="picker">
									{{ array[competitiveUnitsIndex]?.name || '请选择竞争单位' }}
									<uni-icons type="right" size="20" color="#A0A0A0"></uni-icons>
								</view>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="信息类型" name="competitorLevelOne" class="f-c-right">
							<picker @change="onCompetitorLevelOneChange" :value="competitorLevelOne" :range="array1"
								:range-key="'name'">
								<view class="picker">
									{{ array1[competitorLevelOneIndex]?.name || '请选择信息类型' }}
									<uni-icons type="right" size="20" color="#A0A0A0"></uni-icons>
								</view>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="具体分类" name="competitorLevelTwo" class="f-c-right">
						  <picker 
						    @change="onCompetitorLevelTwoChange" 
						    :value="competitorLevelTwoIndex" 
						    :range="currentCompetitorLevelTwoArray"
						    :range-key="'name'"
						  >
						    <view class="picker">
						      {{ currentCompetitorLevelTwoArray[competitorLevelTwoIndex]?.name || '请选择具体分类' }}
						      <uni-icons type="right" size="20" color="#A0A0A0"></uni-icons>
						    </view>
						  </picker>
						</uni-forms-item>
						
						
						<uni-forms-item label="具体信息" name="specificMatters" required
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="formData.specificMatters" :placeholder="dynamicPlaceholder"
								 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 {
		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({
		competitiveUnits: "振华云科", //竞争对手
		competitorLevelOne: "基本信息", //竞争对手一级标签
		competitorLevelTwo: "", //竞争对手二级标签
		specificMatters: "", //具体事情
		remark: "", //、备注
		picture: "", //、图片
		informationType: "竞争对手信息" //信息类型
	})

	// 表单验证规则
	const rules = {
		competitiveUnits: {
			rules: [{
				required: true,
				errorMessage: '请选择竞争单位'
			}]
		},
		competitorLevelOne: {
			rules: [{
				required: true,
				errorMessage: '请选择信息类型'
			}]
		},
		competitorLevelTwo: {
			rules: [{
				required: true,
				errorMessage: '请选择具体分类'
			}]
		},
		specificMatters: {
			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: '广州创天'
		},
		{
			id: 7,
			name: '贝迪斯'
		},
		{
			id: 8,
			name: '禹龙通电子'
		},
		{
			id: 9,
			name: '成都昊天'
		},
		{
			id: 10,
			name: '风华特种'
		},
		{
			id: 11,
			name: '济宁正和'
		},
		{
			id: 12,
			name: '盛世'
		},
		{
			id: 13,
			name: '广东意杰'
		},
		{
			id: 14,
			name: '西安威特'
		},
		{
			id: 15,
			name: '盛雷城'
		},
		{
			id: 16,
			name: '广东福德'
		},
		{
			id: 17,
			name: '咸阳智联'
		},
		{
			id: 18,
			name: '安徽来福'
		},
		{
			id: 19,
			name: '国巨'
		},
		{
			id: 20,
			name: '开步电子'
		},
		{
			id: 21,
			name: '成都宏鸣'
		},
		{
			id: 22,
			name: '其他'
		},

	])
	const array1 = ref([{
			id: 0,
			name: '基本信息'
		},
		{
			id: 1,
			name: '业务信息'
		},
	])
	const array2 = ref([{
			id: 0,
			name: '资质情况'
		},
		{
			id: 1,
			name: '人员情况'
		},
		{
			id: 2,
			name: '产品种类(新研制产品、主推产品)'
		},
		{
			id: 3,
			name: '近三年销售情况'
		},
		{
			id: 4,
			name: '市场组织架构'
		},
		{
			id: 5,
			name: '市场策略'
		},
		{
			id: 6,
			name: '竞争对手变化产生的市场机会'
		},
		{
			id: 7,
			name: '其他'
		},
	])
	const array3 = ref([{
			id: 0,
			name: '质量问题'
		},
		{
			id: 1,
			name: '重大市场活动'
		},
		{
			id: 2,
			name: '市场占有率'
		},
		{
			id: 3,
			name: '与客户人员的关系'
		},
		{
			id: 4,
			name: '竞争动向'
		},
		{
			id: 5,
			name: '其他'
		},
	])
	
const dynamicPlaceholder = computed(() => {
  const placeholderMap = {
    '资质情况': '2020年通过IATF16949 汽车质量管理体系认证，IATF证书编号：0368475，CASC证书编号：2020A069；/四川永星目前有二筛条件，已经拿到CANS认证，可以对电阻器进行二筛。',
      '人员情况': '893厂，现有员工900余人，在全国设立6个办事处/云科成都办事处有五人，负责成都、绵阳、重庆，对接凯天的是罗晓波',
      '产品种类(新研制产品、主推产品)': '云科已申请RN5161系列进入SAST-G目录，目前尚未完成进目录工作。/云科：2022年薄膜电路产品上市。',
      '近三年销售情况': '2021年云科销售浆料8亿元/1、云科一年在隆盛的电阻销售额在200万左右，保险丝的销售额也在200万左右。2、云科一季度在607所的销售额大概在150万左右；',
      '市场组织架构': '1、云科市场部新上任一位领导，与九院13所领导副所长关系密切；2、西安办事处新换办事处主任杨文建，是振华集团领导的亲属；3、云科北京片区今年更换领导，是从振华富调过去的，并且把原来负责九院的业务员吴明金撤了，更换了新的业务员；1、振华云科的河南地区新增一位业务员（胡心圣）。2、佰威达的老板是施广勤，同时也是博威的老板。',
      '市场策略': '1、外围进攻：通过熔断器、射频等产品抢占常规电阻器份额，例如中航工业金城南京机电液压工程研究中心，云科的片阻已有少量供货。2、盯住高价值产品：抢占我们高价值产品（合金箔、熔断器、射频）的最主要客户的市场份额，例如九院16所、兵器212所，但目前仍未得手。低价策略：风华和火炬今年想以低价策略进驻抢占份额。目前普军级F精度报价0.5，J精度报价0.2。',
      '竞争对手变化产生的市场机会': '893将一部分股份卖给北海银河，银河快倒闭时改行做医药行业，不景气',
      '其他': '请输入其他补充信息',
      '质量问题': '在核九院五所，云科产品出现批次性硫化问题，云科及时处理，用抗硫化产品做了替代。893在梅岭说我司08年质量问题，基础采购员都知道了这个情况，说不敢选择我司火工品。目前常规片式产品普军等级，云科与我司均为8毛，893报6毛未选择他们。',
      '重大市场活动': '云科在航天五院举办党建活动',
      '市场占有率': '云科在航天领域的市场占有率为30%（信息来源是XXX)/振华云科在航天航空的份额占比大概在60%，大都基于领导层的关系基础，几乎不会来司拜访用户。',
      '与客户人员的关系': '振华集团高层跟118厂高层关系很好，有时会来上海组织联谊活动/青岛整流器制造有限公司有云科内线，了解我公司价格。',
      '竞争动向': '中电科技集团重庆声光电有限公司的106项目893中标/云科：最近一次竞标常规国军标0.55元/只（单一规格用量60万只)，D精度厚膜0.9元/只(2个规格共20万只)，通过这次竞标得到三个单一规格电阻的采购。'
    
  }
  return placeholderMap[formData.value.competitorLevelTwo] || '请输入具体信息'
})
	const competitiveUnitsIndex = ref(0)

	// 当前选中的信息类型
	const competitorLevelOneIndex = ref(0)
	const competitorLevelOne = ref('基本信息')
	const competitorLevelTwo = ref('资质情况')
	// 当前选中的具体分类索引
	const competitorLevelTwoIndex = ref(0)
	
	// 当前显示的具体分类选项数组（动态切换 array2 / array3）
	const currentCompetitorLevelTwoArray = ref(array2.value)

	// 表单引用 & 客户选择器引用
	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
	}
	// 提交表单
	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);
			      
			console.log('表单数据:', formData.value)
		} catch (err) {
			console.log('表单验证失败:', err)
		}
	}

	const onCompetitiveUnitsChange = (e) => {
		competitiveUnitsIndex.value = e.detail.value
		console.log('competitiveUnitsIndex:', array.value[e.detail.value]?.name)
		formData.value.competitiveUnits = array.value[e.detail.value]?.name || ''
	}
	const onCompetitorLevelOneChange = (e) => {
	  if (e.detail.value >= 0 && e.detail.value < array1.value.length) {
	    competitorLevelOneIndex.value = e.detail.value
	  } else {
	    console.error('选择了无效的索引，重置为 0')
	    competitorLevelOneIndex.value = 0
	  }
	  const selectedType = array1.value[e.detail.value]?.name
	  console.log('选中的信息类型:', selectedType)
	
	  formData.value.competitorLevelOne = selectedType
	
	  if (selectedType === '基本信息') {
	    currentCompetitorLevelTwoArray.value = array2.value
	    competitorLevelTwoIndex.value = 0
	    formData.value.competitorLevelTwo = currentCompetitorLevelTwoArray.value[0]?.name || ''
	  } else if (selectedType === '业务信息') {
	    currentCompetitorLevelTwoArray.value = array3.value
	    competitorLevelTwoIndex.value = 0
	    formData.value.competitorLevelTwo = currentCompetitorLevelTwoArray.value[0]?.name || ''
	  } else {
	    currentCompetitorLevelTwoArray.value = []
	    formData.value.competitorLevelTwo = ''
	  }
	}
	
	const onCompetitorLevelTwoChange = (e) => {
	  competitorLevelTwoIndex.value = e.detail.value
	  formData.value.competitorLevelTwo = currentCompetitorLevelTwoArray.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(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>