<template>
	<view style="overflow: hidden;overflow-y: scroll; height: 100vh;">
		<navBar isRightButton :title="data.navBar.title" :bgColor="data.navBar.bgColor" @right-click="onRightClick">
		</navBar>
		<!-- tabbar -->
		<view class="tab-bar">
			<view class="tab-item" :class="{ blue: billData.selectId == item.selectId }" v-for="item in classifyTabBar"
				:key="item.selectId" @click="billData.selectId = Number(item.selectId)">
				{{ item.type }}
			</view>
		</view>
		<!-- 账单信息容器 -->
		<view class="add-bill-container">
			<!-- 随机骰子 -->
			<view class="random-dice">
				<image class="random-dice-image" src="/static/image/common/random-dice.png"></image>
			</view>
			<!-- 头像 -->
			<view class="avatar-box">
				<image class="avatar-image" src="/static/image/bill/add-bill/add-avatar.png"></image>
			</view>
			<!-- 主要信息 -->
			<view class="main-info flex-align-center flex-column">
				<!-- 名称 -->
				<view class="name info-item-input">
					<!-- 隐藏的text用于测量宽度 -->
					<text class="text-measure">{{ billData.name }}</text>

					<input class="text-input" type="text" v-model="billData.name" />
					<image class="edit-image" src="/static/image/bill/add-bill/edit.png"></image>
				</view>
				<!-- 金额 -->
				<view class=" money info-item-input" style="height: 77rpx;">
					<!-- 隐藏的text用于测量宽度 -->
					<text class="text-measure font-w500" style="font-size: 64rpx;">{{ billData.money }}</text>

					<input class="text-input font-w500" style="font-size: 64rpx;" type="digit"
						v-model="billData.money" />
					<image class="edit-image" src="/static/image/bill/add-bill/edit.png"></image>
				</view>
				<!-- 订单状态 -->
				<view class="order-status-info" :class="{ isRefund: billData.merchantOption.refund }">
					{{ billData.orderStatus }}
				</view>
			</view>
			<!-- 详情信息列表 -->
			<view class="detail-info-container">
				<view class="info-item-box" v-for="item in billData.itemInfoList" :key="item.type">
					<view class="item-label">
						{{ item.label }}
					</view>
					<view class="info-item-input" @click="onClickItemInfo(item)">
						<!-- 隐藏的text用于测量宽度 -->
						<text class="text-measure"
							:class="{ visibility: item.type == 'time' || item.type == 'select' }">{{ item.value
							}}</text>

						<input v-if="item.type == 'text' || item.type == 'digit' || item.type == 'number'"
							:style="{ color: item.textColor ? item.textColor : '#1a1a1a' }" class="text-input"
							:type="item.type" :focus="item.focus" v-model="item.value" @click.stop />
					</view>
					<image class="edit-image" src="/static/image/bill/add-bill/edit.png" @click="onClickItemInfo(item)">
					</image>
				</view>
			</view>
		</view>
		<!-- switch选项列表 -->
		<view class="switch-option-container">
			<template v-for="option in data.switchOptions" :key="option.id">
				<view v-if="option.isShow()" class="border-bottom"
					:class="{ 'no-border-bottom': billData.merchantOption[option.key] && option.isShow() }">
					<view class="switch-option">
						<view class="switch-option-text">{{ option.name }}</view>
						<switch v-if="option.isSwitch" color="#1676FE" :checked="billData.merchantOption[option.key]"
							style="transform:scale(0.8)" @change="(e) => onSwitchChange(e, option)" />
					</view>
					<!-- 服务详情 -->
					<view class="service-detail"
						v-if="option.key == 'serviceDetail' && billData.merchantOption.serviceDetail && option.isShow()">
						<image class="service-detail-image"
							src="/static/image/bill/add-bill/service-detail-image.png" />
						<view class="flex-1 over-hidden">
							<view class="service-detail-info info-item-input">
								<!-- 隐藏的text用于测量宽度 -->
								<text class="text-measure" style="font-size: 22rpx;">{{
									billData.merchantOption.serverDetailInfo.text }}</text>

								<input class="text-input" maxlength="20" style="font-size: 22rpx;" type="text"
									v-model="billData.merchantOption.serverDetailInfo.text" />
								<image class="edit-image" src="/static/image/bill/add-bill/edit.png"></image>
							</view>
						</view>
						<uni-data-select class="select" style="flex: none;width: 80px;"
							v-model="billData.merchantOption.serverDetailInfo.rightText"
							:localdata="serverDetailRightTextList" @change="changeTips"
							:clear="false"></uni-data-select>
						<image class="right-icon" src="/static/image/common/right-grey.png" />
					</view>
					<!-- 推荐服务 -->
					<view class="service-detail recommend-service "
						v-if="option.key == 'recommendService' && billData.merchantOption.recommendService && option.isShow()">
						<view class="flex-1 over-hidden">
							<view class="service-detail-info info-item-input">
								<!-- 隐藏的text用于测量宽度 -->
								<text class="text-measure" style="font-size: 22rpx;">{{
									billData.merchantOption.recommendServiceInfo.text }}</text>

								<input class="text-input" maxlength="20" style="font-size: 22rpx;" type="text"
									v-model="billData.merchantOption.recommendServiceInfo.text" />
								<image class="edit-image" src="/static/image/bill/add-bill/edit.png"></image>
							</view>
						</view>
						<text class="right-text">去看看</text>
						<image class="right-icon" src="/static/image/common/right-grey.png" />
					</view>
					<!-- 服务推荐 -->
					<view class="service-detail service-recommend "
						v-if="option.key == 'serviceRecommend' && billData.merchantOption.serviceRecommend && option.isShow()">
						<view class="flex-1 over-hidden">
							<view class="service-detail-info info-item-input">
								<!-- 隐藏的text用于测量宽度 -->
								<text class="text-measure" style="font-size: 22rpx;">{{
									billData.merchantOption.serviceRecommendInfo.text }}</text>

								<input class="text-input" maxlength="20" style="font-size: 22rpx;" type="text"
									v-model="billData.merchantOption.serviceRecommendInfo.text" />
								<image class="edit-image" src="/static/image/bill/add-bill/edit.png"></image>
							</view>
						</view>
						<image class="right-icon" src="/static/image/common/right-grey.png" />
					</view>
				</view>
			</template>

		</view>
		<!-- 底部icon配置选项列表 -->
		<view class="bill-bottom-icon-options">
			<view class="item-option-box" v-for="option in billBottomIconList" :key="option.id">
				<view class="item-box" :class="{ 'active-item-box': billData.bottomIcons.includes(option.id) }"
					@click="onBottomIconClick(option)">
					<image class="item-icon"
						:src="`/static/image/bill/${billData.bottomIcons.includes(option.id) ? 'white-icon' : 'blue-icon'}/${option.icon}.png`">
					</image>
					<text class="item-text">{{ option.name }}</text>
				</view>
			</view>
		</view>
	</view>

	<!-- 底部弹出层 -->
	<uni-popup ref="timepopup" type="bottom">
		<!-- 时间选择器 -->
		<view v-if="selectItemInfo.type == 'time'" class="timeBox">
			<view class="titleBox">
				<view class="title" @click="closeTimePicker">
					取消
				</view>
				<view class="btn" @click="settmes">
					确定
				</view>
			</view>
			<DateTimePicker :defaultDate="datePickerData.selectDate" :minDate="datePickerData.startDate"
				:maxDate="datePickerData.endDate" :mode="4" @onChange="onChangeStartDate" />
		</view>
		<!-- 账单分类 -->
		<view v-else class="bill-classify-box">
			<view class="title-box">
				<view class="title">
					账单分类
				</view>
				<view class="btn" @click="closeTimePicker">
					<image class="close-image" src="/static/image/common/close.png"></image>
				</view>
			</view>
			<view class="bill-classify-content">
				<view class="bill-classify-item" v-for="item in billClassifyOptions" :key="item.id"
					@click="data.currentClassifyId = item.id">
					<view class="bill-classify-item-text" :class="{ 'active-item': data.currentClassifyId == item.id }">
						{{ item.name }}
					</view>
				</view>
			</view>
			<view class="confirm-btn" @click="confirmClassify">
				确定
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
import navBar from '@/components/nav-bar/nav-bar.vue'
import addBillJson from './add-bill.json'
import DateTimePicker from '@/components/dengrq-datetime-picker/dateTimePicker/index.vue';
import { stringUtil } from '@/utils/common.js';

import {
	reactive,
	toRefs,
	ref,
	onMounted,
	watch,
	nextTick
} from 'vue'
import {
	onShow,
} from '@dcloudio/uni-app'

// 时间选择器
const timepopup = ref(null)

// 分类tabBar
const classifyTabBar = ref(addBillJson.classifyTabBar)

// 账单分类选项
const billClassifyOptions = ref(addBillJson.billClassify)

// 底部icon配置选项列表
const billBottomIconList = ref(addBillJson.billBottomIconList)

// 服务详情右侧选项
const serverDetailRightTextList = [
	{
		"value": 0,
		"text": "进入小程序"
	},
	{
		"value": 1,
		"text": "查看详情"
	}
]
// switch选项
const switchOptions = [
	{
		"id": 1,
		"name": "服务详情",
		"isSwitch": true,
		isShow: () => {
			const showTypeIds = [3, 4, 10]
			return showTypeIds.includes(billData.value.selectId)
		},
		key: 'serviceDetail',
	},
	{
		"id": 2,
		"name": "推荐服务",
		"isSwitch": true,
		isShow: () => {
			const showTypeIds = [4]
			return showTypeIds.includes(billData.value.selectId)
		},
		key: 'recommendService',
	},
	{
		"id": 3,
		"name": "服务推荐",
		"isSwitch": true,
		isShow: () => {
			const showTypeIds = [6, 7]
			return showTypeIds.includes(billData.value.selectId)
		},
		key: 'serviceRecommend',
	},
	{
		"id": 4,
		"name": "退款",
		"isSwitch": true,
		isShow: () => {
			const showTypeIds = [12, 13]
			return showTypeIds.includes(billData.value.selectId)
		},
		key: 'refund',
		change: (value) => {
			if (billData.value.selectId == 12 || billData.value.selectId == 13) {
				if (value) {
					billData.value.orderStatus = "已全额退款"
				} else {
					billData.value.orderStatus = "交易成功"
				}
			}
		}
	},
	{
		"id": 5,
		"name": "支付奖励",
		"isSwitch": true,
		isShow: () => {
			const showTypeIds = [1, 3, 4, 12, 13]
			return showTypeIds.includes(billData.value.selectId)
		},
		key: 'payReward',
	},
	{
		"id": 6,
		"name": "计入收支",
		"isSwitch": true,
		isShow: () => {
			const showTypeIds = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13]
			return showTypeIds.includes(billData.value.selectId)
		},
		key: 'countInAndOut',
	},

]

//获取全部字段的key值
let allFieldsList = ref([])
const keySet = new Set()
classifyTabBar.value.forEach(item => {
	if (item.itemInfoList) {
		item.itemInfoList.forEach(info => {
			if (info.key && !keySet.has(info.key)) {
				keySet.add(info.key)
				allFieldsList.value.push({
					key: info.key,
					value: info.value ? info.value : ""
				})
			}
		})
	}
})

const data = reactive({
	navBar: {
		title: '新增账单',
		bgColor: '#F5F5F5',
	},
	selectItemInfo: {
		type: '',
		value: '',
		label: '',
		id: ''
	},
	currentClassifyId: 0,
	//当前底部字段选择
	currentBottomIcons: [],
	// 时间选择器
	datePickerData: {
		selectDate: "",
		startDate: "",
		endDate: "",
	},
	// 账单数据
	billData: {
		id: "",
		selectId: -1,
		name: '',
		money: "",
		orderStatus: '交易成功',
		itemInfoList: classifyTabBar.value[0].itemInfoList,
		bottomIcons: [0, 1, 2, 3],
		merchantOption: {
			serverDetail: false,
			serverDetailInfo: {
				imgUrl: '',
				rightText: 0,
				text: '收钱吧'
			},
			recommendService: false,
			recommendServiceInfo: {
				text: '你有一个免费取现机会'
			},
			serviceRecommend: false,
			serviceRecommendInfo: {
				text: '恭喜你有6元转账保障福利待领取！'
			},
			refund: false,
			countInAndOut: false,
			payReward: false
		}
	},
	// switch选项
	switchOptions: switchOptions
})

let { billData, datePickerData, selectItemInfo } = toRefs(data)

onMounted(() => {
	billData.value.selectId = 1
})

onShow(() => { })

// 监听selectId
watch(() => billData.value.selectId, (newVal) => {
	// 储存到全部字段的值中
	allFieldsList.value.forEach(item => {
		billData.value.itemInfoList.forEach(oldItem => {
			if (oldItem.key == item.key) {
				item.value = oldItem.value
			}
		})
	})
	console.log("全部字段的值", allFieldsList.value)
	// 获取当前分类的字段
	let currentItemInfoList = []
	classifyTabBar.value.forEach(item => {
		if (item.selectId == newVal) {
			currentItemInfoList = item.itemInfoList ? JSON.parse(JSON.stringify(item.itemInfoList)) : []
		}
	})
	// 从全部字段的值中获取当前分类的字段的值
	currentItemInfoList.forEach(item => {
		allFieldsList.value.forEach(oldItem => {
			if (oldItem.key == item.key) {
				item.value = oldItem.value
			}
		})
	})
	// 设置当前分类的字段
	billData.value.itemInfoList = currentItemInfoList
	const orderStatus = classifyTabBar.value.find(item => item.selectId == newVal).orderStatus
	console.log("是否退款", billData.value.merchantOption)
	// console.log("是否退款", billData.value.merchantOption.refund && (newVal == 12 || newVal == 13))
	if (billData.value.merchantOption.refund && (newVal == 12 || newVal == 13)) {
		billData.value.orderStatus = "退款成功"
	} else {
		billData.value.orderStatus = orderStatus
	}
	// 设置当前分类的底部字段
	billData.value.bottomIcons = classifyTabBar.value.find(item => item.selectId == newVal).defaultBottomIcons
	console.log("当前分类的底部字段", billData.value.bottomIcons)


	setItemInfoValue(newVal)
})

/**
 * 设置每个字段信息值
 */
const setItemInfoValue = (id) => {
	billData.value.itemInfoList.forEach(item => {
		switch (id) {
			case 1:
				if (item.key == 'receiverFullName') {
					item.value = `${billData.value.name}有限公司`
				} else if (item.key == 'productDescription') {
					item.value = `xxxxxxx消费`
				}
				break;
			case 2:
				if (item.key == 'productDescription') {
					item.value = `收钱码收款`
				} else if (item.key == 'receiverFullName') {
					item.value = `***(个人)`
				}
				break;
			case 3:
				if (item.key == 'productDescription') {
					item.value = `xxxxxxx消费`
				}
				break;
			case 4:
				break;
			case 5:
				if (item.key == 'transferNote') {
					item.value = `报销`
				} else if (item.key == 'counterAccount') {
					item.value = `${billData.value.name}`
				}
				break;
			case 6:
				if (item.key == 'transferNote') {
					item.value = `转账`
				} else if (item.key == 'counterAccount') {
					item.value = `xxx123654789`
				}
				break;
			case 7:
				break;
			case 8:
				if (item.key == 'relatedRecord') {
					item.value = `查看关联记录`
				}
				break;
			case 9:
				if (item.key == 'relatedRecord') {
					item.value = `查看原账单`
				}
				break;
			case 10:
				break;
			case 11:
				break;
			case 12:
				break;
			case 13:
				break;
			default:
				break;
		}
	})
}

/**
 * 保存账单
 */
const onRightClick = () => {
	billData.value.id = stringUtil.uuid()
	console.log("保存", billData.value)
}

// 点击itemInfo
const onClickItemInfo = (item) => {
	console.log(item)
	if (item.type == 'time') {
		datePickerData.value.selectDate = item.value;
		datePickerData.value.endDate = formatTime(new Date());
		selectItemInfo.value = item
		timepopup.value.open()
	} else if (item.type == 'select') {
		selectItemInfo.value = item
		timepopup.value.open()
	} else if (item.type == 'text' || item.type == 'number' || item.type == "digit") {
		item.focus = false
		nextTick(() => {
			item.focus = true
		})
	}
}

/**
 * 底部icon点击选择
 * @param option 
 */
const onBottomIconClick = (option) => {
	if (billData.value.bottomIcons.includes(option.id)) {
		billData.value.bottomIcons = billData.value.bottomIcons.filter(item => item != option.id)
	} else {
		billData.value.bottomIcons.push(option.id)
	}
	console.log(billData.value.bottomIcons)
}

/**
 * switch切换
 */
const onSwitchChange = (e, option) => {
	const value = e.detail.value
	billData.value.merchantOption[option.key] = value
	console.log(billData.value.merchantOption)
	if (option.change) {
		option.change(value)
	}
}

/**
 * 格式化时间
 */
function formatTime(time) {
	const newTime = new Date(time)
	const year = newTime.getFullYear()
	const month = newTime.getMonth() + 1
	const date = newTime.getDate()
	const hours = newTime.getHours()
	const minutes = newTime.getMinutes()
	const seconds = newTime.getSeconds()
	return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`
}
/**
 * 关闭时间选择器
 */
const closeTimePicker = () => {
	timepopup.value.close()
}

/**
 * 设置时间
 */
const settmes = () => {
	console.log(datePickerData.value.selectDate)
	billData.value.itemInfoList.forEach(item => {
		if (item.type == 'time' && selectItemInfo.value.key == item.key) {
			item.value = datePickerData.value.selectDate
		}
	})
	timepopup.value.close()
}

/**
 * 设置分类选择
 */
const confirmClassify = () => {
	billData.value.itemInfoList.forEach(item => {
		if (item.type == 'select' && selectItemInfo.value.key == item.key) {
			billClassifyOptions.value.forEach(option => {
				if (option.id == data.currentClassifyId) {
					item.value = option.name
				}
			})
		}
	})
	timepopup.value.close()
}

/**
 * @param {Object} date
 * 切换时间
 */
function onChangeStartDate(date) {
	datePickerData.value.selectDate = date;
}
</script>

<style lang="less">
@import "@/common/main.css";
@import "@/common/specify-style.less";

page {
	background-color: #F5F5F5;
}
</style>
<style lang="less" scoped>
.tab-bar {
	display: flex;
	align-items: center;
	flex-wrap: nowrap;
	margin: 22rpx 24rpx;
	overflow: hidden;
	overflow-x: scroll;

	.tab-item {
		display: inline-block;
		padding: 12rpx 24rpx;
		background-color: #ffffff;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		width: auto;
		font-size: 26rpx;
		line-height: 31rpx;
		font-weight: 500;
		margin-right: 16rpx;
		white-space: nowrap;
	}

	.blue {
		color: #1B71F8;
	}
}

.add-bill-container {
	background-color: #ffffff;
	margin: 24rpx;
	margin-top: 34rpx;
	padding: 24rpx;
	border-radius: 16rpx 16rpx 16rpx 16rpx;

	.random-dice {
		width: 100%;
		text-align: right;

		.random-dice-image {
			width: 64rpx;
			height: 64rpx;
		}
	}
}



.avatar-box {
	margin-top: 12rpx;
	text-align: center;
	margin-bottom: 26rpx;

	.avatar-image {
		width: 80rpx;
		height: 80rpx;
	}
}

.main-info {
	color: var(--text-color);

	.order-status-info {
		font-size: 28rpx;
		margin-top: 12rpx;
	}

	.isRefund {
		color: #EA6B48;
	}
}

.detail-info-container {
	padding-top: 36rpx;

	.info-item-input {
		font-size: 26rpx;

		.text-measure {
			font-size: 26rpx;
		}

		.text-input {
			font-size: 26rpx;
		}
	}
}

.info-item-box {
	display: flex;
	align-items: center;
	margin: 20rpx 0;

	.item-label {
		min-width: 160rpx;
		margin-right: 28rpx;
		font-size: 26rpx;
		color: var(--text-secondary);
	}
}

.info-item-input {
	display: inline-flex;
	align-items: center;
	position: relative;
	min-width: 20px;
	max-width: 100%;
	width: auto;
	overflow: hidden;
	min-height: 20px;

	/* 隐藏的测量元素 */
	.text-measure {
		visibility: hidden;
		white-space: nowrap;
		color: var(--text-color);
		font-family: inherit;
		font-size: 28rpx;
		width: auto;
		min-width: 20px;
		height: auto;
	}

	.visibility {
		visibility: visible;
	}


	.text-input {
		font-size: 28rpx;
		position: absolute;
		width: calc(100%);
	}
}

.edit-image {
	width: 28rpx;
	height: 28rpx;
	margin-left: 10rpx;
	flex-shrink: 0;
}

.money {
	margin-top: 14rpx;
}

.switch-option-container {
	margin: 16rpx 24rpx;
	background-color: #ffffff;
	border-radius: 16rpx 16rpx 16rpx 16rpx;

	.border-bottom {
		border-bottom: 1px solid #efefef
	}

	.no-border-bottom {
		border: none;
	}

	.switch-option {
		padding: 24rpx;
		// border-top: 1rpx solid #E4E4E4;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.switch-option-text {
			font-size: 28rpx;
		}
	}

	.switch-option:first-child {
		border-top: none !important;
	}

	.service-detail {
		display: flex;
		align-items: center;
		background-color: #F6F7FB;
		padding: 22rpx 24rpx;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		margin: 0 18rpx;

		.service-detail-info {
			margin-left: 8rpx;
		}

		.service-detail-image {
			width: 44rpx;
			height: 44rpx;
		}

		.enter-mini-program {
			font-size: 22rpx;
			color: #969696;
			margin-left: 6px;
			line-height: 22rpx;
		}

		.right-text {
			font-size: 22rpx;
			color: #969696;
			margin-left: 6px;
			line-height: 22rpx;
		}

		.right-icon {
			width: 24rpx;
			height: 24rpx;
		}

		.select {
			flex: none;
			width: 80px;

			::v-deep .uni-select {
				font-size: 22rpx;
				padding: 0 5px !important;
				min-height: 22rpx !important;
			}

			::v-deep .uni-select__selector-item {
				font-size: 22rpx;
				padding: 0 5px !important;
			}

			::v-deep .uni-icons {
				font-size: 22rpx !important;

			}
		}
	}

	.recommend-service {
		background-color: #FFF5F6;

		.text-input {
			color: #9E2036;
		}
	}

	.service-recommend {
		background-color: #F6F7FB;

		.text-input {
			color: #123D72;
		}
	}
}

.bill-bottom-icon-options {
	display: flex;
	flex-wrap: wrap;
	margin: 16rpx 24rpx;
	background-color: #ffffff;
	border-radius: 16rpx 16rpx 16rpx 16rpx;
	padding: 22rpx 26rpx;

	.item-option-box {
		width: calc(100% / 3);
		// text-align: center;
		margin: 14rpx 0;

		.item-box {
			display: inline-flex;
			font-size: 20rpx;
			height: 52rpx;
			padding: 0 18rpx;
			border-radius: 94rpx 94rpx 94rpx 94rpx;
			border: 2rpx solid #EDEDED;
			align-items: center;

			.item-icon {
				width: 20rpx;
				height: 20rpx;
				margin-right: 12rpx;
			}
		}

		.active-item-box {
			background-color: #1B71F8;
			color: #ffffff;
			border: none;
		}
	}

}
</style>