<template>
	<view class="box flex flex-column align-items justify-center">
		<view class="first flex flex-column align-items justify-start">
			<view class="row flex align-items" @click.stop="teacherShow = true">
				<span class="label flex align-items">课程讲师
					<span style="color: #FF2323;">*</span>
				</span>
				<view class="row-right flex align-items">
					<span class="hui" v-if="form.teacher == ''">选择</span>
					<span class="hui" v-if="form.teacher != ''">{{form.teacher}}</span>
					<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
				</view>
			</view>
			<span class="line-row"></span>
			<view class="row flex align-items" style="margin-top: 25rpx; " @click.stop="classesShow = true">
				<span class="label flex align-items">课程类型
					<span style="color: #FF2323;">*</span>
				</span>
				<view class="row-right flex align-items">
					<span class="hui" v-if="form.classes == ''">选择</span>
					<span class="hui" v-if="form.classes != ''">{{form.classes}}</span>
					<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
				</view>
			</view>
			<span class="line-row"></span>
			<view class="row flex align-items" style="margin-top: 25rpx; ">
				<span class="label flex align-items ">课程标题
					<span style="color: #FF2323;">*</span>
				</span>
				<span class="row-right">
					<input type="text" placeholder="填写标题" class="input" v-model="form.title"
						placeholder-class="plasty" />
				</span>
			</view>
			<span class="line-row"></span>
			<view class="row flex align-items" style="margin-top: 25rpx; ">
				<span class="label flex align-items ">课程价格
					<span style="color: #FF2323;">*</span>
				</span>
				<span class="row-right">
					<input type="text" placeholder="填写0则为免费课程" class="input" v-model="form.price"
						placeholder-class="plasty" />
				</span>
			</view>
			<span class="line-row"></span>
			<view class="row flex align-items" style="margin-top: 25rpx; ">
				<span class="label flex align-items ">核销次数
					<span style="color: #FF2323;">*</span>
				</span>
				<span class="row-right">
					<input type="number" placeholder="课时数不能少于核销次数" disabled="true" class="input"
						v-model="form.classes_num" placeholder-class="plasty" />
				</span>
			</view>
		</view>
		<view class="second flex flex-column align-items justify-start">
			<span class="se-title flex">课时添加</span>
			<view class="secondList flex flex-column align-items justify-start">
				<view class="content flex flex-column align-items justify-start" v-for="(item, index) in formList"
					:key="index">
					<view class="row flex align-items" style="margin-top: 25rpx;">
						<span class="label flex align-items">课时名称
							<span style="color: #FF2323;">*</span>
						</span>
						<span class="row-right">
							<input type="text" placeholder="填写名称" class="input" v-model="item.name"
								placeholder-class="plasty" />
						</span>
					</view>
					<span class="line-row"></span>
					<view class="row flex align-items" style="margin-top: 31rpx;" @click="selctTime(index)">
						<span class="label flex align-items">上课时间
							<span style="color: #FF2323;">*</span>
						</span>
						<view class="row-right flex align-items">
							<span v-if="item.start_time" class="hui">{{ item.start_time }}-{{item.end_time}}</span>
							<span v-else class="hui">选择时间</span>
							<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
						</view>
					</view>
					<!-- <span class="line-row"></span>
					<view class="row flex align-items" style="margin-top: 31rpx;" @click="selctTime(index)">
						<span class="label flex align-items">开始时间
							<span style="color: #FF2323;">*</span>
						</span>
						<view class="row-right flex align-items">
							<span>{{ item.start_time }}</span>
							<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
						</view>
					</view>
					<span class="line-row"></span>
					<view class="row flex align-items" style="margin-top: 31rpx;" @click="selctTime(index)">
						<span class="label flex align-items">结束时间
							<span style="color: #FF2323;">*</span>
						</span>
						<view class="row-right flex align-items">
							<span>{{ item.end_time }}</span>
							<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
						</view>
					</view> -->
					<span class="line-row"></span>
					<view class="row flex align-items" style="margin-top: 31rpx;">
						<span class="label flex align-items">人数上限
							<span style="color: #FF2323;">*</span>
						</span>
						<span class="row-right">
							<input type="text" placeholder="填写人数上限" class="input" v-model="item.limit_num"
								placeholder-class="plasty" />
						</span>
					</view>
					<!-- <span class="line-row"></span> -->
					<!-- <view class="row flex align-items" style="margin-top: 31rpx;" @click.stop="isStatus(index)">
						<span class="label flex align-items">上架状态
							<span style="color: #FF2323;">*</span>
						</span>
						<view class="row-right flex align-items">
							<span class="hui" v-if="item.status_name == ''">选择</span>
							<span class="hui" v-if="item.status_name != ''">{{item.status_name}}</span>
							<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
						</view>
					</view> -->
					<!-- <view class="row flex align-items" style="margin-top: 31rpx;">
						<span class="label flex align-items">上架状态
							<span style="color: #FF2323;">*</span>
						</span>
						<view class="row-right flex align-items">
							<span class="hui">上架</span>
							<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
						</view>
					</view> -->
					<span class="del" @click.stop="removePeriod(index)" v-if="formList.length > 1">移出课时-</span>
				</view>
				<span class="add" @click.stop="addPeriod()">新增课时 + </span>
			</view>
		</view>
		<!-- 机构热门 -->
		<view class="trend flex justify-center align-items">
			<view class="row flex align-items" @click.stop="selfhotShow = true">
				<span class="label flex align-items">机构热门
					<span style="color: #FF2323;">*</span>
				</span>
				<view class="row-right flex align-items">
					<span class="hui">{{form.selfhot == 0 ? '否' : '是'}}</span>
					<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
				</view>
			</view>
		</view>

		<!-- 上架状态 -->
		<view class="trend flex justify-center align-items">
			<view class="row flex align-items" @click.stop="disable && (shangShow = true)">
				<span class="label flex align-items">是否立即上架
					<span style="color: #FF2323;">*</span>
				</span>
				<view class="row-right flex align-items">
					<span class="hui">{{form.status_name}}</span>
					<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;" v-if="disable"></image>
				</view>
			</view>
		</view>
		<!-- 地点类型  上课位置 -->
		<view class="first flex flex-column align-items justify-start">
			<view class="row flex align-items" @click.stop="typeShow = true">
				<span class="label flex align-items">地点类型
					<span style="color: #FF2323;">*</span>
				</span>
				<view class="row-right flex align-items">
					<span class="hui">{{form.type}}</span>
					<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
				</view>
			</view>
			<span class="line-row"></span>
			<view class="row flex align-items" style="margin-top: 25rpx; " @click.stop="address_typeShow = true">
				<span class="label flex align-items">上课位置
					<span style="color: #FF2323;">*</span>
				</span>
				<view class="row-right flex align-items">
					<span class="hui">{{form.address_type}}</span>
					<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
				</view>
			</view>
			<view class="w-100  flex flex-column align-items justify-start" v-if="localShow">
				<span class="line-row"></span>
				<view class="row flex align-items" style="margin-top: 25rpx; " @click.stop="districtShow = true">
					<span class="label flex align-items">选择县区
						<span style="color: #FF2323;">*</span>
					</span>
					<view class="row-right flex align-items">
						<span class="hui">{{form.district_name}}</span>
						<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
					</view>
				</view>
				<span class="line-row"></span>
				<view class="row flex align-items" style="margin-top: 25rpx;">
					<span class="label flex align-items">选择地址 <span style="color: #FF2323;">*</span></span>
					<span class="row-right flex align-items" @click="choose()">
						<span class="hui">{{form.address}}</span>
						<image src="../../static/my/right.png" mode="" style="width: 24rpx;height: 24rpx;"></image>
					</span>
				</view>
				<span class="line-row"></span>
				<view class="row flex align-items" style="margin-top: 25rpx;">
					<span class="label flex align-items ">详细位置
						<span style="color: #FF2323;">*</span>
					</span>
					<span class="row-right flex align-items">
						<input type="text" placeholder="请填写详细位置" class="input" v-model="form.address_detail"
							placeholder-class="plasty" />
					</span>
				</view>
			</view>

		</view>
		<!-- 标签 -->
		<view class="four flex flex-column align-items justify-start">
			<view class="class_type">课程标签
				<span style="color: #FF2323;margin: 0 12rpx 0 6rpx;">*</span>
				<span>(最多只能选择三个)</span>
			</view>
			<view class="" style="width: 100%;margin-top: 24rpx;">
				<uni-section title="" type="line">
					<view class="uni-px-5 uni-pb-5">
						<zxz-uni-data-select v-model="form.classes_cate_ids" filterable multiple dataKey="label"
							dataValue="value" :localdata="classes_cateList" @change="change"></zxz-uni-data-select>
					</view>
				</uni-section>
			</view>
			<span class="line-row"></span>
			<view class="class_type" style="margin-top: 31rpx;">热门标签
				<span style="color: #FF2323;margin: 0 12rpx 0 6rpx;">*</span>
				<span>(最多只能选择三个)</span>
			</view>
			<view class="" style="width: 100%;margin-top: 24rpx;">
				<uni-section title="" type="line">
					<view class="uni-px-5 uni-pb-5">
						<zxz-uni-data-select v-model="form.classes_label_ids" filterable multiple dataKey="label"
							dataValue="value" :localdata="classes_labelList"></zxz-uni-data-select>
					</view>
				</uni-section>
			</view>
		</view>
		<!-- 封面照片 -->
		<view class="third flex flex-column" style="margin-top: 42rpx;">
			<span class="swiper" style="margin-bottom: 24rpx;">封面图
				<span style="color: #FF2323;">*</span></span>
			<u-upload :fileList="fileList1" @afterRead="afterRead" :previewFullImage="true" @delete="deletePic"
				@oversize="oversize" name="1" multiple :maxSize="2*1024*1024" :maxCount="1">
				<image src="../../static/index/upload.png" mode="widthFix" style="width: 200rpx;height: 200rpx;" />
			</u-upload>
		</view>
		<!-- 轮播图 -->
		<view class="third flex flex-column">
			<view class="header flex flex-column">
				<span class="swiper">轮播图
					<span style="color: #FF2323;">*</span></span>
				<span class="tips">(最多只能上传6张,单张最大不超过2M,尺寸750*450)</span>

			</view>
			<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" multiple :maxCount="6"
				:previewFullImage="true" width="200rpx" height="200rpx" @oversize="oversize" :maxSize="2*1024*1024">
				<image src="../../static/index/upload.png" mode="widthFix" style="width: 200rpx;height: 200rpx;">
			</u-upload>
		</view>

		<!-- 课程详情 -->
		<view class="third flex flex-column">
			<view class="header flex flex-column">
				<span class="swiper">课程详情
					<span style="color: #FF2323;">*</span></span>

			</view>
			<view class="">
				<u--textarea v-model="form.content" placeholder="请输入内容" height="170" :maxlength="2000"
					count></u--textarea>
			</view>
		</view>

		<!-- 课程须知 -->
		<view class="third flex flex-column" style="margin-bottom:242rpx;">
			<view class="header flex flex-column">
				<span class="swiper">课程须知
					<span style="color: #FF2323;">*</span></span>
			</view>
			<view class="">
				<u--textarea v-model="form.notice" placeholder="请输入内容" height="170" :maxlength="2000"
					count></u--textarea>
			</view>
		</view>

		<view class="footer flex align-items" style="justify-content: space-evenly;">
			<span class="cancel flex align-items justify-center">取消</span>
			<span class="pass flex align-items justify-center" v-if="disable" @click.stop="add()">确认</span>
			<span class="pass flex align-items justify-center" v-if="disable == false" @click.stop="add()">编辑</span>
		</view>

		<!-- 课程讲师 -->
		<u-picker :show="teacherShow" :columns="teacherList" keyName="name" @cancel="teacherCancel"
			@confirm="teacherConfirm"></u-picker>
		<!-- 课程类型 -->
		<u-picker :show="classesShow" :columns="classesTypeList" keyName="name" @cancel="classesCancel"
			@confirm="classesConfirm"></u-picker>
		<!-- 机构热门 -->
		<u-picker :show="selfhotShow" :columns="selfhotList" @cancel="selfhotCancel"
			@confirm="selfhotConfirm"></u-picker>
		<!-- 地点类型 -->
		<u-picker :show="typeShow" :columns="typeList" @cancel="typeCancel" @confirm="typeConfirm"></u-picker>
		<!-- 选择县区 -->
		<u-picker :show="districtShow" :columns="districtList" keyName="label" @cancel="districtCancel"
			@confirm="districtConfirm"></u-picker>
		<!-- 课时上架状态 -->
		<u-picker :show="statusShow" :columns="statusList" keyName="label" @cancel="statusCancel"
			@confirm="statusConfirm"></u-picker>

		<!-- 课程上架状态 -->
		<u-picker :show="shangShow" :columns="shangList" keyName="label" @cancel="shangCancel"
			@confirm="shangConfirm"></u-picker>
		<!-- 地址类型 -->
		<u-picker :show="address_typeShow" :columns="address_typeList" @cancel="address_typeCancel"
			@confirm="address_typeConfirm"></u-picker>
		<!-- 时间选择 -->
		<hbxw-date-range-picker title="选择时间" :visible="dateReangeVisible" level="minute" @cancel="cancel" @sure="sure"
			@change="dateChange" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//教师列表
				teacherShow: false,
				teacherList: [],
				// 课程列表
				classesShow: false,
				classesTypeList: [],
				// 机构热门
				selfhotShow: false,
				selfhotList: [
					['是', '否']
				],
				// 地点类型
				typeShow: false,
				typeList: [
					['室内', '室外']
				],
				// 县区
				districtShow: false,
				districtList: [],
				// 课时上架状态
				statusShow: false,
				// 课程上架状态
				shangShow: false,
				shangList: [
					[{
						label: '是',
						// 其他属性值
						value: 1
						// ...
					}, {
						label: '否',
						value: 2
					}, 
					// {
					// 	label: '平台下架',
					// 	value: 3
					// },
					]
				],
				statusList: [
					[{
						label: '上架',
						// 其他属性值
						value: 1
						// ...
					}, {
						label: '下架',
						value: 2
					}, 
					// {
					// 	label: '平台下架',
					// 	value: 3
					// },
					]
				],
				// 地址类型
				address_typeList: [
					['机构内授课', '特定位置授课']
				],
				address_typeShow: false,
				localShow: false,

				form: {
					latitude: '',
					longitude: '',
					address_detail: '',
					teacher_id: "",
					teacher: '',
					classes: '',
					classes_type: '',
					title: '',
					price: '',
					verification_num: '',
					location_type: '',
					address_type: '机构内授课',
					address: '',
					course_details: '',
					course: "",
					selfhot: '否',
					type: '室内',
					classes_cate_ids: '',
					classes_label_ids: '',
					notice: '', //须知
					content: '', //详情
					status_name: '是', //上下架,
					status: '1', //上下架id
					classes_num: '1', //核销次数
					district_name: '', //县区名字
					district: "" //县区id
				},
				dateReangeVisible: false,
				currentPeriodIndex: null,
				currentTimeType: null,
				date: null,
				formList: [{
					name: '',
					start_time: '',
					end_time: '',
					limit_num: '',
					status_name: '',
					status: '1',
					visible: true
				}],
				fileList1: [], // 用于存储第一个上传组件的文件列表
				fileList2: [], // 用于存储第二个上传组件的文件列表
				list1: '',
				list2: '',
				disable: true,
				// 课程标签
				classes_cateList: [],
				// 课程热门
				classes_labelList: [],
			};
		},
		watch: {
			value1: {
				handler(newVal, oldVal) {
					// console.log("b------: ", newVal, oldVal);
				},
				deep: true, //对象中任一属性值发生变化，都会触发handler方法
				immediate: true //初始化绑定时就会执行handler方法
			}
		},
		onLoad(option) {
			 this.initData(option);
		},

		methods: {
			async initData(option) {
			    const promises = [
			        this.getTeacherList(option.shop_id),
			        this.getclassesTypeList(),
			        this.getclassesList(),
			        this.getclasses_labelList(),
			        this.getdistrictList()
			    ];
			
			    try {
			        await Promise.all(promises);
			
			        if (option.id) {
			            this.disable = false;
			            uni.setNavigationBarTitle({
			                title: '编辑课程'
			            });
			            await this.getDetail(option.id); // 等待 getDetail 完成
			        }
			    } catch (error) {
			        console.error('加载数据时发生错误:', error);
			        uni.showToast({
			            title: '加载数据失败，请重试',
			            icon: 'none',
			            duration: 2000
			        });
			    }
			},
			
			addPeriod() {
				this.formList.push({
					name: '',
					start_time: '',
					end_time: '',
					limit_num: '',
					status: 1,
					visible: true
				});
			},
			// 获取详情
			async getDetail(id) {
			    try {
			        const res = await uni.$u.http.get('/api/school/classes/detail', {
			            params: {
			                id: id,
			            }
			        });
			
			        if (res.code == 1) {
			            this.form = res.data.detail;
			
			            // 调试信息
			            console.log('form.classes_type:', this.form.classes_type);
			            console.log('classesTypeList:', this.classesTypeList);
			
			            // 创建一个映射对象，将 id 映射到 name
			            const classes_typeMap = {};
			            this.classesTypeList[0].forEach(item => {
			                classes_typeMap[item.id] = item.name;
			            });
			
			            // 调试信息
			            console.log('classes_typeMap:', classes_typeMap);
			
			            this.form.classes = classes_typeMap[this.form.classes_type] || '';
			
			            // 其他数据处理逻辑...
			
			            const teacherMap = {};
			            this.teacherList[0].forEach(item => {
			                teacherMap[item.id] = item.name;
			            });
			            this.form.teacher = teacherMap[this.form.teacher.id] || '';
			
						if (this.form.status == 1) {
							this.form.status_name  = '是'
						} if (this.form.status == 1){
							this.form.status_name  = '否'
						} else {
							this.form.status_name  = '审核中'
						}
			            this.form.type = this.form.type == 'in' ? '室内' : "室外";
			            this.form.address_type = this.form.address_type == 1 ? '机构内授课' : "特定位置授课";
			            if (this.form.address_type == 2) {
			                this.localShow = true;
			            }
			
			            const districtMap = {};
			            this.districtList.forEach(item => {
			                districtMap[item.value] = item.label;
			            });
			            this.form.district_name = districtMap[this.form.district] || '';
			
			            this.formList = res.data.detail.specs.map((item) => {
			                return {
			                    name: item.name,
			                    end_time: item.end_time_text,
			                    weigh: item.weigh,
			                    start_time: item.start_time_text,
			                    limit_num: item.limit_num,
			                    id: item.id,
			                    status: item.status // 假设 item 中有 status 属性
			                };
			            });
			
			            const statusMap = {};
			            this.statusList.forEach(item => {
			                statusMap[item.value] = item.label;
			            });
			
			            this.formList = this.formList.map(item => {
			                return {
			                    ...item,
			                    status_name: statusMap[item.status] || ''
			                };
			            });
			
			            this.form.classes_cate_ids = this.form.classes_cate_ids.split(',');
			            this.form.classes_label_ids = this.form.classes_label_ids.split(',');
			            this.fileList1 = this.formatImagesToFiles(this.form.headimage.split(','));
			            this.list1 = this.form.headimage;
			            this.list2 = this.form.images.join(',');
			            this.fileList2 = this.formatImagesToFiles(this.form.images);
			        } else {
			            uni.showToast({
			                title: res.msg,
			                icon: 'none',
			                duration: 2000
			            });
			            throw new Error(res.msg);
			        }
			    } catch (error) {
			        console.error('请求失败', error);
			        throw error;
			    }
			},
			formatImagesToFiles(images) {
				return images.map((url, index) => ({
					url,
					name: `image${index + 1}.jpg`
				}));
			},
			// 获取县区
			getdistrictList() {
				uni.$u.http.get('/api/index/get_area', {
					params: {
						province: '410000',
						city: '410300',
					}
				}).then(res => {
					if (res.code == 1) {
						this.districtList[0] = res.data.map(item => ({
							label: item.label,
							value: item.value
						}));
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			},
			// 获取课程标签
			getclassesList() {
				uni.$u.http.get('/api/school/classes/cate_list', {}).then(res => {
					if (res.code == 1) {
						this.classes_cateList = res.data.list.map(item => ({
							label: item.name,
							value: item.id
						}));
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			},
			// 获取课程热门
			getclasses_labelList() {
				uni.$u.http.get('/api/school/classes/label_list', {}).then(res => {
					if (res.code == 1) {
						this.classes_labelList = res.data.list.map(item => ({
							label: item.name,
							value: item.id
						}));
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			},
			// 获取教师
			getTeacherList(id) {
				uni.$u.http.get('/api/school/teacher/teacher_list', {
					params: {
						shop_id: id,
					}
				}).then(res => {
					if (res.code == 1) {
						this.teacherList[0] = res.data.list

					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			},
			// 课程类型
			getclassesTypeList() {
				uni.$u.http.get('/api/school/classes/type_list', {}).then(res => {
					if (res.code == 1) {
						this.classesTypeList[0] = res.data.list

					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch(error => {
					console.error('请求失败', error);
				});

			},
			// 选择地址
			choose() {
				const that = this
				uni.chooseLocation({
					success: function(res) {
						console.log(res)
						that.form.address = res.name
						// that.form.address_detail = res.address
						that.form.latitude = res.latitude
						that.form.longitude = res.longitude
					},
					fail: function(rot) {
						console.log(rot)
					}
				});
			},
			// 选择县区
			districtCancel(e) {
				this.teacherShow = false
			},
			districtConfirm(e) {
				console.log(e.value)
				this.form.district = e.value[0].value
				this.form.district_name = e.value[0].label
				this.districtShow = false
			},
			// 选择教师
			teacherCancel(e) {
				this.teacherShow = false
			},
			teacherConfirm(e) {
				console.log(e.value)
				this.form.teacher_id = e.value[0].id
				this.form.teacher = e.value[0].name
				this.teacherShow = false
			},
			// 平台状态
			isStatus(index) {
				this.currentPeriodIndex = index;
				this.statusShow = true
			},
			statusCancel(e) {
				this.statusShow = false
			},
			statusConfirm(e) {
				console.log(e.value)
				const {
					currentPeriodIndex,
				} = this;
				// if (e.value[0].value == '')
				if (currentPeriodIndex !== null) {
					this.$set(this.formList[currentPeriodIndex], 'status', e.value[0].value);
					this.$set(this.formList[currentPeriodIndex], 'status_name', e.value[0].label);
				}
				this.statusShow = false
			},
			// 课程上架状态
			shangCancel(e) {
				this.shangShow = false
			},
			shangConfirm(e) {
				this.form.status = e.value[0].value
				this.form.status_name = e.value[0].label
				this.shangShow = false
			},
			// 选择课程类型
			classesCancel(e) {
				this.classesShow = false
			},
			classesConfirm(e) {
				console.log(e.value)
				this.form.classes_type = e.value[0].id
				this.form.classes = e.value[0].name
				this.classesShow = false
			},
			// 是否热门
			selfhotCancel(e) {
				this.selfhotShow = false
			},
			selfhotConfirm(e) {
				console.log(e.value)
				this.form.selfhot = e.value[0]
				this.selfhotShow = false
			},
			// 地点类型
			typeCancel(e) {
				this.typeShow = false
			},
			typeConfirm(e) {
				console.log(e.value)
				this.form.type = e.value[0]
				this.typeShow = false
			},
			// 地址类型
			address_typeCancel(e) {
				this.address_typeShow = false
			},
			address_typeConfirm(e) {
				console.log(e.value)
				this.form.address_type = e.value[0]
				this.address_typeShow = false

				if (e.value[0] == '特定位置授课') {
					this.localShow = true
				} else {
					this.localShow = false
					this.form.province = ''
					this.form.city = ''
					this.form.district = ''
					this.form.address = ''
					this.form.address_detail = ''
					this.form.longitude = ''
					this.form.latitude = ''
				}
			},
			// 选择时间
			selctTime(index) {
				this.currentPeriodIndex = index;
				this.dateReangeVisible = true;
			},
			cancel() {
				this.dateReangeVisible = false;
			},
			sure(res) {
				const {
					currentPeriodIndex,
				} = this;
				console.log(res)
				if (currentPeriodIndex !== null) {
					this.$set(this.formList[currentPeriodIndex], 'start_time', res.startStr);
					this.$set(this.formList[currentPeriodIndex], 'end_time', res.endStr);
				}
				this.dateReangeVisible = false;
			},
			dateChange(res) {
				console.log('---- change ----:', res);
				this.date = res;
			},
			removePeriod(index) {
				this.formList.splice(index, 1);
				this.formList[index].visible = false; // 设置 visible 为 false
			},
			change(e) {
				console.log('e:', e);
			},
			oversize(e) {
				this.$u.toast("请传2MB以内大小的图片！");
				return false;
			},

			// 删除图片
			deletePic(event) {
				console.log(event);
				const {
					name,
					index
				} = event;

				if (index >= 0 && index < this[`fileList${name}`].length) {
					this[`fileList${name}`].splice(index, 1);

					// 更新对应的 list 字段
					// if (name === '1') {
					// 	this.list1 = this.fileList1.map(item => item.url).join(',');
					// 	console.log('Updated list1:', this.list1);
					// } else
					if (name === '1') {
						this.list1 = this.fileList1.length > 0 ? this.fileList1[0].url : '';
						console.log('Updated list1:', this.list1);
					} else if (name === '2') {
						this.list2 = this.fileList2.map(item => item.url).join(',');
						console.log('Updated list2:', this.list2);
					}

					// 确保对应的 list 字段是一个数组
					let list = this[`list${name}`];
					if (!Array.isArray(list)) {
						console.warn(`list${name} is not an array, skipping splice operation`);
					} else {
						list.splice(index, 1);
						console.log(`Updated list${name}:`, list);
					}
				} else {
					console.error('Invalid index');
				}
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}));
					console.log(this[`fileList${event.name}`], ' this[`fileList${event.name}`]')
					fileListLen++;
					// 更新对应的list字段
					// if (event.name === '1') {
					// 	console.log(this.fileList1, 'this.fileList1');
					// 	this.list1 = this.fileList1.map(item => item.url).join(',');
					// 	console.log(this.list1, 'this.list1');
					// }
					if (event.name === '1') {
						this.list1 = this.fileList1[0]?.url || '';
					} else if (event.name === '2') {
						this.list2 = this.fileList2.map(item => item.url).join(',');
					}
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://testy.hschool.com.cn//api/school.worker.common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"token": uni.getStorageSync("token")
						},
						success: (res) => {
							resolve(JSON.parse(res.data).data.fullurl);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			//确认添加
			add() {
				console.log(this.formList)
				this.formList.forEach(item => {
					let formattedStartTime, formattedEndTime;

					// 处理 start_time
					if (item.start_time.includes('年')) {
						const [startYear, startMonth, startDay, startTime] = item.start_time.match(
							/(\d{4})年(\d{1,2})月(\d{1,2})日 (\d{2}:\d{2})/).slice(1);
						formattedStartTime =
							`${startYear}/${startMonth.padStart(2, '0')}/${startDay.padStart(2, '0')} ${startTime}`;
					} else {
						const [startYear, startMonth, startDay, startTime] = item.start_time.match(
							/(\d{4})-(\d{1,2})-(\d{1,2}) (\d{2}:\d{2}):(\d{2})/).slice(1);
						formattedStartTime =
							`${startYear}/${startMonth.padStart(2, '0')}/${startDay.padStart(2, '0')} ${startTime}`;
					}

					// 处理 end_time
					if (item.end_time.includes('年')) {
						const [endYear, endMonth, endDay, endTime] = item.end_time.match(
							/(\d{4})年(\d{1,2})月(\d{1,2})日 (\d{2}:\d{2})/).slice(1);
						formattedEndTime =
							`${endYear}/${endMonth.padStart(2, '0')}/${endDay.padStart(2, '0')} ${endTime}`;
					} else {
						const [endYear, endMonth, endDay, endTime] = item.end_time.match(
							/(\d{4})-(\d{1,2})-(\d{1,2}) (\d{2}:\d{2}):(\d{2})/).slice(1);
						formattedEndTime =
							`${endYear}/${endMonth.padStart(2, '0')}/${endDay.padStart(2, '0')} ${endTime}`;
					}

					// 拼接成新的 time 字段
					item.time = `${formattedStartTime} - ${formattedEndTime}`;
				});
				
				let params = {}
				let url = ''
				if (this.disable) {
					url = '/api/school.worker.classes/add'
					params = {
						classes_num: this.form.classes_num,
						status: this.form.status,
						teacher_id: this.form.teacher_id,
						classes_type: this.form.classes_type,
						classes_cate_ids: this.form.classes_cate_ids.join(','),
						classes_label_ids: this.form.classes_label_ids.join(','),
						self_label_tag: this.form.self_label_tag,
						title: this.form.title,
						headimage: this.list1,
						images: this.list2,
						type: this.form.type == '室内' ? 'in' : 'out',
						// weigh:0,
						address_type: this.form.address_type == '机构内授课' ? 1 : 2,
						province: '410000',
						city: '410300',
						content: this.form.content,
						notice: this.form.notice,
						price: this.form.price,
						selfhot: this.form.selfhot == '是' ? '1' : 0,
						address_detail: this.form.address_detail,
						address: this.form.address,
						longitude: this.form.longitude,
						latitude: this.form.latitude,
						spec: JSON.stringify(this.formList),
						district: this.form.district,
					}
				} else {
					url = '/api/school.worker.classes/edit'
					params = {
						id: this.form.id,
						classes_num: this.form.classes_num,
						status: this.form.status,
						teacher_id: this.form.teacher_id,
						classes_type: this.form.classes_type,
						classes_cate_ids: this.form.classes_cate_ids.join(','),
						classes_label_ids: this.form.classes_label_ids.join(','),
						self_label_tag: this.form.self_label_tag,
						title: this.form.title,
						headimage: this.list1,
						images: this.list2,
						type: this.form.type == '室内' ? 'in' : 'out',
						// weigh:0,
						address_type: this.form.address_type == '机构内授课' ? 1 : 2,
						province: '410000',
						city: '410300',
						content: this.form.content,
						notice: this.form.notice,
						price: this.form.price,
						selfhot: this.form.selfhot == '是' ? '1' : 0,
						address_detail: this.form.address_detail,
						address: this.form.address,
						longitude: this.form.longitude,
						latitude: this.form.latitude,
						spec: JSON.stringify(this.formList),
						district: this.form.district,
					}
					
				}
				
				uni.$u.http.post(url, params).then(res => {
					if (res.code == 1) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000,
							complete: function() {
								setTimeout(function() {
									uni.navigateBack(1)
								}, 2000);
							}
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.w-100 {
		width: 100%;
	}

	.flex {
		display: flex;
	}

	.flex-start {
		align-items: flex-start;
	}

	.justify-center {
		justify-content: center;
	}

	.align-items {
		align-items: center;
	}

	.flex-column {
		flex-flow: column;
	}

	.justify-start {
		justify-content: start;
	}

	.line {
		margin-top: 12rpx;
		width: 690rpx;
		height: 1rpx;
		background: #008CFF;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
	}

	.hui {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #343434;
	}

	.box {
		width: 750rpx;
		background-color: #F1F2F8;

		.first {
			width: 642rpx;
			padding: 32rpx 24rpx 24rpx 24rpx;
			background: #FFFFFF;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			margin-top: 42rpx;

			.row {
				width: 642rpx;
				margin-top: 7rpx;
				justify-content: space-between;

				.label {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #343434;
					line-height: 32rpx;
				}

				.row-right {}
			}

			.line-row {
				margin-top: 25rpx;
				width: 642rpx;
				height: 1rpx;
				background: #F1F2F8;
				border-radius: 0rpx 0rpx 0rpx 0rpx;
			}
		}

	}

	.second {
		margin-top: 42rpx;
		width: 642rpx;
		padding: 32rpx 24rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;

		.se-title {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 42rpx;
			color: #343434;
			align-self: self-start;
		}

		.secondList {
			margin-top: 49rpx;

			.content {
				width: 588rpx;
				border-radius: 20rpx 20rpx 20rpx 20rpx;
				border: 1rpx solid #C0C0C0;
				padding: 32rpx 24rpx 24rpx 24rpx;
				margin-bottom: 42rpx;

				.row {
					width: 100%;
					margin-top: 7rpx;
					justify-content: space-between;

					.label {
						font-family: PingFang SC, PingFang SC;
						font-weight: 500;
						font-size: 28rpx;
						color: #343434;
						line-height: 32rpx;
					}

					.row-right {}
				}

				.line-row {
					margin-top: 25rpx;
					width: 642rpx;
					height: 1rpx;
					background: #F1F2F8;
					border-radius: 0rpx 0rpx 0rpx 0rpx;
				}

				.del {
					width: 588rpx;
					height: 80rpx;
					border-radius: 401rpx 401rpx 401rpx 401rpx;
					border: 2rpx solid #FF6767;
					font-family: PingFang SC, PingFang SC;
					font-weight: 800;
					font-size: 34rpx;
					color: #FF6767;
					letter-spacing: 28rpx;
					margin-top: 75rpx;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}

		.add {
			width: 642rpx;
			height: 80rpx;
			background: #008CFF;
			border-radius: 401rpx 401rpx 401rpx 401rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 800;
			font-size: 34rpx;
			color: #FFFFFF;
			letter-spacing: 28rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

	}

	.trend {
		width: 642rpx;
		padding: 32rpx 24rpx 24rpx 24rpx;
		margin-top: 42rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #343434;

		.row {
			width: 100%;
			// margin-top: 7rpx;
			justify-content: space-between;

			.label {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #343434;
				line-height: 32rpx;
			}

			.row-right {}
		}
	}

	.four {
		width: 642rpx;
		padding: 32rpx 24rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin-top: 32rpx;

		.class_type {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #343434;
			display: flex;
			align-self: self-start;
		}

		.line-row {
			margin-top: 25rpx;
			width: 642rpx;
			height: 1rpx;
			background: #F1F2F8;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
		}
	}

	.third {
		width: 690rpx;

		.header {
			margin: 42rpx 0 24rpx 0;

			.swiper {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #343434;
			}

			.tips {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #C0C0C0;
				margin-top: 8rpx;
			}

		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		width: 750rpx;
		height: 122rpx;
		z-index: 99;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 12rpx 0rpx rgba(111, 190, 255, 0.1);

		span {
			width: 306rpx;
			height: 80rpx;

		}

		.cancel {
			border-radius: 401rpx 401rpx 401rpx 401rpx;
			border: 2rpx solid #008CFF;
			font-family: PingFang SC, PingFang SC;
			font-weight: 800;
			font-size: 34rpx;
			color: #008CFF;
			letter-spacing: 28rpx;
		}

		.pass {
			background: #008CFF;
			border-radius: 401rpx 401rpx 401rpx 401rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 800;
			font-size: 34rpx;
			color: #FFFFFF;
			letter-spacing: 28rpx;
		}
	}

	.input {
		text-align: right;
		font-family: PingFang SC, PingFang SC;
		font-size: 28rpx;
		color: #343434;
		line-height: 32rpx;
	}

	::v-deep.plasty {
		text-align: right;
		font-family: PingFang SC, PingFang SC;
		font-size: 28rpx;
	}
</style>