<template>
	<view class="main">
		<view class="toptitle">
			<view class="toptitle_left" @click="ht">
				<u-icon name="arrow-left" color="#fff" size="20"></u-icon>
			</view>
			<view class="toptitle_title">
				用户反馈
			</view>
		</view>
		<view class="" style="padding: 10px;background-color: #fff;border-radius: 5px;margin-bottom: 10px;">
			<u-subsection :list="list" fontSize="14" activeColor="#0052D8" :current="current"
				@change='change'></u-subsection>
		</view>
		<view class="" style="padding: 10px;border-radius: 5px;background-color: #fff;" v-if="current == 1">
			<view class="" @click="gxgnshow = true"
				style="display: flex;justify-content: space-between;align-items: center;border-bottom: 1px dashed #ccc;padding: 10px;">
				<span>问题分类</span>
				<!-- <u--input inputAlign="right" placeholder="请输入内容" border="none" v-model="form2.title"></u--input> -->
				<span>{{form1.qxgn}}</span>
			</view>
			<u-picker @cancel="gxgnshow = false" :show="gxgnshow" @confirm="gxgnconfirm" :columns="columns"></u-picker>
			<view class="" style="padding: 10px;border-bottom: 1px dashed #ccc;">
				<view style="margin-bottom: 8px;">问题描述</view>
				<textarea v-model="form1.nr" placeholder="请输入问题描述" class="yhfk-textarea" auto-height />
			</view>
			<view class=""
				style="display: flex;justify-content: space-between;align-items: center;border-bottom: 1px dashed #ccc;padding: 10px;">
				<span>对接人员</span>
				<uni-data-picker placeholder="请选择对接人员" popup-title="请选择对接人员" :localdata="dataTree" v-model="classes1"
					@change="onchange1" @nodeclick="onnodeclick" @popupopened="onpopupopened" @popupclosed="onpopupclosed">
				</uni-data-picker>
			</view>
			<view class="" style="padding: 10px;border-bottom: 1px dashed #ccc;">
				<view style="margin-bottom: 10px;">问题截图</view>
				<u-upload uploadIcon="photo" :fileList="fileList1" @afterRead="afterRead1" @delete="deletePic1" name="1" multiple
					:maxCount="10"></u-upload>
			</view>
			<view class="" style="padding: 10px;">
				<view style="margin-bottom: 10px;">问题视频</view>
				<u-upload uploadIcon="camera" accept="video" :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic2" name="1" multiple
					:maxCount="10"></u-upload>
			</view>
			<view class="" @click="tjxtwt">
				<button type="primary">提交</button>
				<!-- <u-button type="primary" text="提交"></u-button> -->
			</view>
		</view>
		<view class="" style="padding: 10px;border-radius: 5px;background-color: #fff;" v-if="current == 0">
			<view class=""
				style="display: flex;justify-content: space-between;align-items: center;border-bottom: 1px dashed #ccc;padding: 10px;">
				<span>问题设备</span>
				<u--input inputAlign="right" placeholder="请输入内容" border="none" v-model="form2.title"></u--input>
			</view>
			<view class="" style="padding: 10px;border-bottom: 1px dashed #ccc;">
				<view style="margin-bottom: 8px;">问题描述</view>
				<textarea v-model="form2.nr" placeholder="请输入问题描述" class="yhfk-textarea" auto-height />
			</view>
			<view class=""
				style="display: flex;justify-content: space-between;align-items: center;border-bottom: 1px dashed #ccc;padding: 10px;">
				<span>对接人员</span>
				<uni-data-picker placeholder="请选择对接人员" popup-title="请选择对接人员" :localdata="dataTree" v-model="classes"
					@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened" @popupclosed="onpopupclosed">
				</uni-data-picker>
			</view>
			<view class="" style="padding: 10px;border-bottom: 1px dashed #ccc;">
				<view style="margin-bottom: 10px;">截图</view>
				<u-upload uploadIcon="photo" :fileList="fileList3" @afterRead="afterRead3" @delete="deletePic3" name="1" multiple
					:maxCount="10"></u-upload>
			</view>
			<view class="" style="padding: 10px;">
				<view style="margin-bottom: 10px;">视频</view>
				<u-upload uploadIcon="camera" accept="video" :fileList="fileList4" @afterRead="afterRead4" @delete="deletePic4" name="1" multiple
					:maxCount="10"></u-upload>
			</view>
			<view class="" @click="tjsbfk">
				<button type="primary">提交</button>
				<!-- <u-button type="primary" text="提交"></u-button> -->
			</view>
			
		</view>
		<view class="" style="position: absolute;bottom: 170rpx;right: 40rpx;" @click="tzfk">
			
			<image style="width: 80rpx;height: 80rpx;" src="/static/xxicon.png" mode=""></image>
		</view>
		<view v-if="xxtsvalue > 0" class="" style="position: absolute;bottom: 230rpx;right: 20rpx;z-index: 999;">
			<u-badge :type="xxtstype" max="99" :value="xxtsvalue"></u-badge>
		</view>
	</view>
</template>

<script>
	export default {

		data() {
			return {
				gxgnshow:false,
				columns:[[]],
				// 问题分类字典类型ID（与 migrations 中一致）
				QXGN_DICT_TYPE_ID: '626798200000000001',
				xxtstype:"error",
				xxtsvalue: 0,
				classes1:"",
				classes: '',
				dataTree: [],
				
				keyword: "",
				show: false,
				list: ['设备问题反馈','系统问题反馈'],
				current: 0,
				title: "关键词",
				// 
				base_url: "https://hhjj.antissoft.com/api/file/Uploader/annex",
				fileList1: [],
				fileList2: [],
				fileList3: [],
				fileList4: [],
				form1: {
					title: "",
					nr: "",
					fj1: [], // 视频附件
					fj2: [], // 图片附件
					clr:"",
					fbr:"",
					fbsj:"",
					qxgn:"请选择"
				},
				form2: {
					"title": "",
					"nr": "",
					"sbmc": "",
					"shry": "",
					"shdh": "",
					"shyx": "",
					"clr":"",
					"fj1": [], // 视频附件
					"fj2": [], // 图片附件
					"fbr":"",
					"fbsj":""
				},
				userInfo:{},
			}
		},
		onLoad() {
			this.fkuser();
			this.hquserxx();
			this.hqxtwdnumber();
			this.loadQxgnOptions();
		},
		methods: {
			// 从后台字典加载问题分类选项
			loadQxgnOptions() {
				this.API.hqcpfl(this.QXGN_DICT_TYPE_ID).then(res => {
					const list = (res.list || []).filter(d => d && d.fullName)
					this.columns = [list.map(d => d.fullName)]
					if (this.columns[0].length === 0) {
						this.columns = [['系统缺陷', '功能缺失', '显示异常', '优化建议', '功能新增']]
					}
				}).catch(() => {
					this.columns = [['系统缺陷', '功能缺失', '显示异常', '优化建议', '功能新增']]
				})
			},
			// 获取系统未读数量（系统问题+设备问题）
			hqxtwdnumber(){
				var user = uni.getStorageSync('userinfo') || {};
				var id = user.userId || user.id || '';
				if (!id) return;
				var info = { id };
				var num = 0;
				this.API.hqxtwdnumber(info).then(res=>{
					console.log("获取系统未读数量",res);
					num = num + (res.data?.unreadCount || 0);
					this.API.hqsbwtwdnumber(info).then(res1=>{
						console.log("获取设备问题未读数量",res1);
						num = num + (res1.data?.unreadCount || 0);
						this.xxtsvalue = num;
					})
				})
			},
			gxgnconfirm(e){
				this.gxgnshow = false
				this.form1.qxgn = e.value[0]
				console.log("1",e);
			},
			tzfk(){
				uni.navigateTo({
					url:"/pages/new/yhfk/fkhf"
				})
			},
			hquserxx(){
				this.API.hqdqdlrxx().then(res=>{
					console.log("用户信息",res);
					this.userInfo = res.data.userInfo
				})
			},
			onchange(e){
				console.log("onchange",e);
				if(e.detail.value.length  == 1){
					this.form2.clr = e.detail.value[0].text
				}
				if(e.detail.value.length  == 0){
					this.form2.clr = ''
				}
			},
			onchange1(e){
				console.log("onchange",e);
				if(e.detail.value.length  == 1){
					this.form1.clr = e.detail.value[0].text
				}
				if(e.detail.value.length  == 0){
					this.form1.clr = ''
				}
			},
			onpopupclosed(e){
				console.log("onpopupclosed",e);
			},
			onpopupopened(e){
				console.log("onpopupopened",e);
			},
			onnodeclick(e){
				console.log("onnodeclick",e);
			},
			fkuser(){
				var info = {
					currentPage:1,
					pageSize:20
				}
				var arr = []
				this.API.fkuser(info).then(res=>{
					console.log("获取反馈人员列表",res);
					if(res.data.list.length > 0){
						for(let i = 0;i < res.data.list.length;i++){
							var info = {
								text:res.data.list[i].xm,
								value:res.data.list[i].id,
								children:[]
							}
							arr.push(info)
						}
					}
					this.dataTree = arr
				})
			},
			ht() {
				uni.navigateBack({
					delta: 1
				});
			},
			change(e) {
				this.current = e
			},
			tjsbfk() {
				this.form2.fbr = this.userInfo.userId
				
				if(this.form2.clr == ''){
					uni.showToast({
						icon:"error",
						title:"请选择联系人"
					})
					return
				}
				if(this.form2.title == ''){
					uni.showToast({
						icon:"error",
						title:"请输入设备名"
					})
					return
				}
				if(this.form2.nr == ''){
					uni.showToast({
						icon:"error",
						title:"请输入故障信息"
					})
					return
				}
				
				// 检查是否有文件正在上传
				const uploadingFiles3 = this.fileList3.filter(file => file.status === 'uploading');
				const uploadingFiles4 = this.fileList4.filter(file => file.status === 'uploading');
				if (uploadingFiles3.length > 0 || uploadingFiles4.length > 0) {
					uni.showToast({
						icon: "none",
						title: "请等待文件上传完成"
					});
					return;
				}
				
				// 清空附件数组，避免重复添加
				this.form2.fj1 = []
				this.form2.fj2 = []
				
				// fileList3 是图片，应该放到 fj2
				if (this.fileList3.length > 0) {
					for (let i = 0; i < this.fileList3.length; i++) {
						const file = this.fileList3[i];
						// 只处理上传成功的文件
						if (file.status === 'success' && file.url) {
							var info = {
								name: file.name || '图片',
								fileId: file.fileId || "",
								url: file.url,
							}
							this.form2.fj2.push(info)
							console.log("添加图片附件:", info);
						} else {
							console.warn("跳过未上传成功的图片:", file);
						}
					}
				}
				// fileList4 是视频，应该放到 fj1
				if (this.fileList4.length > 0) {
					for (let i = 0; i < this.fileList4.length; i++) {
						const file = this.fileList4[i];
						// 只处理上传成功的文件
						if (file.status === 'success' && file.url) {
							var info = {
								name: file.name || '视频',
								fileId: file.fileId || "",
								url: file.url,
							}
							this.form2.fj1.push(info)
							console.log("添加视频附件:", info);
						} else {
							console.warn("跳过未上传成功的视频:", file);
						}
					}
				}
				
				console.log("提交设备问题反馈数据:", JSON.stringify(this.form2, null, 2));
				console.log("fileList3 原始数据:", this.fileList3);
				console.log("fileList4 原始数据:", this.fileList4);
				console.log("图片附件数量:", this.form2.fj2.length);
				console.log("视频附件数量:", this.form2.fj1.length);
				
				this.API.sbwtfk(this.form2).then(res => {
					console.log("提交成功", res);
					uni.showToast({
						icon: "success",
						title: "提交成功"
					})
					this.form2 = {
						"title": "",
						"nr": "",
						"sbmc": "",
						"shry": "",
						"shdh": "",
						"shyx": "",
						"clr":"",
						"fj1": [],
						"fj2": []
					}
					this.fileList3 = []
					this.fileList4 = []
					this.classes1 = ""
					this.classes = ""
				}).catch(err => {
					console.error("提交失败:", err);
					uni.showToast({
						icon: "error",
						title: "提交失败，请重试"
					})
				})
			},
			tjxtwt() {
				this.form1.fbr = this.userInfo.userId
				if(this.form1.nr == ''){
					uni.showToast({
						icon:"error",
						title:"请输入问题"
					})
					return
				}
				if(this.form1.clr == ''){
					uni.showToast({
						icon:"error",
						title:"请选择联系人员"
					})
					return
				}
				
				// 检查是否有文件正在上传
				const uploadingFiles1 = this.fileList1.filter(file => file.status === 'uploading');
				const uploadingFiles2 = this.fileList2.filter(file => file.status === 'uploading');
				if (uploadingFiles1.length > 0 || uploadingFiles2.length > 0) {
					uni.showToast({
						icon: "none",
						title: "请等待文件上传完成"
					});
					return;
				}
				
				// 清空附件数组，避免重复添加
				this.form1.fj1 = []
				this.form1.fj2 = []
				
				// fileList1 是图片，应该放到 fj2
				if (this.fileList1.length > 0) {
					for (let i = 0; i < this.fileList1.length; i++) {
						const file = this.fileList1[i];
						// 只处理上传成功的文件
						if (file.status === 'success' && file.url) {
							var info = {
								name: file.name || '图片',
								fileId: file.fileId || "",
								url: file.url,
							}
							this.form1.fj2.push(info)
							console.log("添加图片附件:", info);
						} else {
							console.warn("跳过未上传成功的图片:", file);
						}
					}
				}
				// fileList2 是视频，应该放到 fj1
				if (this.fileList2.length > 0) {
					for (let i = 0; i < this.fileList2.length; i++) {
						const file = this.fileList2[i];
						// 只处理上传成功的文件
						if (file.status === 'success' && file.url) {
							var info = {
								name: file.name || '视频',
								fileId: file.fileId || "",
								url: file.url,
							}
							this.form1.fj1.push(info)
							console.log("添加视频附件:", info);
						} else {
							console.warn("跳过未上传成功的视频:", file);
						}
					}
				}
				
				console.log("提交系统问题反馈数据:", JSON.stringify(this.form1, null, 2));
				console.log("fileList1 原始数据:", this.fileList1);
				console.log("fileList2 原始数据:", this.fileList2);
				console.log("图片附件数量:", this.form1.fj2.length);
				console.log("视频附件数量:", this.form1.fj1.length);
				
				this.API.xtwtfk(this.form1).then(res => {
					console.log("提交成功", res);
					uni.showToast({
						icon: "success",
						title: "提交成功"
					})
					this.form1 = {
						title: "",
						nr: "",
						fj1: [],
						fj2: [],
						qxgn: "请选择"
					}
					this.fileList1 = []
					this.fileList2 = []
					this.classes1 = ""
					this.classes = ""
				}).catch(err => {
					console.error("提交失败:", err);
					uni.showToast({
						icon: "error",
						title: "提交失败，请重试"
					})
				})
			},
			// 上传系统反馈图片
			async afterRead1(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList1.length
				lists.map((item) => {
					this.fileList1.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					try {
						var result = await this.uploadFilePromise(lists[i].url)
						result = JSON.parse(result)
						console.log("图片上传成功:", result);
						let item = this.fileList1[fileListLen]
						this.fileList1.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							name: result.data.name,
							url: result.data.url
						}))
						fileListLen++
					} catch (error) {
						console.error("图片上传失败:", error);
						let item = this.fileList1[fileListLen]
						this.fileList1.splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败'
						}))
						fileListLen++
					}
				}
			},
			deletePic1(event) {
				this.fileList1.splice(event.index, 1)
			},
			async afterRead2(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList2.length
				lists.map((item) => {
					this.fileList2.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					try {
						var result = await this.uploadFilePromise(lists[i].url)
						result = JSON.parse(result)
						console.log("视频上传成功:", result);
						let item = this.fileList2[fileListLen]
						this.fileList2.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							name: result.data.name,
							url: result.data.url
						}))
						fileListLen++
					} catch (error) {
						console.error("视频上传失败:", error);
						let item = this.fileList2[fileListLen]
						this.fileList2.splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败'
						}))
						fileListLen++
					}
				}
			},
			deletePic2(event) {
				this.fileList2.splice(event.index, 1)
			},
			async afterRead3(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList3.length
				lists.map((item) => {
					this.fileList3.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					try {
						var result = await this.uploadFilePromise(lists[i].url)
						result = JSON.parse(result)
						console.log("图片上传成功:", result);
						let item = this.fileList3[fileListLen]
						this.fileList3.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							name: result.data.name,
							url: result.data.url
						}))
						fileListLen++
					} catch (error) {
						console.error("图片上传失败:", error);
						let item = this.fileList3[fileListLen]
						this.fileList3.splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败'
						}))
						fileListLen++
					}
				}
			},
			deletePic3(event) {
				this.fileList3.splice(event.index, 1)
			},
			async afterRead4(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList4.length
				lists.map((item) => {
					this.fileList4.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					try {
						var result = await this.uploadFilePromise(lists[i].url)
						result = JSON.parse(result)
						console.log("视频上传成功:", result);
						let item = this.fileList4[fileListLen]
						this.fileList4.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							name: result.data.name,
							url: result.data.url
						}))
						fileListLen++
					} catch (error) {
						console.error("视频上传失败:", error);
						let item = this.fileList4[fileListLen]
						this.fileList4.splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败'
						}))
						fileListLen++
					}
				}
			},
			deletePic4(event) {
				this.fileList4.splice(event.index, 1)
			},
			uploadFilePromise(url) {
				console.log("开始上传文件:", url);
				var that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.base_url,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test',
							token: uni.getStorageSync("token"),
						},
						success: (res) => {
							console.log("上传响应:", res);
							try {
								const result = JSON.parse(res.data);
								console.log("解析后的上传结果:", result);
								if (result && result.data && result.data.url) {
									resolve(res.data);
								} else {
									console.error("上传结果格式错误:", result);
									reject(new Error("上传结果格式错误"));
								}
							} catch (e) {
								console.error("解析上传结果失败:", e, res.data);
								reject(e);
							}
						},
						fail: (err) => {
							console.error("上传失败:", err);
							reject(err);
						}
					});
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	@import 'index.scss';

	.u-subsection--button {
		height: 50px;
	}

	.yhfk-textarea {
		width: 100%;
		min-height: 120rpx;
		padding: 16rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
</style>