<template>
	<el-dialog v-model="showDialog" :title="
      formData.id ? t('updateCustomerResources') : t('addCustomerResources')
    " width="50%" class="diy-dialog-wrap" :destroy-on-close="true">
		<div class="tab-container">
			<el-tabs v-model="activeTab" class="tab-pane-half">
				<!-- Tab 1: 基本信息 -->
				<el-tab-pane label="客户信息" name="base">
					<el-form :model="formData" label-width="120px" ref="formRef" :rules="formRules" class="page-form"
						v-loading="loading">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item :label="t('source')" prop="source">
									<el-select class="input-width" v-model="formData.source" clearable
										:placeholder="t('sourcePlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in sourceList" :key="index" :label="item.name"
											:value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12" v-if="formData.source == 1">
								<el-form-item :label="t('sourceChannel')">
									<el-select class="input-width" v-model="formData.source_channel" clearable
										:placeholder="t('sourceChannelPlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in source_channelList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>


						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item :label="t('name')" prop="name">
									<el-input v-model="formData.name" clearable :placeholder="t('namePlaceholder')"
										class="input-width" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item :label="t('age')" prop="age">
									<el-input-number v-model="formData.age" clearable :placeholder="t('agePlaceholder')"
										class="input-width" :min="3" max="80" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item :label="t('gender')" prop="gender">
									<el-select class="input-width" v-model="formData.gender" clearable
										:placeholder="t('genderPlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in genderList" :key="index" :label="item.name"
											:value="item.value" />
									</el-select>
								</el-form-item>

							</el-col>
							<el-col :span="12">

								<el-form-item :label="t('phoneNumber')" prop="phone_number">
									<el-input v-model="formData.phone_number" clearable
										:placeholder="t('phoneNumberPlaceholder')" class="input-width" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">

								<el-form-item :label="t('demand')" prop="demand">
									<el-input v-model="formData.demand" type="textarea" rows="4" clearable
										:placeholder="t('demandPlaceholder')" class="input-width" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item :label="t('purchasingPower')" prop="purchasing_power">
									<el-select class="input-width" v-model="formData.purchasing_power" clearable
										:placeholder="t('purchasingPowerPlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in purchasing_powerList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item :label="t('cognitiveIdea')" prop="cognitive_idea">
									<el-select class="input-width" v-model="formData.cognitive_idea" clearable
										:placeholder="t('cognitiveIdeaPlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in cognitive_ideaList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">

								<el-form-item :label="t('optionalClassTime')" prop="optional_class_time"
									class="input-width">
									<el-date-picker class="flex-1 !flex" v-model="formData.optional_class_time"
										clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
										:placeholder="t('optionalClassTimePlaceholder')">
									</el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="12">
								
								<el-form-item :label="t('distance')" prop="distance">
									<el-select class="input-width" v-model="formData.distance" clearable
										:placeholder="t('distancePlaceholder')">
										<el-option label="远60分钟以上路程" value="远60分钟以上路程"></el-option>
										<el-option label="适中20-60分钟路程" value="适中20-60分钟路程"></el-option>
										<el-option label="近20分钟以内" value="近20分钟以内"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">

									<el-form-item :label="t('decisionMaker')" prop="decision_maker">
										<el-select class="input-width" v-model="formData.decision_maker" clearable
											:placeholder="t('decisionMakerPlaceholder')">
											<el-option label="妈妈" value="妈妈"></el-option>
											<el-option label="爸爸" value="爸爸"></el-option>
											<el-option label="双亲" value="双亲"></el-option>
											<el-option label="长辈" value="长辈"></el-option>
											<el-option label="其他亲属" value="其他亲属"></el-option>
											<el-option label="不详" value="不详"></el-option>
										</el-select>
									</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item :label="t('initialIntent')" prop="initial_intent">
									<el-select class="input-width" v-model="formData.initial_intent" clearable
										:placeholder="t('initialIntentPlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in initial_intentList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item :label="t('campus')" prop="campus">
									<el-select class="input-width" v-model="formData.campus" clearable
										:placeholder="t('campusPlaceholder')" :disabled="!!campus">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in campusList" :key="index"
											:label="item['campus_name']" :value="item['id']" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item :label="t('status')" prop="status">
									<el-select class="input-width" v-model="formData.status" clearable
										:placeholder="t('statusPlaceholder')">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in statusList" :key="index" :label="item.name"
											:value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">


								<el-form-item label="会员标签">
									<el-select v-model="formData.member_label" multiple collapse-tags
										placeholder="请选择会员标签" class="input-width">
										<el-option :label="item['label_name']" :value="item['label_id']"
											v-for="(item, index) in labelSelectData" :key="index" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-tab-pane>

				<el-tab-pane label="客户六要素" name="sixElements" v-if="pageName != '客户资源列表'">
					<!-- 客户六要素表单内容 -->
					<el-form :model="formData" label-width="120px">

<!-- 						<el-row :gutter="20">
							<el-col :span="12">

								<el-form-item label="需求购买力" prop="purchase_power">
									<el-select class="input-width" v-model="formData.purchase_power" clearable
										placeholder="请选择需求购买力">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in purchase_powerList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">

								<el-form-item label="认知理念" prop="concept_awareness">
									<el-select class="input-width" v-model="formData.concept_awareness" clearable
										placeholder="请选择认知理念">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in concept_awarenessList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>

							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="可选上课时间" prop="preferred_class_time" class="input-width">
									<el-date-picker class="flex-1 !flex" v-model="formData.preferred_class_time"
										clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
										placeholder="可选上课时间">
									</el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">

								<el-form-item label="距离" prop="distance_tow">
									<el-input v-model="formData.distance_tow" clearable placeholder="请填写距离"
										class="input-width" />
								</el-form-item>
							</el-col>
						</el-row> -->
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="沟通备注" prop="communication">
									<el-input v-model="formData.communication" type="textarea" rows="4" clearable
										placeholder="请填写沟通备注" class="input-width" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="承诺到访时间" prop="promised_visit_time" class="input-width">
									<el-date-picker class="flex-1 !flex" v-model="formData.promised_visit_time"
										clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
										placeholder="请选择承诺到访时间">
									</el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="实际到访时间" class="input-width">
									<el-date-picker class="flex-1 !flex" v-model="formData.actual_visit_time" clearable
										type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请填写实际到访时间">
									</el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">

								<el-form-item label="电话后的意向程度" prop="call_intent">
									<el-select class="input-width" v-model="formData.call_intent" clearable
										placeholder="请选择电话后的意向程度">
										<el-option label="请选择" value=""></el-option>
										<el-option v-for="(item, index) in call_intentList" :key="index"
											:label="item.name" :value="item.value" />
									</el-select>
								</el-form-item>

							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="一访情况">
									<el-input v-model="formData.first_visit_status" type="textarea" rows="4" clearable
										placeholder="请填写一访情况" class="input-width" />
								</el-form-item>
							</el-col>
							<el-col :span="12">

								<el-form-item label="二访情况">
									<el-input v-model="formData.second_visit_status" type="textarea" rows="4" clearable
										placeholder="请填写二访情况" class="input-width" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="是否关单" prop="is_closed">
							<el-select class="input-width" v-model="formData.is_closed" clearable placeholder="请选择是否关单" disabled >
								<el-option label="请选择" value=""></el-option>
								<el-option v-for="(item, index) in is_closedList" :key="index" :label="item.name"
									:value="Number(item.value)" />
							</el-select>
						</el-form-item>
					</el-form>
				</el-tab-pane>
			</el-tabs>
		</div>


		<!-- Footer -->
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="showDialog = false">{{ t('cancel') }}</el-button>
				<el-button type="primary" :loading="loading" @click="confirm(formRef)">
					{{ t('confirm') }}
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ref, reactive, computed, watch } from 'vue'
	import { useDictionary } from '@/app/api/dict'
	import { t } from '@/lang'
	import type { FormInstance } from 'element-plus'
	import { getMemberLabelAll } from '@/app/api/member'
	import {
		addCustomerResources,
		editCustomerResources,
		getCustomerResourcesInfo,
		getWithPersonnelList,
		getWithCampusList,
	} from '@/app/api/customer_resources'
	import {
		addSixSpeed,
		editSixSpeed,
		getSixSpeedInfo,
		getWithCustomerResourcesList,
	} from '@/app/api/six_speed'
	import { useRouter, useRoute } from 'vue-router'
	const route = useRoute()
	const pageName = route.meta.title;
	
	const activeTab = ref('base')
	let showDialog = ref(false)
	const loading = ref(false)

	/**
	 * 表单数据
	 */
	const initialFormData = {
		id: '',
		source: '',
		source_channel: '',
		name: '',
		age: '',
		gender: '',
		phone_number: '',
		demand: '',
		purchasing_power: '',
		cognitive_idea: '',
		optional_class_time: '',
		distance: '',
		decision_maker: '',
		initial_intent: '',
		campus: '',
		status: '',
		member_label: '',

		purchase_power: '',
		concept_awareness: '',
		preferred_class_time: '',
		distance_tow: '',
		communication: '',
		promised_visit_time: '',
		actual_visit_time: '',
		call_intent: '',
		first_visit_status: '',
		second_visit_status: '',
		is_closed: '',
	}


	const labelSelectData : any = ref(null)
	// 获取全部标签
	const getMemberLabelAllFn = async () => {
		labelSelectData.value = await (await getMemberLabelAll()).data
	}
	getMemberLabelAllFn()

	const formData : Record<string, any> = reactive({ ...initialFormData })

	const formRef = ref<FormInstance>()

	// 表单验证规则
	const formRules = computed(() => {
		return {
			source: [
				{ required: true, message: t('sourcePlaceholder'), trigger: 'blur' },
			],
			source_channel: [
				{
					required: true,
					message: t('sourceChannelPlaceholder'),
					trigger: 'blur',
				},
			],
			name: [{ required: true, message: t('namePlaceholder'), trigger: 'blur' }],
			age: [
				{ required: true, message: t('agePlaceholder'), trigger: 'blur' },
				{
					validator: (rule : any, value : number, callback : any) => {
						if (value === undefined || value === null || value === '') {
							callback()
						} else if (value < 3 || value > 80) {
							callback(new Error(t('generateBetween')))
						} else {
							callback()
						}
					},
					trigger: 'blur',
				},
			],
			gender: [
				{ required: true, message: t('genderPlaceholder'), trigger: 'blur' },
			],
			phone_number: [
				{ required: true, message: t('phoneNumberPlaceholder'), trigger: 'blur' },
			],
			demand: [
				{ required: true, message: t('demandPlaceholder'), trigger: 'blur' },
			],
			purchasing_power: [
				{
					required: true,
					message: t('purchasingPowerPlaceholder'),
					trigger: 'blur',
				},
			],
			cognitive_idea: [
				{
					required: true,
					message: t('cognitiveIdeaPlaceholder'),
					trigger: 'blur',
				},
			]
		}
	})

	const emit = defineEmits(['complete'])

	/**
	 * 确认
	 * @param formEl
	 */
	const confirm = async (formEl : FormInstance | undefined) => {
		console.log(123123)
		if (loading.value || !formEl) return
		let save = formData.id ? editCustomerResources : addCustomerResources

		await formEl.validate(async (valid) => {
			if (valid) {
				loading.value = true

				let data = formData

				save(data)
					.then((res) => {
						loading.value = false
						showDialog.value = false
						emit('complete')
					})
					.catch((err) => {
						loading.value = false
					})
			}
		})
	}

	// 获取字典数据
	let sourceList = ref([])
	const sourceDictList = async () => {
		sourceList.value = await (await useDictionary('source')).data.dictionary
	}
	sourceDictList()
	watch(
		() => sourceList.value,
		() => {
			formData.source = sourceList.value[0].value
		}
	)
	let source_channelList = ref([])
	const source_channelDictList = async () => {
		source_channelList.value = await (
			await useDictionary('SourceChannel')
		).data.dictionary
	}
	source_channelDictList()
	watch(
		() => source_channelList.value,
		() => {
			formData.source_channel = source_channelList.value[0].value
		}
	)
	let genderList = ref([])
	const genderDictList = async () => {
		genderList.value = await (await useDictionary('zy_sex')).data.dictionary
	}
	genderDictList()
	watch(
		() => genderList.value,
		() => {
			formData.gender = genderList.value[0].value
		}
	)
	let purchasing_powerList = ref([])
	const purchasing_powerDictList = async () => {
		purchasing_powerList.value = await (
			await useDictionary('customer_purchasing_power')
		).data.dictionary
	}
	purchasing_powerDictList()
	watch(
		() => purchasing_powerList.value,
		() => {
			formData.purchasing_power = purchasing_powerList.value[0].value
		}
	)
	let cognitive_ideaList = ref([])
	const cognitive_ideaDictList = async () => {
		cognitive_ideaList.value = await (
			await useDictionary('cognitive_concept')
		).data.dictionary
	}
	cognitive_ideaDictList()
	watch(
		() => cognitive_ideaList.value,
		() => {
			formData.cognitive_idea = cognitive_ideaList.value[0].value
		}
	)
	let initial_intentList = ref([])
	const initial_intentDictList = async () => {
		initial_intentList.value = await (
			await useDictionary('preliminarycustomerintention')
		).data.dictionary
	}
	initial_intentDictList()
	watch(
		() => initial_intentList.value,
		() => {
			formData.initial_intent = initial_intentList.value[0].value
		}
	)
	let statusList = ref([])
	const statusDictList = async () => {
		statusList.value = await (await useDictionary('kh_status')).data.dictionary
	}
	statusDictList()
	watch(
		() => statusList.value,
		() => {
			formData.status = statusList.value[0].value
		}
	)

	const consultantList = ref([] as any[])
	const setConsultantList = async () => {
		consultantList.value = await (await getWithPersonnelList({})).data
	}
	setConsultantList()
	const campusList = ref([] as any[])
	const setCampusList = async () => {
		campusList.value = await (await getWithCampusList({})).data
	}
	setCampusList()

	// 获取字典数据
	let purchase_powerList = ref([])
	const purchase_powerDictList = async () => {
		purchase_powerList.value = await (
			await useDictionary('customer_purchasing_power')
		).data.dictionary
	}
	purchase_powerDictList()
	watch(
		() => purchase_powerList.value,
		() => {
			formData.purchase_power = purchase_powerList.value[0].value
		}
	)

	let concept_awarenessList = ref([])
	const concept_awarenessDictList = async () => {
		concept_awarenessList.value = await (
			await useDictionary('cognitive_concept')
		).data.dictionary
	}
	concept_awarenessDictList()
	watch(
		() => concept_awarenessList.value,
		() => {
			formData.concept_awareness = concept_awarenessList.value[0].value
		}
	)
	let call_intentList = ref([])
	const call_intentDictList = async () => {
		call_intentList.value = await (
			await useDictionary('preliminarycustomerintention')
		).data.dictionary
	}
	call_intentDictList()
	watch(
		() => call_intentList.value,
		() => {
			formData.call_intent = call_intentList.value[0].value
		}
	)
	let is_closedList = ref([])
	const is_closedDictList = async () => {
		is_closedList.value = await (
			await useDictionary('global_true_or_false')
		).data.dictionary
	}
	is_closedDictList()
	watch(
		() => is_closedList.value,
		() => {
			formData.is_closed = is_closedList.value[0].value
		}
	)

	const staffIdList = ref([] as any[])
	const setStaffIdList = async () => {
		staffIdList.value = await (await getWithPersonnelList({})).data
	}
	setStaffIdList()
	const resourceIdList = ref([] as any[])
	const setResourceIdList = async () => {
		resourceIdList.value = await (await getWithCustomerResourcesList({})).data
	}
	setResourceIdList()
	const campus = ref('')
	
	const setFormData = async (row : any = null) => {
		Object.assign(formData, initialFormData)
		loading.value = true
		if (row) {
			const data = await (await getCustomerResourcesInfo(row.id)).data
			if (data)
				Object.keys(formData).forEach((key : string) => {
					if (data[key] != undefined) formData[key] = data[key]
				})
		}
		
		campus.value = formData.campus;
		loading.value = false
	}

	// 验证手机号格式
	const mobileVerify = (rule : any, value : any, callback : any) => {
		if (value && !/^1[3-9]\d{9}$/.test(value)) {
			callback(new Error(t('generateMobile')))
		} else {
			callback()
		}
	}

	// 验证身份证号
	const idCardVerify = (rule : any, value : any, callback : any) => {
		if (
			value &&
			!/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
				value
			)
		) {
			callback(new Error(t('generateIdCard')))
		} else {
			callback()
		}
	}

	// 验证邮箱号
	const emailVerify = (rule : any, value : any, callback : any) => {
		if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
			callback(new Error(t('generateEmail')))
		} else {
			callback()
		}
	}

	// 验证请输入整数
	const numberVerify = (rule : any, value : any, callback : any) => {
		if (!Number.isInteger(value)) {
			callback(new Error(t('generateNumber')))
		} else {
			callback()
		}
	}

	defineExpose({
		showDialog,
		setFormData,
	})
</script>

<style lang="scss" scoped></style>
<style lang="scss">
	.diy-dialog-wrap .el-form-item__label {
		height: auto !important;
	}
</style>