<script setup lang="ts">
	import { onMounted, ref } from 'vue';
	import { formatDate } from '../../utils/date';
	import { getAction } from '../../common/http';
	import { showToast } from 'vant';

	const craftList = ref([] as any[])
	const otherList = ref([] as any[])
	const hasTex = ref('' as any)
	const nameList = ref([] as any[])
	onMounted(() => {
		uni.getStorage({
			key: 'info',
			success(res) {
				let data = JSON.parse(res.data)
				form.value.customOrder.makeUser = data.userName
				form.value.customOrder.belongTo = data.userName
			},
			fail: (err : any) => {
				console.log(err);
			}
		})
		getAction('/fabric/craft/info').then((res : any) => {
			if (res.code === 200) {
				craftList.value = res.data.map((l : any) => ({ value: l.name, text: l.name }))
			}
		})
		getAction('/fabric/info/all').then((res : any) => {
			if (res.code === 200) {
				res.data.forEach((l : any) => {
					let itemMl = mlList.value.find(m => m.text === l.commodity)
					if (itemMl) {
						let itemMm = itemMl.children.find(m => m.value === l.momme)
						if (itemMm) {
							itemMm.children.push({ text: l.width + 'cm', value: l.width })
						} else {
							itemMl.children.push({
								text: l.momme + 'mm',
								value: l.momme,
								children: [{ text: l.width + 'cm', value: l.width }]
							})
						}
					} else {
						mlList.value.push({
							text: l.commodity,
							value: l.commodity,
							children: [{ text: l.momme + 'mm', value: l.momme, children: [{ text: l.width + 'cm', value: l.width }] }]
						})
					}
				})
			}
		})
		getAction('/v1/user/getNames').then((res : any) => {
			if (res.code === 200) {
				nameList.value = res.data.map((l : any) => ({ value: l, text: l }))
			}
		})
		getAction('/extraOption').then((res : any) => {
			if (res.code === 200) {
				otherList.value = JSON.parse(res.data.payload)
			}
		})
	})

	const onClickLeft = () => {
		uni.navigateBack()
	}

	const onSubmit = () => {

	}

	const form = ref({ customOrder: { makeTime: formatDate(new Date()) }, orderItems: [{ fabric: [{}] }] } as any)
	const showPicker = ref(false)
	const typeData = ref()
	const popuList = ref([] as any[])
	const show = ref(false)
	const pickerList = ref([])//面料数据
	const pickerContainerList = ref([])
	const showPickerList = ref(false)
	const searchValue = ref('')//查询的值
	const searchIndex = ref(0)//查询到的数组
	const mlList = ref([])
	const indexData = ref()
	//选择框事件
	const choosePic = (type : any, index : any) => {
		showPicker.value = true
		typeData.value = type
		indexData.value = index
	}
	//选择框确认
	const pickerConfirm = (val : any) => {
		if (typeData.value === 'craft') {
			form.value.orderItems[indexData.value][typeData.value] = val.selectedValues[0]
		} else if (typeData.value === 'hasTex') {
			hasTex.value = val.selectedOptions[0].text
			form.value.customOrder[typeData.value] = val.selectedOptions[0].value
		} else {
			form.value.customOrder[typeData.value] = val.selectedValues[0]
		}
		showPickerCancel()
	}
	//取消
	const showPickerCancel = () => {
		showPicker.value = false
	}
	//弹窗开启事件
	const handleOpen = () => {
		if (typeData.value === 'craft') {
			popuList.value = craftList.value
		} else if (typeData.value === 'hasTex') {
			popuList.value = [{ value: 'true', text: '含税' }, { value: 'false', text: '不含税' }]
		} else if (typeData.value === 'belongTo') {
			popuList.value = nameList.value
		}
	}

	const chooseDate = (type : any) => {
		typeData.value = type
		show.value = true
	}
	//日期选择
	const onConfirmDate = (val : any) => {
		form.value.customOrder[typeData.value] = formatDate(val)
		show.value = false
	}

	//选择面料
	const selectChoose = (index : any, indexSecond : any) => {
		indexData.value = index
		typeData.value = indexSecond
		showPickerList.value = true
	}
	//面料开启
	const mlmcOpen = () => {
		pickerList.value = mlList.value
		pickerContainerList.value = pickerList.value
		searchValue.value = ''
	}
	//面料关闭
	const pickerCancel = () => {
		showPickerList.value = false
	}

	//搜索
	const selectedValue = ref()
	const getSeachList = () => {
		searchIndex.value = 0
		let reg = new RegExp(searchValue.value)
		let arr = []
		pickerList.value.forEach(l => {
			if (reg.test(l.text)) {
				arr.push(l)
			}
		})
		pickerContainerList.value = arr
	}
	//向上选择
	const upSearch = () => {
		if (searchIndex.value === 0 && pickerContainerList.value.length) {
			searchIndex.value = pickerContainerList.value.length - 1
			selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
		} else if (pickerContainerList.value.length) {
			searchIndex.value--
			selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
		} else {
			showToast('没有了！')
		}
	}
	//向下选择
	const downSearch = () => {
		if (pickerContainerList.value.length) {
			if (searchIndex.value === pickerContainerList.value.length) {
				searchIndex.value = 0
				selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
			} else {
				searchIndex.value++
				selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
			}
		} else {
			showToast('没有了！')
		}
	}
	//搜索框输入
	const timer = ref()
	const searchTo = () => {
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			getSeachList()
		}, 800)
	}
	const onConfirm = (val : any) => {
		form.value.orderItems[indexData.value].fabric[typeData.value].name = val.selectedValues[2] + '/' + val.selectedValues[0] + val.selectedValues[1]
		pickerCancel()
	}
	const activeIds = ref([1, 2]);
	const activeIndex = ref(0);
	const items = [
		{
			text: '浙江',
			children: [
				{ text: '杭州', id: 1 },
				{ text: '温州', id: 2 },
				{ text: '宁波', id: 3, },
			],
		},
		{
			text: '江苏',
			children: [
				{ text: '南京', id: 4 },
				{ text: '无锡', id: 5 },
				{ text: '徐州', id: 6 },
			],
		},
		{ text: '福建', },
	];
</script>

<template>
	<view class="flex">
		<van-nav-bar title="客户定做单" left-text="返回" left-arrow @click-left="onClickLeft" />
		<view class="content">
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field v-model="form.customOrder.customerName" name="客户名称" label="客户名称" colon class="bor"
						label-width="5em" readonly :rules="[{ required: true, message: '请填写' }]"
						@click="chooseDate()" />
					<van-field v-model="form.customOrder.makeTime" name="做单日期" label="做单日期" colon label-width="5em"
						readonly :rules="[{ required: true, message: '请填写' }]" class="bor-n" />
					<van-field v-model="form.customOrder.belongTo" name="订单归属" label="订单归属" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor"
						@click="choosePic('belongTo')" />
					<van-field v-model="form.customOrder.makeUser" name="做单人员" label="做单人员" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor-n" />
					<van-field v-model="form.customOrder.sd" name="谁定" label="谁定" colon
						:rules="[{ required: true, message: '请填写' }]" label-width="5em" />
					<van-field v-model="hasTex" name="是否含税" label="是否含税" colon
						:rules="[{ required: true, message: '请填写' }]" label-width="5em" readonly class="bor"
						@click="choosePic('hasTex')" />
					<view class="a-b">
						<van-button type="primary" @click="form.orderItems.push({})">面料添加</van-button>
					</view>

					<view class="card" v-for="(item,index) in form.orderItems" :key="index">
						<view style="text-align: end;">
							<van-icon name="cross" @click="form.orderItems.splice(index,1)" />
						</view>
						<van-field v-model="item.color" name="颜色色号" label="颜色色号" colon
							:rules="[{ required: true, message: '请填写' }]" label-width="5em" />
						<van-field v-model="item.craft" name="工艺名称" label="工艺名称" colon
							:rules="[{ required: true, message: '请填写' }]" label-width="5em" readonly class="bor"
							@click="choosePic('craft',index)" />
						<view v-for="(itemSecond,indexSecond) in item.fabric" :key="index">
							<view class="a-c">
								<van-icon name="add" color="red" size="25" v-if="index===0"
									@click="item.fabric.push({})" />
								<van-icon name="clear" color="red" size="25" v-if="index!=0"
									@click="item.fabric.splice(index,1)" />
								<van-field v-model="itemSecond.name" name="面料名称" label="面料名称" colon readonly
									label-width="5em" @click="selectChoose(index,indexSecond)" class="bor" />
							</view>
							<van-field v-model="itemSecond.len" name="需求米数" label="需求米数" type="number" colon
								label-width="6.5em" />
							<van-field v-model="itemSecond.qty" name="需求匹数" label="需求匹数" colon label-width="6.5em"
								readonly />
						</view>
						<van-field v-model="item.price" name="订单单价" label="订单单价" colon
							:rules="[{ required: true, message: '请填写' }]" label-width="5em" />
						<van-field v-model="item.craftComment" name="工艺要求" label="工艺要求" colon
							:rules="[{ required: true, message: '请填写' }]" label-width="5em" readonly class="bor"
							@click="choosePic('craftComment')" />
						<van-field v-model="item.width" name="有效门幅" label="有效门幅" colon label-width="5em" />
						<van-field v-model="item.expecetWidth" name="全门幅" label="全门幅" colon label-width="5em" />
						<p>其他要求</p>
						<view v-for="(item,index) in otherList" :key="index">
							<van-field v-model="item.value" :name="item.name" :label="item.name" colon
								:rules="item.necessary?[{ required: true, message: '请填写' }]:[]" label-width="5em"
								readonly class="bor" @click="choosePic('')" />
						</view>
						<p style="text-align: center;margin: 10rpx 0;color: #02a7f0;" @click="form.fabrics.push({})">
							复制新增</p>
					</view>

					<van-field v-model="form.customOrder.totalLen" name="总米数" label="总米数" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor-n" />
					<van-field v-model="form.customOrder.totalQty" name="总匹数" label="总匹数" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor-n" />
					<van-field v-model="form.customOrder.currency" name="订单总额" label="订单总额" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor-n" />
					<van-field v-model="form.customOrder.finishDate" name="交货日期" label="交货日期" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor"
						@click="chooseDate('finishDate')" />
					<van-field v-model="form.customOrder.customerComment" name="客户备注" label="客户备注" colon
						label-width="5em" :rules="[{ required: true, message: '请填写' }]" readonly class="bor-n" />
					<van-field v-model="form.customOrder.interComment" name="内部备注" label="内部备注" colon label-width="5em"
						:rules="[{ required: true, message: '请填写' }]" readonly class="bor-n" />
				</van-cell-group>
				<view style="margin: 16px;">
					<van-button round block type="primary" native-type="submit">
						提交
					</van-button>
				</view>
			</van-form>
		</view>
	</view>

	<van-calendar v-model:show="show" @confirm="onConfirmDate" :min-date="new Date(2010, 0, 1)"
		:max-date="new Date(2050, 0, 31)" />

	<!--选择框-->
	<van-popup v-model:show="showPicker" round position="bottom" @open="handleOpen">
		<van-tree-select v-if="typeData==='craftComment'" v-model:active-id="activeIds"
			v-model:main-active-index="activeIndex" :items="items" />
		<van-picker show-toolbar :columns="popuList" @confirm="pickerConfirm" @cancel="showPickerCancel" ref="pickerRef"
			v-else />
	</van-popup>

	<!--    面料选择框-->
	<van-popup v-model:show="showPickerList" position="bottom" @open="mlmcOpen">
		<view class="select-model">
			<van-picker :columns="pickerContainerList" @cancel="pickerCancel" v-model="selectedValue"
				@confirm="onConfirm" />
			<view>
				<view class="top-select">
					<view class="confirm-select">
						<p>请选择品种</p>
					</view>
					<view class="search-box">
						<view>
							<van-search placeholder="请输入品种名字" v-model="searchValue" label="面料搜索：" background="#ffffff"
								@input="searchTo()" :clearable="false" />
						</view>
						<view class="flex-btn">
							<button class="search-btn" @click="upSearch()">↑</button>
							<button class="search-btn" @click="downSearch()">↓</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</van-popup>
</template>

<style lang="scss" scoped>
	.flex {
		display: flex;
		flex-direction: column;
		height: 100vh;
		width: 100vw;
		overflow-y: hidden;

		.van-nav-bar {
			width: 100%;
		}

		.content {
			flex: 1;
			padding: 0 10px;
			overflow-y: scroll;
		}
	}

	.card {
		border: 1rpx solid #d7d7d7;
		border-radius: 5rpx;
		padding: 10rpx;
	}

	.footer-button {
		margin: 20px;
		display: flex;
		justify-content: space-around;
	}

	::v-deep .van-field {
		font-size: 16px;
	}

	.a-b {
		margin: 10rpx;

		::v-deep .van-button--normal {
			padding: 5px 8px;
			height: 30px;
		}
	}

	.a-c {
		display: flex;
		align-items: center;

		::v-deep .van-button--normal {
			padding: 8rpx;
			height: 50rpx;
			width: 7em;
		}
	}

	.bor {
		::v-deep .van-field__control {
			border: 1px solid #d7d7d7;
		}
	}

	.bor-n {
		::v-deep .van-field__control {
			border: none;
		}
	}

	::v-deep .van-field__control {
		border-bottom: 1px solid #d7d7d7;
		text-align: center;
	}

	::v-deep .van-field__label {
		text-align: end;
	}

	/*面料选择搜索框*/
	.select-model {
		position: relative;
	}

	.confirm-select {
		width: 100%;
	}

	.confirm-select>p {
		text-align: center;
	}

	.confirm-select>button {
		border: none;
		background-color: #ffffff;
		color: #388aed;
		margin: 10px 30px 0 0;
	}

	.top-select {
		position: absolute;
		top: 30px;
		left: 0;
		right: 0;
		margin: auto;
		z-index: 999;
	}

	::v-deep .select-model .van-picker__toolbar {
		height: 66px;
		align-items: flex-start;
		/*justify-content: flex-end;*/
	}

	::v-deep .select-model .van-picker__cancel,
	.select-model .van-picker__confirm {
		height: 30px;
		padding: 10px 16px 0;
	}

	.search-btn {
		padding: 1px 8px;
		border: none;
		background-color: #388aed;
		color: #ffffff;
		margin-left: 5px;
		height: 30px;
		line-height: 25px;
	}

	.search-box {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		padding-top: 15px;
		padding-bottom: 5px;
		position: relative;
		background-color: #fff;
	}

	.van-search {
		background-color: #f7f7f8;
	}

	.ml-search-jump {
		padding: 3px 10px;
		background-color: #388aed;
		color: #ffffff;
		border: none;
		margin-left: 10px;
	}

	.flex-btn {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}
</style>