<template>
	<view class="page">
		
		<view class="pos-title" >
			<text>pos产品开通</text>
			<view class="btn" @click="addPos">添加POS终端</view>
		</view>
		
		<view v-for="(item, index) in posInfoList" :key="index" class="pos-list">
			<view class="pos-title">
				<text>pos终端【{{ index + 1 }}】</text>
				<view class="btn remove" @click="removePos(index)">删除终端</view>
			</view>
			
			<JeePayForm text="pos安装位置" >
				<!--  -->
				<jeeDataPicker :localdata="address" :code="codeback[index]"  @change="addressHandle($event, index)" paramType="arr" />
			</JeePayForm>
			
			<JeePayForm text="具体位置" v-model:value="item.terminalDetailAddress" />
			
			<JeePayForm text="小品名称" v-model:value="item.ticketName" />
			
			<JeePayForm text="终端数量" v-model:value="item.terminalCount" />
			
		</view>

	</view>
</template>

<script setup>

import { ref, reactive, toRaw } from 'vue'
import address from '@/components/applyJson/address.json' // 盛付通地址json
import JeePayForm from '@/components/applyComponents/JeePayForm.vue' // 通用左右结构布局
import jeeDataPicker from '@/components/applyComponents/dataPicker.vue' // 通用级联选择

// pos信息列表
let posInfoList = reactive([
	{
		terminalCityId: '', // pos位置
		terminalDetailAddress: '', // 具体位置
		ticketName: '', // 小票名称
		terminalCount: '', // 终端数量
	}
])

// 地址回显
let codeback = reactive([])

// pos信息合并
const merge = list => {
	posInfoList.length = 0
	posInfoList.push(...list)
	posInfoList.forEach((item, index) => {
		codeback[index] = item.terminalCityId[2]
	})
}

// 选择地址回调
const addressHandle = (e, index) => {
	posInfoList[index].terminalCityId = e.detail.value
	codeback[index] = e.detail.value[2]
}

// 新增POS
const addPos = () => {
	posInfoList.push({
		terminalCityId: '', // pos位置
		terminalDetailAddress: '', // 具体位置
		ticketName: '', // 小票名称
		terminalCount: '', // 终端数量
	})
}

// 删除终端
const removePos = index => {
	if (posInfoList.length == 1) return uni.showToast({
		title: '最后一项不可删除',
		icon: 'none'
	})
	posInfoList.splice(index, 1)
}

// 提供给父组件的数据
const getPosInfo = (isTempData) => {
	
	let num = 0 // pos数量不能超过五个
	
	// 先进行校验 在传给父元素
	if (!isTempData) {
		
		num =+posInfoList[i].terminalCount
		
		for (var i = 0; i < posInfoList.length; i++) {
			if (!posInfoList[i].terminalCityId || !posInfoList[i].terminalDetailAddress || !posInfoList[i].ticketName || !posInfoList[i].terminalCount) {
				uni.showToast({
					title: `第${i + 1}项pos信息填写不完整`,
					icon: 'none'
				})
				return false
			}
			
			if (num > 5) {
				uni.showToast({title: '所有终端产品数量不能超过5个', icon: 'none'})
				return false
			}
			
		}
	}
	
	return JSON.stringify(toRaw(posInfoList))
}

defineExpose({ getPosInfo, merge })

</script>

<style scoped lang="scss">
.page {
	padding: 30rpx;
	box-sizing: border-box;
}
.pos-title {
	display: flex;
	justify-content: space-between;
	margin: 30rpx 0;
}
.btn {
	border-radius: 10rpx;
	background: #3981FF;
	color: #fff;
	padding: 5rpx 15rpx;
}
.remove {
	background: #ff4d4f;
}

</style>