<template>
	<view class="skill-page">
		<!-- 陪玩：分类 Tab -->
		<scroll-view v-if="isPlaymate" scroll-x class="category-tabs" :show-scrollbar="false">
			<view v-for="tab in playmateTabs" :key="tab.id" class="category-tab"
				:class="{ active: activeCategory === tab.id }" @click="activeCategory = tab.id">
				<text class="category-tab__text">{{ tab.name }}</text>
				<image v-if="activeCategory === tab.id" class="category-tab__indicator" src="/static/workbench/tabs.png"
					mode="widthFix" />
			</view>
		</scroll-view>

		<!-- 状态筛选 -->
		<view class="status-tabs">
			<view v-for="tab in statusTabs" :key="tab.key" class="status-tab"
				:class="{ active: activeStatus === tab.key }" @click="onStatusChange(tab.key)">{{ tab.label }}</view>
		</view>

		<!-- 技能列表 -->
		<view class="skill-list" v-if="filteredList.length">
			<view class="skill-card" v-for="item in filteredList" :key="item.id || item.projectId">
				<view class="card-body">
					<view class="card-main">
						<view class="cover">
							<image v-if="getCover(item)" :src="getCover(item)" mode="aspectFill" />
						</view>
						<view class="info">
							<view class="title-row">
								<text class="title">{{ item.projectName }}</text>
								<text class="sold" v-if="activeStatus === '1' && getSoldCount(item)">已售{{
									getSoldCount(item) }}</text>
							</view>
							<text class="price">
								<text class="priceUnit">¥</text>
								<text>{{ formatSkillPrice(item) }}</text>
								<!-- 计量单位(0:分钟 1:小时 2:次） -->
								<text class="priceUnit">/{{ item.unitType === 0 ? '分钟' : item.unitType === 1 ? '小时' :
									'次' }}</text>
							</text>
							<view class="status-bar"
								:class="{ 'status-bar--opened': activeStatus === '1', 'status-bar--rejected': activeStatus === '2' }"
								v-if="statusBarText(item)" @click="onStatusBarClick(item)">
								<image v-if="activeStatus === '1' || activeStatus === '0'" class="status-icon"
									:src="activeStatus === '1' ? '/static/workbench/skillTime.png' : '/static/workbench/clockIcon.png'"
									mode="aspectFit" />
								<text class="status-text">{{ statusBarText(item) }}</text>
								<view class="chevron" v-if="activeStatus === '2'">
									<image src="/static/workbench/redArrow.png" mode="aspectFit"
										style="width: 16rpx; height: 16rpx;" />
								</view>
							</view>
						</view>

					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="card-footer" v-if="activeStatus !== '0'">
					<template v-if="activeStatus === '1'">
						<view class="footer-btn footer-btn--ghost" @click="onOffShelf(item)">申请下架</view>
						<view class="footer-divider"></view>
						<view class="footer-btn footer-btn--primary" @click="goEdit(item)">编辑价格</view>
					</template>
					<template v-if="activeStatus === '2'">
						<view class="footer-btn footer-btn--ghost" @click="onDelete(item)">删除</view>
						<view class="footer-divider"></view>
						<view class="footer-btn footer-btn--primary" @click="openApplyModal([item])">重新申请</view>
					</template>
				</view>
			</view>
		</view>
		<view class="empty" v-else-if="!loading">暂无数据</view>

		<!-- 开通新服务 -->
		<view class="fab-btn" @click="goAdd">
			<image class="fab-icon" src="/static/workbench/addSkill.png" mode="aspectFit" />
			<text class="fab-text">开通新服务</text>
		</view>

		<!-- 驳回详情弹窗 -->
		<view class="modal-mask" v-if="showRejectModal" @click="showRejectModal = false">
			<view class="modal-box" @click.stop>
				<view class="modal-title">申请开通服务驳回</view>
				<view class="modal-body">{{ rejectDetailText }}</view>
				<view class="modal-footer" @click="showRejectModal = false">关闭</view>
			</view>
		</view>


		<!-- 申请开通弹窗 -->
		<view class="modal-mask1" v-if="showApplyModal" @click="showApplyModal = false">
			<view class="modal-box" @click.stop>
				<view class="box">
					<view class="modal-title">申请开通</view>
					<view class="apply-tip">已申请开通{{ applyItems.length }}项服务</view>
					<textarea class="apply-reason" v-model="applyReason" placeholder="请输入开通原因" maxlength="200"
						placeholder-style="font-weight: 400;font-size: 26rpx;color: #C9CDD4;" />
				</view>

				<view class="apply-btns">
					<view class="btn flex1" @click="closeApplyModal">取消</view>
					<view class="btn submit flex1" @click="submitApply">提交申请</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { PLAYMATE_TABS } from './mock.js'
import { getSkillList, updateMaProject, updateApply } from '@/api/workbench.js'

export default {
	data() {
		return {
			public: this.$globalData.publicUrl,
			cJsId: '',
			/** 服务标签（1：按摩推拿 2：陪玩） */
			serviceTag: '',
			playmateTabs: PLAYMATE_TABS,
			statusTabs: [
				{ key: '1', label: '已开通' },
				{ key: '0', label: '申请中' },
				{ key: '2', label: '申请驳回' },
			],
			skillList: [],
			activeCategory: PLAYMATE_TABS[0]?.id || '',
			activeStatus: '1',
			loading: false,
			showRejectModal: false,
			rejectDetailText: '',
			showApplyModal: false,
			applyItems: [],
			applyReason: '',
			agginApplyProjectId: '',
		}
	},
	computed: {
		isPlaymate() {
			return String(this.serviceTag) === '2'
		},
		isMassage() {
			return String(this.serviceTag) === '1'
		},
		filteredList() {
			if (!this.isPlaymate) return this.skillList
			const tab = this.playmateTabs.find(t => t.id === this.activeCategory)
			if (!tab) return this.skillList
			return this.skillList.filter(item => this.matchPlaymateCategory(item, tab))
		},
	},
	onLoad(query) {
		this.public = this.$globalData?.publicUrl || ''
		this.cJsId = uni.getStorageSync('userId') || ''
		this.serviceTag = query.serviceTag || uni.getStorageSync('serviceTag') || '1'
	},
	onShow() {
		this.getSkillList()
	},
	methods: {
		onStatusChange(key) {
			if (this.activeStatus === key) return
			this.activeStatus = key
			this.getSkillList()
		},
		getSkillList() {
			if (!this.cJsId) {
				this.cJsId = uni.getStorageSync('userId') || ''
			}
			if (!this.cJsId) return
			this.loading = true
			const params = {
				auditStatus: this.activeStatus,
				merchantId: this.cJsId,
				//typeId: this.serviceTag,
			}
			getSkillList(params).then(res => {
				if (res.data.code == 200) {
					this.skillList = Array.isArray(res.data.data) ? res.data.data : []

				} else {
					this.skillList = []
				}
			}).catch(() => {
				this.skillList = []
			}).finally(() => {
				this.loading = false
			})
		},
		matchPlaymateCategory(item, tab) {
			const categoryId = String(item.subTypeId || item.categoryId || item.subCategoryId || '')
			const categoryName = item.subTypeName || item.categoryName || item.subCategoryName || ''
			return categoryId === String(tab.id) || categoryName === tab.name
		},
		getCover(item) {
			const image = item.cover || item.projectImage || ''
			if (!image) return ''
			return image.startsWith('http') ? image : this.public + image
		},
		getSoldCount(item) {
			return item.soldCount ?? item.saleCount ?? item.orderCount ?? item.nSaleCount ?? 0
		},
		formatMoney(amount) {
			const num = parseFloat(amount)
			if (isNaN(num)) return '0.00'
			return num.toFixed(2)
		},
		formatSkillPrice(item) {
			const unit = item.cUnit || item.unit || '次'
			const min = item.projectLowestPrice
			const max = item.projectMaxPrice
			if (min != null && max != null) {
				return `${this.formatMoney(min)}-${this.formatMoney(max)}`
			}
			const price = item.projectCurrentPrice
			return `${this.formatMoney(price)}`
		},
		formatApplyDate(timeStr) {
			if (!timeStr) return ''
			const str = String(timeStr)
			const d = new Date(str.replace(/-/g, '/'))
			if (Number.isNaN(d.getTime())) return str
			return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日申请开通服务`
		},
		getRejectReason(item) {
			return item.reason || ''
		},
		statusBarText(item) {
			if (this.activeStatus === '1') {
				const time = item.applyTime || ''
				return time ? this.formatApplyDate(time) : ''
			}
			if (this.activeStatus === '0') return '申请开通服务审核中'
			if (this.activeStatus === '2') {
				const reason = this.getRejectReason(item)
				return reason.length > 28 ? reason.slice(0, 28) + '...' : reason
			}
			return ''
		},
		onStatusBarClick(item) {
			if (this.activeStatus === '2') {
				this.rejectDetailText = this.getRejectReason(item)
				this.showRejectModal = true
			}
		},
		goAdd() {
			const type = this.isPlaymate ? 'playmate' : 'massage'
			uni.navigateTo({ url: `/workbench/skill/add?type=${type}` })
		},
		//编辑服务
		goEdit(item) {
			console.log(item)
			if (item.auditStatus != 1) {
				uni.showToast({ title: '服务未开通，不支持该操作', icon: 'none' })
				return
			}
			const categoryName = this.isPlaymate
				? item.subTypeName || item.categoryName || item.subCategoryName || ''
				: ''
			const str = uni.$u.queryParams({
				id: item.projectId || '',
				title: item.projectName || '',
				cover: encodeURIComponent(this.getCover(item)),
				categoryName,
				billingType: item.unitType === 0 ? '按分钟计费' : item.unitType === 1 ? '按小时计费' : '按次计费',
				platformPrice: item.projectCurrentPrice,
				priceRangeMin: item.projectLowestPrice,
				priceRangeMax: item.projectMaxPrice,
				myPrice: item.projectOriginalPrice,
			})
			console.log(this.getCover(item))
			uni.navigateTo({ url: `/workbench/skill/edit${str}` })
		},

		//上下架服务
		onOffShelf(item) {
			if (item.auditStatus != 1) {
				uni.showToast({ title: '服务未开通，不支持该操作', icon: 'none' })
				return
			}
			if (this.filteredList.length == 1) {
				uni.showToast({ title: '不支持该操作，请至少保留1项服务', icon: 'none' })
				return
			}
			this.updateMaProjectFun({
				projectId: item.projectId || '',
				isPass: true,
			})
		},

		//更新服务状态
		updateMaProjectFun(params) {
			updateMaProject(params).then(res => {
				if (res.data.code == 200) {
					uni.showToast({ title: res.data.msg || '更新成功', icon: 'none' })
					this.getSkillList()
				} else {
					uni.showToast({ title: res.data.msg || '更新失败', icon: 'none' })
				}
			})
		},
		//删除服务
		onDelete(item) {
			uni.showModal({
				title: '提示',
				content: '确定删除该服务？',
				success: res => {
					if (res.confirm) {
						this.updateMaProjectFun({
							projectId: item.projectId || '',
							isDelete: true,
						})
					}
				},
			})
		},
		openApplyModal(items) {
			this.applyItems = items
			this.applyReason = ''
			this.showApplyModal = true
		},
		closeApplyModal() {
			this.showApplyModal = false
			this.applyItems = []
			this.applyReason = ''
		},
		submitApply() {
			if (!this.applyReason.trim()) {
				uni.showToast({ title: '请输入开通原因', icon: 'none' })
				return
			}
			updateApply({
				projectId: this.applyItems[0].projectId || '',
				applyReason: this.applyReason,
			}).then(res => {
				if (res.data.code == 200) {
					this.showApplyModal = false
					this.closeApplyModal()
					this.activeStatus = '0'
					this.getSkillList()
					uni.showToast({
						title: res.data.msg || '申请成功',
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: res.data.msg || '申请失败',
						icon: 'none'
					})
				}
			})

		},
	},
}
</script>

<style lang="scss" scoped>
.skill-page {
	min-height: 100vh;
	width: 100%;
	background: #f5f5f5;
	padding-bottom: 160rpx;
}

.category-tabs {
	white-space: nowrap;
	background: #fff;
	padding: 16rpx 24rpx 0;
	border-bottom: 1rpx solid #eee;
}

.category-tab {
	display: inline-flex;
	flex-direction: column;
	align-items: center;
	padding: 16rpx 28rpx 12rpx;
	position: relative;

	&__text {
		font-size: 28rpx;
		color: #999;
		line-height: 1.4;
	}

	&__indicator {
		width: 48rpx;
		height: 12rpx;
		margin-top: -8rpx;
	}

	&.active &__text {
		color: #333;
		font-weight: 600;
	}
}

.status-tabs {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 56rpx 18rpx 56rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 20rpx;
}

.status-tab {

	font-weight: 400;
	font-size: 30rpx;
	color: #4E5969;

	&.active {
		font-weight: 600;
		font-size: 32rpx;
		color: #1D2129;
	}
}

.skill-list {
	width: 100%;
	padding: 0 32rpx;
}

.skill-card {
	width: 100%;
	background: #fff;
	border: 1rpx solid #eee;
	border-radius: 12rpx;
	margin-bottom: 24rpx;
	overflow: hidden;
}

.card-body {
	width: 100%;
	padding: 32rpx;
	box-sizing: border-box;
}

.card-main {
	width: 100%;
	display: flex;
	gap: 24rpx;
	justify-content: space-between;
}

.cover {
	width: 140rpx;
	height: 140rpx;
	background: #eee;
	border-radius: 8rpx;
	flex-shrink: 0;
	overflow: hidden;

	image {
		width: 100%;
		height: 100%;
	}
}

.info {
	flex: 1;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	height: 140rpx;
}

.title-row {
	display: flex;
	justify-content: space-between;
}

.title {
	font-weight: 500;
	font-size: 30rpx;
	color: #1D2129;
}

.sold {
	width: 100rpx;
	height: 36rpx;
	background: #FFF4E7;
	border-radius: 4rpx 4rpx 4rpx 4rpx;
	padding: 8rpx 12rpx;
	font-weight: 400;
	font-size: 20rpx;
	color: #FF8D2F;



}

.price {
	font-weight: Bold;
	font-size: 36rpx;
	color: #FF4C12;
	margin: auto 0;
	//margin-top: 16rpx;
}

.priceUnit {
	font-weight: Regular;
	font-size: 20rpx;
	color: #FF4C12;
}

.status-bar {
	//margin-top: 8rpx;
	line-height: 36rpx;
	background: linear-gradient(90deg, #FFF6E6 0%, rgba(255, 246, 230, 0) 100%);
	border-radius: 4rpx 4rpx 4rpx 4rpx;
	padding: 0 16rpx;
	display: flex;
	align-items: center;
	overflow: hidden;

	font-weight: 400;
	font-size: 20rpx;
	color: #FC8C0C;

	&--opened {
		background: linear-gradient(90deg, #EAFFF0 0%, rgba(234, 255, 240, 0) 100%);

		.status-text {
			color: #00B42A;
		}
	}

	&--rejected {
		background: #FFF5F5;


		.status-text {
			flex: 1;
			color: #F53F3F;
			white-space: nowrap;
			/* 禁止换行 单行 */
			overflow: hidden;
			/* 超出隐藏 */
			text-overflow: ellipsis;
			/* 末尾... */
		}
	}
}

.status-icon {
	margin-right: 8rpx;
	width: 20rpx;
	height: 20rpx;
	flex-shrink: 0;
}



.chevron {
	display: flex;
	align-items: center;
}

.card-footer {
	flex: 1;
	display: flex;
	align-items: center;
	border-top: 1rpx solid #eee;
	height: 80rpx;
}

.footer-btn {
	flex: 1;
	text-align: center;
	padding: 24rpx 0;
	font-size: 28rpx;

	&--ghost {
		font-weight: 500;
		font-size: 28rpx;
		color: #86909C;
	}

	&--primary {
		font-weight: 500;
		font-size: 28rpx;
		color: #1D2129;
	}
}

.footer-divider {
	width: 1rpx;
	background: #eee;
	flex-shrink: 0;
}

.btn {
	padding: 12rpx 32rpx;
	font-size: 26rpx;
	border-radius: 8rpx;
	text-align: center;

	&.ghost {
		border: 1rpx solid #ccc;
		color: #666;
		background: #fff;
	}

	&.primary {
		background: #333;
		color: #fff;
		border: 1rpx solid #333;
	}

	&.flex1 {
		flex: 1;
	}
}

.empty {
	text-align: center;
	padding: 120rpx 0;
	font-size: 28rpx;
	color: #999;
}

.fab-btn {
	position: fixed;
	right: 32rpx;
	bottom: calc(48rpx + env(safe-area-inset-bottom));
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 12rpx 32rpx 12rpx 12rpx;
	background: #20CAC2;
	border-radius: 48rpx;
	box-shadow: 0 8rpx 24rpx rgba(32, 202, 194, 0.35);
	z-index: 100;

	.fab-icon {
		width: 48rpx;
		height: 48rpx;
		flex-shrink: 0;
	}

	.fab-text {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}
}

.modal-mask {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 48rpx;
	box-sizing: border-box;

	.modal-box {
		width: 100%;
		max-width: 600rpx;
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		text-align: center;
		padding: 32rpx;
	}

	.modal-body {
		font-weight: 400;
		font-size: 30rpx;
		color: #4E5969;
		max-height: 400rpx;
		overflow-y: auto;
		padding: 0 48rpx 32rpx;
	}

	.modal-footer {
		text-align: center;
		padding: 24rpx;
		font-size: 30rpx;
		color: #1D2129;
		border-top: 1rpx solid #eee;
	}

	.apply-box {
		padding-bottom: 0;
	}

	.apply-tip {
		text-align: center;
		font-size: 26rpx;
		color: #666;
		padding: 0 32rpx 16rpx;
	}

	.apply-reason {
		display: block;
		width: calc(100% - 64rpx);
		margin: 0 32rpx 24rpx;
		min-height: 200rpx;
		padding: 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		font-size: 26rpx;
		box-sizing: border-box;
	}

	.apply-btns {
		display: flex;
		gap: 16rpx;
		padding: 0 32rpx 32rpx;
	}
}



.modal-mask1 {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 48rpx;
	box-sizing: border-box;

	.modal-box {
		width: 100%;
		max-width: 600rpx;
		background: #fff;
		border-radius: 16rpx;

	}

	.box {
		padding: 32rpx 48rpx;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: 600;
		text-align: center;
	}

	.apply-tip {
		margin-top: 32rpx;
		font-weight: 400;
		font-size: 30rpx;
		color: #1D2129;
		text-align: left;
	}

	.apply-reason {
		width: 100%;
		height: 124rpx;
		padding: 8rpx;
		display: block;
		background: #F7F8FA;
		border-radius: 6rpx 6rpx 6rpx 6rpx;
		box-sizing: border-box;
		margin-top: 8rpx;

		font-weight: 400;
		font-size: 26rpx;
		color: #4E5969;
	}

	.apply-btns {
		display: flex;
		border-top: 1rpx solid #E7E7E7;
	}

	.btn {
		padding: 20rpx;
		height: 90rpx;
		font-size: 28rpx;
		border-radius: 8rpx;
		text-align: center;
		font-weight: 400;
		font-size: 30rpx;
		color: #86909C;
		text-align: center;



		&.submit {
			border-left: 1rpx solid #E7E7E7;
			font-weight: 400;
			font-size: 30rpx;
			color: #1D2129;
		}

		&.flex1 {
			flex: 1;
		}
	}
}
</style>
