<template>
	<view class="page">
		<u-navbar :title="isEdit ? '编辑' + (agreementType == 0 ? '公告' : '协议') : '添加' + (agreementType == 0 ? '公告' : '协议')" :border-bottom="false" :background="bgc" back-icon-color="#262B37" title-color='#262B37'
			title-size='36' height='36' id="navbar">
		</u-navbar>
		<view class="form">
			<view class="form-item">
				<text class="label">标题</text>
				<input class="input" v-model="obj.title" placeholder="请输入标题" placeholder-class="ph" />
			</view>
			<view class="form-item">
				<text class="label">展示秒数</text>
				<view class="input-with-unit">
					<input class="input" type="number" v-model.number="obj.duration" placeholder="请输入展示秒数" placeholder-class="ph" />
					<text class="unit">秒</text>
				</view>
			</view>
			<view class="form-item" style="display: flex;align-items: center;justify-content: space-between;">
				<text class="label">是否开启</text>
				<view class="input-with-unit">
					<u-switch v-model="flag"></u-switch>
				</view>
			</view>
		</view>
		 <view class="richtext">
		    <piaoyiEditor :values="values" :maxlength="0" @changes="saveContens" :readOnly="readOnly" :photoUrl="photoUrl" :token="token" :api="api" :name="name"/>
		   <!-- <view class="">
		        {{txt}}
		    </view> -->
		</view>
		<button hover-class="app-tap-hover" class="bc" @click="btnbc">{{ isEdit ? '保存' : '添加' }}</button>
		<qiniu-upload-progress />
	</view>
</template>

<script>
	 import piaoyiEditor from '@/uni_modules/piaoyi-editor/components/piaoyi-editor/piaoyi-editor.vue';
	    export default {
	        data() {
	            return {
	                readOnly: false, //是否只读
	                photoUrl: 'https://up-z2.qiniup.com', //服务器图片域名或者ip
	                api: '', //上传图片接口地址
	                txt: '',
	                name: 'file',
	                values: '',
					bgc: {
						backgroundColor: "#FFFFFF",
					},
					areaId:'',
					token:'',
					obj:{
						title: '',
						duration: 0
					},
					id:'',
					agreementType: 0, // 0-公告 1-协议
					isEdit: false ,// 是否为编辑模式
					flag:true
	            };
	        },
	        components: {
	            piaoyiEditor
	        },
			onLoad(option) {
				this.id = option.id || ''
				this.areaId = option.areaId || ''
				this.agreementType = option.agreementType ? Number(option.agreementType) : 0
				this.isEdit = !!this.id
				this.getqiniuyun()
				if (this.isEdit) {
					this.getxieyi()
				}
			},
	        methods: {
	            saveContens(e) {
	                this.txt = e.html
	            },
				// 获取公告协议
				getxieyi(){
					this.$u.get(`/bst/agreement/${this.id}`).then((res) => {
						if (res.code == 200) {
							this.values = res.data.content
							this.obj = res.data
							// status：1 启用 → 开关开；2 禁用 → 开关关（无字段时默认启用）
							const st = res.data.status
							this.flag = st == null || st === '' ? true : Number(st) === 1
						}
					})
				},
				// 获取七牛云上传token
				getqiniuyun(){
					this.$u.get("/common/qiniuToken").then((res) => {
						if (res.code == 200) {
							this.token = res.data
						}
					})
				},
				// 点击保存
				btnbc(){
					// 验证标题
					if (!this.obj.title || !this.obj.title.trim()) {
						uni.showToast({
							title: '请输入标题',
							icon: 'none',
							duration: 2000
						})
						return
					}
					
					// 验证内容
					const content = this.txt || this.values || ''
					if (!content || !content.trim()) {
						uni.showToast({
							title: '请输入内容',
							icon: 'none',
							duration: 2000
						})
						return
					}
					
					if (this.isEdit) {
						// 编辑模式 - PUT请求
						let data = {
							id: this.id,
							title: this.obj.title,
							duration: Number(this.obj.duration) || 0,
							content: content,
							status: this.flag ? 1 : 2
						}
						this.$u.put(`/bst/agreement`, data).then((res) => {
							if (res.code == 200) {
								uni.showToast({
									title: '保存成功',
									icon: 'success',
									duration: 3000
								})
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							} else {
								uni.showToast({
									title: res.msg || '保存失败',
									icon: 'none',
									duration: 3000
								})
							}
						}).catch((err) => {
							uni.showToast({
								title: '保存失败，请重试',
								icon: 'none',
								duration: 3000
							})
						})
					} else {
						// 添加模式 - POST请求
						// 验证areaId
						if (!this.areaId) {
							uni.showToast({
								title: '区域ID不能为空',
								icon: 'none',
								duration: 2000
							})
							return
						}
						
						let data = {
							title: this.obj.title,
							agreementType: this.agreementType,
							areaId: this.areaId,
							contentType: 2,
							content: content,
							duration: Number(this.obj.duration) || 0,
							status: this.flag ? 1 : 2
						}
						this.$u.post(`/bst/agreement`, data).then((res) => {
							if (res.code == 200) {
								uni.showToast({
									title: '添加成功',
									icon: 'success',
									duration: 3000
								})
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							} else {
								uni.showToast({
									title: res.msg || '添加失败',
									icon: 'none',
									duration: 3000
								})
							}
						}).catch((err) => {
							uni.showToast({
								title: '添加失败，请重试',
								icon: 'none',
								duration: 3000
							})
						})
					}
				}
	        },
	        onShareAppMessage(res) {
	            if (res.from === 'button') { // 来自页面内分享按钮
	                console.log(res.target)
	            }
	            return {
	                title: '多功能富文本编辑器！',
	                path: '/pages/editor/editor'
	            }
	        },
	        onShareTimeline(res) {
	            if (res.from === 'button') { // 来自页面内分享按钮
	                console.log(res.target)
	            }
	            return {
	                title: '多功能富文本编辑器！'
	            }
	        }
	    }
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
	::v-deep .editor{
		height: 43vh;
		overflow: scroll;
	}
	.form{
		padding: 24rpx 32rpx 0;
	}
	.form-item{
		margin-bottom: 28rpx;
	}
	.label{
		display: inline-block;
		font-size: 28rpx;
		color: #222;
		margin-bottom: 12rpx;
	}
	.input{
		width: 84%;
		height: 88rpx;
		padding: 0 24rpx;
		border-radius: 16rpx;
		background: #ffffff;
		border: 2rpx solid #ececec;
		color: #222;
		font-size: 28rpx;
	}
	.input:focus{
		border-color: #ff5fa2;
		box-shadow: 0 0 0 4rpx rgba(255,95,162,0.1);
	}
	.ph{
		color: #9a9a9a;
	}
	.input-with-unit{
		display: flex;
		align-items: center;
		gap: 12rpx;
	}
	.unit{
		color: #ff5fa2; /* 粉色点缀 */
		font-size: 28rpx;
		padding: 0 8rpx;
	}
	.bc{
		width: 680rpx;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 50rpx;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #4297F3;
		color: #fff;
		text-align: center;
		line-height: 90rpx;
		font-size: 32rpx;
		font-weight: 600;
	}
</style>