<template>
	<uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft" />
	<view>
		<view class="set-box bg-white">
			<uv-form :model="form" :rules="rules" ref="uForm" :errorType="errorType" labelWidth="80">
				<uv-form-item :label-position="labelPosition" label="客户名称:" required prop="name">
					<uv-input v-model="form.name" placeholder="请输入客户名称" />
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="联系手机:" prop="mobile">
					<uv-input v-model="form.mobile" placeholder="请输入联系手机" />
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="联系电话:">
					<uv-input v-model="form.telephone" placeholder="请输入联系电话" />
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="客户等级:" @click="levelShow">
					<uv-input v-model="levelName" disabled disabledColor="#ffffff" placeholder="选择等级">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="客户行业:" @click="industryShow">
					<uv-input v-model="industryName" disabled disabledColor="#ffffff" placeholder="选择行业">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="客户来源:" @click="sourceShow">
					<uv-input v-model="sourceName" disabled disabledColor="#ffffff" placeholder="选择来源">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="客户标签:" @click="tagsShow">
					<uv-input v-model="form.tags" disabled disabledColor="#ffffff" placeholder="添加标签">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="地址:" @click="openAddressSelect">
					<uv-input v-model="addressName" placeholder="请选择地址" disabled disabledColor="#ffffff">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="详细地址:">
					<uv-textarea v-model="form.detailAddress" placeholder="请输入详细地址"></uv-textarea>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="下次跟进 :" @click="createTimeShow">
					<uv-input v-model="nextTime" placeholder="选择跟进时间" disabled disabledColor="#ffffff">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="备注 :">
					<uv-textarea v-model="form.remark" placeholder="请输入备注"></uv-textarea>
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="QQ:">
					<uv-input v-model="form.qq" placeholder="请输入qq" />
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="微信:">
					<uv-input v-model="form.weixin" placeholder="请输入微信" />
				</uv-form-item>
				<uv-form-item :label-position="labelPosition" label="跟进状态:" @click="followStatusShow">
					<uv-input v-model="followStatusName" placeholder="请选择跟进状态" disabled disabledColor="#ffffff">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
			</uv-form>
			<!-- 底部浮动按钮 -->
			<view class="bottom-btn">
				<uv-button type="success" @click="submit" color="#09b4f1" :ripple="true">提交</uv-button>
			</view>
		</view>
		<!-- 添加标签弹窗 -->
		<uv-popup mode="bottom" round="38" ref="tagsShowRef" :closeable="true">
			<view class="text-center p-2">
				添加标签
			</view>
			<scroll-view scroll-y style="height:660rpx;width: 100%;">
				<view class="p-2">
					<view class="flex">
						<view style="width:70%;margin-right: 10rpx;">
							<uv-input class="mr-1" v-model="tagVal" />
						</view>
						<view style="width:30%">
							<uv-button type="primary" size="medium" color="#09b4f1" @click="addTag">添加</uv-button>
						</view>
					</view>
					<view class="flex mt-5 flex-wrap">
						<view class="mb-2 mr-1" v-for="(item,index) in tagList" :key="index">
							<uv-tags :text="item" plain closable @close="tagClick(index)" size="mini" type="error"></uv-tags>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="p-2">
				<uv-button type="primary" @click="chosen" color="#09b4f1" size="medium">确定</uv-button>
			</view>
		</uv-popup>
		<!-- 选择客户等级 -->
		<uv-action-sheet :actions="levelList" ref="levelShowRef" title="请选择客户等级" @select="levelClick"></uv-action-sheet>
		<!-- 选择客户行业 -->
		<uv-action-sheet :actions="industryList" ref="industryShowRef" title="请选择客户行业"
			@select="industryClick"></uv-action-sheet>
		<!-- 选择客户来源 -->
		<uv-action-sheet :actions="sourceList" ref="sourceShowRef" title="请选择客户来源" @select="sourceClick"></uv-action-sheet>

		<uv-action-sheet :actions="followStatusList" ref="followStatusShowRef" title="请选择跟进状态"
			@select="followStatusClick"></uv-action-sheet>
		<!-- 跟进时间选择 -->
		<uv-datetime-picker ref="datetimePicker" v-model="timeValue" mode="datetime"
			@confirm="createTimeChange"></uv-datetime-picker>
		<AddressSelect ref="addressSelectRef" @confirm="addressSelectConfirm" />
	</view>
</template>

<script setup>
	import {
		ref,
		unref,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		getDictData,
		customerCreate,
		getCustomer,
		customerUpdate
	} from '@/api/customer'
	import AddressSelect from '@/components/AddressSelect/index.vue'
	import {
		formatDateTime,
		prePage
	} from '@/utils/util'
	const title = ref('添加客户')
	const labelPosition = ref('left')
	const customerId = ref(0)
	const customerData = ref('')
	const timeValue = ref(Number(new Date()))
	const regionList = ref([])
	const levelName = ref('')
	const industryName = ref('')
	const sourceName = ref('')
	const addressName = ref('')
	const followStatusName = ref('')
	const tagVal = ref('')
	const tagList = ref([])
	const form = ref({
		name: ''
	})
	const type = ref('add')
	const errorType = ref('message')
	const levelList = ref([])
	const industryList = ref([])
	const sourceList = ref([])
	const followStatusList = ref([])
	const rules = ref({
		'name': {
			type: 'string',
			required: true,
			message: '请填写客户名称',
			trigger: ['blur', 'change']
		},
	})
	const address = ref({
		cityId: undefined,
		city: undefined,
		district: undefined,
		province: undefined,
	})
	const nextTime = ref('')


	onLoad((e) => {
		console.log('e:', e)
		getBaseConfig()
		if (e && e.type == "edit") {
			type.value = 'edit'
			customerId.value = e.id
			title.value = '编辑客户'

			getCustomerInfo()
		}
	})

	const levelShowRef = ref()
	const levelShow = () => {
		levelShowRef.value.open()
	}
	const industryShowRef = ref()
	const industryShow = () => {
		industryShowRef.value.open()
	}
	const sourceShowRef = ref()
	const sourceShow = () => {
		sourceShowRef.value.open()
	}
	const followStatusShowRef = ref()
	const followStatusShow = () => {
		followStatusShowRef.value.open()
	}
	const tagsShowRef = ref()
	const tagsShow = () => {
		tagsShowRef.value.open()
	}
	const datetimePicker = ref()
	const createTimeShow = () => {
		unref(datetimePicker).open()
	}

	/**
	 * 打开选择地址
	 */
	const addressSelectRef = ref()

	function openAddressSelect() {
		//const {address} = unref(address)
		let defaultAddressStr = ''
		if (address.value.province && address.value.city && address.value.district) {
			defaultAddressStr = `${ address.value.province }-${ address.value.city }-${ address.value.district }`
		}
		unref(addressSelectRef).open(defaultAddressStr)
	}

	/**
	 * 地址选择confirm
	 * @param areaList 地区 [省, 市, 区]
	 */
	function addressSelectConfirm(areaList) {
		if (areaList.length < 3) return
		address.value.province = areaList[0]?.name
		form.value.province = areaList[0]?.id
		address.value.city = areaList[1]?.name
		form.value.city = areaList[1]?.id
		address.value.district = areaList[2]?.name
		form.value.area = areaList[2]?.id

		addressName.value = `${ address.value.province }-${ address.value.city }-${ address.value.district }`
		form.value.addressStr = addressName.value
	}


	// 获取客户详情
	const getCustomerInfo = async () => {
		form.value = await getCustomer({
			id: customerId.value
		})
		nextTime.value = formatDateTime(form.value.nextTime)
		addressName.value = form.value.addressStr
	}


	// 确定
	const chosen = () => {
		form.value.tags = tagList.value.join(",")
		tagsShowRef.value.close()
	}
	// 选择客户等级
	const levelClick = (index) => {
		levelName.value = index.name
		form.value.level = index.value
	}
	// 选择客户行业
	const industryClick = (index) => {
		industryName.value = index.name
		form.value.industry = index.value
	}
	// 来源选择
	const sourceClick = (index) => {
		sourceName.value = index.name
		form.value.source = index.value
	}
	const followStatusClick = (index) => {
		followStatusName.value = index.name
		form.value.followStatus = index.value
	}
	// 选择时间
	const createTimeChange = (e) => {
		form.value.nextTime = e.value
		nextTime.value = formatDateTime(e.value)
	}


	// 添加标签
	const addTag = () => {
		if (tagVal.value) {
			tagList.value.push(tagVal.value)
		}
	}
	// 移除标签
	const tagClick = (index) => {
		tagList.value.splice(index, 1)
		form.tags = tagList.value.join(',')
	}

	// 获取配置字段
	const getBaseConfig = async () => {
		levelList.value = await getDictData({
			type: 'customer_level'
		})
		industryList.value = await getDictData({
			type: 'customer_industry'
		})
		sourceList.value = await getDictData({
			type: 'customer_source'
		})
		followStatusList.value = await getDictData({
			type: 'follow_status'
		})

		levelList.value.forEach((dict) => {
			if (dict.value === form.value.level + '') {
				levelName.value = dict.name
			}
		})
		industryList.value.forEach((dict) => {
			if (dict.value === form.value.industry + '') {
				industryName.value = dict.name
			}
		})
		sourceList.value.forEach((dict) => {
			if (dict.value === form.value.source + '') {
				sourceName.value = dict.name
			}
		})
		followStatusList.value.forEach((dict) => {
			if (dict.value === form.value.followStatus + '') {
				followStatusName.value = dict.name
			}
		})

	}


	// 修确认提交
	const uForm = ref()
	const submit = () => {
		uForm.value.validate().then(res => {
			onSubmit()
		}).catch(errors => {
			uni.showToast({
				icon: 'error',
				title: '校验失败'
			})
		})
	}
	// 提交
	const onSubmit = async () => {
		if (type.value == 'add') {
			await customerCreate(form.value)
			if (prePage().route == 'pages/customer/index') {
				prePage().$vm.isRefresh = true
			}
			uni.navigateBack()
		} else {
			await customerUpdate(form.value)
			uni.navigateBack()
		}

	}
</script>

<style lang="scss" scoped>
	.set-box {
		padding: 0rpx 22rpx 250rpx;

		.cif-title {
			font-size: 30rpx;
			font-weight: 700;
			padding: 22rpx 0;
		}

	}


	.bottom-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 25rpx 30rpx 45rpx;
		background-color: #fff;
		z-index: 100;
	}
</style>