<template>
	<view class="page">
		<view class="box">
			<view>
				<uni-forms :model="category" :rules="rules" err-show-type="toast" validateTrigger="blur" ref="form"
					:border="true" label-position="top" label-width="350">
					<view class="block">
						<view class="border-top-0">
							<uni-forms-item ref="fileItem" label="图标">
								<my-upload-file ref="refFile" :images="category.images"></my-upload-file>
							</uni-forms-item>
						</view>
						<view class="">
							<uni-forms-item label="分类名称" required name="categoryName">
								<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="inputBorder"
									v-model="category.categoryName" placeholder="输入分类名称" />
							</uni-forms-item>
						</view>
						<template v-if="option.type==='edit'">
							<uni-forms-item label="排序" required name="sort">
								<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="inputBorder"
									v-model="category.sort" type="number" placeholder="排序越小越靠前" />
							</uni-forms-item>
						</template>
						<uni-forms-item label=""  name="categoryName">
							<view class="u-flex u-row-between u-col-center">
								<view class="label-title">开关</view>
								<view class="u-flex">
									<my-switch v-model="category.required"></my-switch>
								</view>
							</view>
						</uni-forms-item>
						<!-- <uni-forms-item>
							<template #label>
								<view class="u-flex u-row-between u-col-center">
									<view class="label-title">必选分类</view>
									<view class="u-flex">
										<my-switch v-model="category.required"></my-switch>
									</view>
								</view>
							</template>
							<view class="u-m-t-20">
								<uni-easyinput :disabled="!category.required" :placeholderStyle="placeholderStyle"
									:inputBorder="inputBorder" v-model="category.requiredNumber"
									:placeholder="category.required?'输入必选商品数量':'开启后必选一个以上商品才能下单'" />

							</view>
						</uni-forms-item> -->
						<!-- <uni-forms-item @tap="toTimer(category.timers,-1)">
							<template #label>
								<view class="u-flex u-row-between u-col-center">
									<view class="label-title">定时上下架</view>
									<view class="u-flex">
										<uni-icons type="right"></uni-icons>
									</view>
								</view>
							</template>
							<view class="u-m-t-20">
								<template v-if=" category.timers.length">
									<view class="u-m-b-20" v-for="(item,index) in category.timers" :key="index">
										{{returnTimers(item)}}
									</view>
								</template>
								<template v-else>
									<view>无</view>
								</template>

							</view>
						</uni-forms-item> -->

					</view>
					<view class="block" v-for="(item,index) in category.childrens" :key="index">
						<view class="border-top-0">
							<uni-forms-item label="子分类名称" required name="categoryName">
								<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="inputBorder"
									v-model="item.categoryName" placeholder="输入子分类名称" />
							</uni-forms-item>
						</view>
						<template v-if="option.type==='edit'">
							<uni-forms-item label="排序" required name="sort">
								<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="inputBorder"
									v-model="item.sort" type="number" placeholder="排序越小越靠前" />
							</uni-forms-item>
						</template>
						
						<uni-forms-item>
							<template #label>
								<view class="u-flex u-row-between u-col-center">
									<view class="label-title">必选分类</view>
									<view class="u-flex">
										<my-switch v-model="item.required"></my-switch>
									</view>
								</view>
							</template>
							<view class="u-m-t-20">
								<uni-easyinput :disabled="!item.required" :placeholderStyle="placeholderStyle"
									:inputBorder="inputBorder" v-model="item.requiredNumber"
									:placeholder="item.required?'输入必选商品数量':'开启后必选一个以上商品才能下单'" />

							</view>
						</uni-forms-item>
						<uni-forms-item @tap="toTimer(item.timers,index)">
							<template #label>
								<view class="u-flex u-row-between u-col-center">
									<view class="label-title">定时上下架</view>
									<view class="u-flex">
										<uni-icons type="right"></uni-icons>
									</view>
								</view>
							</template>
							<view class="u-m-t-20">
								<template v-if="item.timers.length">
									<view class="u-m-b-20" v-for="(item,index) in item.timers" :key="index">
										{{returnTimers(item)}}
									</view>
								</template>
								<template v-else>
									<view>无</view>
								</template>

							</view>
						</uni-forms-item>

					</view>

				</uni-forms>
			</view>
			<view class="u-flex block u-p-l-20 u-p-r-20 u-p-t-28 u-p-b-28" @click="addcategoryChildren">
				<view class="icon icon-add u-m-r-22 ">

				</view>
				<view class="color-main">添加子分类</view>
			</view>

			<view class="save-btn-box">
				<button class="save-btn" hover-class="btn-hover-class" @click="save">保存</button>
			</view>
		</view>
		<view class="bottom" ref="bottom"></view>
	</view>
</template>

<script setup>
	import tColorPicker from '@/components/t-color-picker/t-color-picker'
	import go from '@/commons/utils/go.js';
	import infoBox from '@/commons/utils/infoBox.js';
	import mySwitch from '@/components/my-components/my-switch.vue'
	import myUploadFile from '@/components/my-components/my-upload-file'
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app';
	import {
		onMounted,
		reactive,
		nextTick,
		ref,
		onBeforeMount
	} from 'vue';
	// 表单样式
	const placeholderStyle = ref('font-size:28rpx;')
	//表单边框
	const inputBorder = ref(false)
	const form = ref(null)
	const bottom = ref(null)
	//表单验证
	const rules = {
		categoryName: {
			rules: [{
				required: true,
				errorMessage: '输入分类名称'
			}]
		},
		sort: {
			rules: [{
				required: true,
				errorMessage: '输入排序'
			}]
		}
	}

	function toTimer(timer, index) {
		console.log(timer);
		uni.setStorageSync('timer', timer.map(v => {
			return {
				...v,
				cycleChecked: v.cycleChecked.map(v => v.value)
			}
		}))
		go.to('PAGES_CATEGORY_TIMER', {
			index: index
		})
	}

	function returnTimers(timers) {
		const {
			listingTime,
			offShelf,
			cycleChecked
		} = timers
		let len = cycleChecked.length
		if (len === 7) {
			return `每天 ${listingTime.value} - ${offShelf.value}`
		}
		let result = cycleChecked.reduce((prve, cur) => {
			return prve + cur.text.replace('星期', '周')
		}, '')
		return `${result} ${listingTime.value} - ${offShelf.value}`
	}
	//图片上传
	function FileUploadprogress() {

	}

	function FileUploadsuccess() {

	}

	function FileUploadail() {

	}

	function FileUploadselect(e) {
		// TEST
		// FormData.images.push(e)
	}


	function returnOptionsBasicData() {
		return {
			...categoryOptionsBasicData
		}
	}
	// 构造分类的基础数据
	const categoryBasicData = {
		categoryName: '',
		sort: 0,
		required: false,
		requiredNumber: '',
		timers: []
	}


	function onFieldChange(e) {
		console.log(e);
	}
	// 分类列表
	const category = reactive({
		...categoryBasicData,
		childrens: []
	})
	//添加子分类
	function addcategoryChildren() {
		category.childrens.push({
			...categoryBasicData
		})
		scrollPageBottom()
	}

	//页面滚动到最底部
	function scrollPageBottom() {
		nextTick(() => {
			uni.pageScrollTo({
				duration: 100, // 过渡时间
				scrollTop: 100000, // 滚动的实际距离
			})
		})
	}
	//设置表单验证规则
	function setFormRules() {
		form.value.setRules(rules)
	}
	const formRefs = ref([]);
	//绑定表单元素
	function setFormRef(index) {
		formRefs.value[index] = null;
		return (el) => {
			if (el) {
				formRefs.value[index] = el;
			}
		};
	}
	// 绑定option input元素
	const refFormInput = ref([])

	function setFormInputRef(index, index1) {
		const newIndex = index * 10000 + index1
		return (el) => {
			if (el) {
				if (!refFormInput.value[newIndex]) {
					refFormInput.value[newIndex] = el;
				}
			}
		}
	}
	// 当表单内容输入变化根据配置的rules进行验证
	function inpuChange(index, index1) {
		const newIndex = index * 10000 + index1
		console.log(refFormInput.value[newIndex]);
		refFormInput.value[newIndex].onFieldChange()
	}



	function triggerEvent(emitName, data) {
		if (emitName) {
			uni.$emit(emitName, data)
		}
	}
	const option = reactive({
		type: ''
	})

	function isEmpty(obj) {
		return obj && JSON.stringify(obj) !== '{}'
	}

	/**
	 *  监听定时器保存,拿到数据
	 * @param {Boolean} open //控制开启或关闭监听
	 */
	function watchTimerSave(open = true) {
		if (open) {
			uni.$on('timerSave', function(res) {
				const {
					index,
					data
				} = res
				console.log('timerSave get');
				console.log(res);
				if (index == -1) {
					category.timers = data
				} else {
					category.childrens[index].timers = data
				}
			})
		} else {
			uni.$off('timerSave', function(data) {
				console.log('timerSave remove');
			})
		}

	}
	watchTimerSave()

	onLoad(params => {
		// const arr = uni.getStorageSync('guige')
		// if (arr.length) {
		// 	category.list = arr
		// 	console.log(arr);
		// }
		if (isEmpty(params)) {
			option.type = params.type ? params.type : 'add'
		}
		console.log(option.type);
		uni.setNavigationBarTitle({
			title: option.type === 'add' ? '添加分类' : '编辑分类'
		})
	})

	function emitcategorySave() {
		// emitcategorySave  触发规格保存事件将数据给到添加商品页面
		// guigeEdit  触发规格保存事件将数据给到添加规格页面
		uni.removeStorageSync('guige')
		triggerEvent(emitName, category.list)
	}
	

	function returnValidateResult(obj) {
		const validateFuncObj = {
			categoryName: (value) => {
				return {
					pass:value.length >= 1,
					errMeessage:'请输入分类名称'
				}
			},
			sort: (value) => {
				return {
					pass:value!=='',
					errMeessage:'请输入排序'
				}
			}
		}
		function validateFunc(key, value) {
			if (validateFuncObj.hasOwnProperty(key)) {
				const func = validateFuncObj[key]
				return func(value)
			}
			return {pass:true}
		}
		let resultArr = []
		for (let key in obj) {
			resultArr.push(validateFunc(key, category[key]))
		}
		resultArr=resultArr.filter(v => !v.pass)
		return resultArr
	}
	async function save() {
		let isAllPassForm = 0
		const formRules = {}
		const result=[]
		result.push(...returnValidateResult(category))
		for(let obj of  category.childrens){
			const res = returnValidateResult(obj)
			result.push(...res)
		}
		if(result.length){
			return infoBox.showToast(result[0].errMeessage)
		}
		go.back()
		// const res = await form.value.validate().then(res => {
		// 	go.back()
		// })

	}
</script>
<style scoped>
	page {
		background: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	$icon-size: 34rpx;
	$icon-line-width: 20rpx;
	$icon-line-height: 4rpx;

	.page {
		background: #F9F9F9;
		padding: 30rpx;
		padding-bottom: 200rpx;
	}

	.my-switch {
		transform: scale(0.7);
	}

	::v-deep .uni-forms-item__error {
		display: none !important;
	}

	::v-deep .option .uni-forms-item {
		padding: 0;
		min-height: inherit;
		background-color: transparent;
		border-top: none;
	}

	.icon {
		width: $icon-size;
		height: $icon-size;
		position: relative;
		border-radius: 50%;

		&:before,
		&::after {
			position: absolute;
			display: block;
			content: '';
			background-color: #fff;
		}
	}

	.icon-add {
		background-color: $my-main-color;

		&::before {
			width: $icon-line-height;
			height: $icon-line-width;
			top: calc(($icon-size /2) - ($icon-line-width / 2));
			left: calc(($icon-size /2) - ($icon-line-height / 2));
		}

		&::after {
			width: $icon-line-width;
			height: 4rpx;
			top: calc(($icon-size /2) - ($icon-line-height / 2));
			left: calc(($icon-size /2) - ($icon-line-width / 2));
		}
	}

	.icon-reduce {
		background-color: $my-red-color;

		&::after {
			width: $icon-line-width;
			height: $icon-line-height;
			top: calc(($icon-size /2) - ($icon-line-height / 2));
			left: calc(($icon-size /2) - ($icon-line-width / 2));
		}
	}

	.label-title {
		font-size: 28rpx;
		font-weight: bold;
		font-family: Source Han Sans CN, Source Han Sans CN;
	}

	.lh40 {
		line-height: 40rpx;
	}

	.box {
		font-size: 28rpx;
		.block {
			background: #FFFFFF;
			border-radius: 18rpx 18rpx 18rpx 18rpx;
			padding: 12rpx 24rpx;
			margin-bottom: 32rpx;
		}
	}

	.save-btn-box {
		position: fixed;
		left: 30rpx;
		right: 30rpx;
		bottom: 60rpx;

	}

	::v-deep.uni-forms-item {
		align-items: inherit;
	}

	::v-deep .uni-forms-item .uni-forms-item__label {
		text-indent: 0;
		font-size: 28rpx !important;
		font-weight: bold;
		color: #333;
	}

	::v-deep .border-top-0 .uni-forms-item.is-direction-top {
		border-color: transparent !important;
	}

	.save-btn {
		background-color: $my-main-color;
		color: #fff;
		border-radius: 12rpx;
		font-size: 28rpx;
	}

	.btn-hover-class {
		opacity: .6;
	}

	.zuofa {
		padding: 28rpx 0;
		background: #F9F9F9;
		padding-left: 42rpx;
		border-radius: 14rpx 14rpx 14rpx 14rpx;
	}

	::v-deep .uni-input-placeholder {
		font-size: 28rpx;
	}

	.option {
		padding: 26rpx 30rpx 24rpx 24rpx;
		background: #F9F9F9;
	}

	.option-item {
		margin-bottom: 34rpx;
	}
</style>