<template>
	<view class="workorderlist">
		<!-- 输入框示例 -->
		<uni-popup ref="titleInputDialog" type="dialog">
			<uni-section title="" subTitle="请简短描述您遇到的问题" type="line" padding>
				<uni-easyinput maxlength="100" type="textarea" style="width: 600rpx;" v-model="title"
					placeholder="请简单描述您遇到的问题(100字以内)"></uni-easyinput>
				<view class="example-body">
					<uni-file-picker ref="files" @select="selectFile" @delete="deleteFile" :auto-upload="false"
						limit="3" title="最多选择3张图片"></uni-file-picker>
				</view>
				<button class="nextButton" @click="creatNew()" :disabled="submitDisabled">提交工单</button>
			</uni-section>

		</uni-popup>
		<view class="top">
			<button size="mini" plain="true" class="addbutton" @click="creatClick()">创建工单</button>
		</view>
		<uni-list v-if="orderList.length>0" id="container">
			<uni-list-item v-for="(item,index) in orderList" :key="index" link
				:to="`/pages/chat/detail?id=${item.id}`" :title="item.title"
				:note="item.msg!=null?item.msg.content:'未留言'">
				<template v-slot:footer>
					<view class="right">
						<view style="text-align: center;">
							<uni-tag v-if="item.status==1" text="未处理" type="primary" inverted></uni-tag>
							<uni-tag v-if="item.status==2" text="处理中" type="warning" inverted></uni-tag>
							<uni-tag v-if="item.status==3" text="完结" type="default" inverted></uni-tag>
						</view>
						<view class="time">{{item.created_at}}</view>
					</view>
				</template>
			</uni-list-item>

		</uni-list>
		<view v-else class="tishi" style="padding-top: 40rpx;">
			欢迎使用工单
		</view>

	</view>
</template>
<script setup>
	import {
		ref,
		onMounted,
		watch
	} from "vue"
	import {
		WorkOrderList,
		UpFileUrl,WorkOrderSave
	} from "@/api"
	import { useRouter } from 'vue-router';
	const router = useRouter();
	let submitDisabled=ref(false);
	let IncompleteCount = ref(0)
	
	watch(
	      () => router.currentRoute.value,
	      (to, from) => {
	        // 在每次路由变化时执行的逻辑
	        // 执行你的方法
	       GetList()
	      }
	    );
	let orderList = ref([])
	const GetList = () => {
		WorkOrderList().then(res => {
			if (res.status) {
				orderList.value = res.data.list
				IncompleteCount.value =  res.data.incompleteCount
			}
		})
	}
	let title = ref('')
	let titleInputDialog = ref(null)
	//点击右上角新建按钮
	const creatClick = () => {
		submitDisabled.value=false
		filelist.value = []
		successUpfileList.value = []
		if (IncompleteCount.value == 0) {
			title.value = ''
			titleInputDialog.value.open()
		} else {
			uni.showToast({
				title: "存在未关闭工单，请先关闭，再创建新工单",
				duration: 2000,
				icon: 'none'
			});
			return false
		}

	}
	let files = ref(null)
	
	//如果上传图片了，先提交图片，成功后在提交数据。如果没图片则直接提交
	const creatNew = async () => {
		if (title.value == '') {
			uni.showToast({
				title: "请简短描述需求",
				duration: 1500,
				icon: 'none'
			});
			return false
		}
			submitDisabled.value=true
		uni.showLoading({
			title: '加载中'
		});
	 
	 if(filelist.value.length>0){
		 filelist.value.forEach((v,i)=>{
			 upFile(v)
		 })
	 }else{
		 submit()
	 }
	}
	 
	const submit = () => { //提交全部数据
		 WorkOrderSave({title:title.value,imgs:successUpfileList.value}).then(res => { 
		 	if (res.status) {
		 		 titleInputDialog.value.close()
				 uni.navigateTo({
				 	url: '/pages/chat/detail?id='+res.data
				 })
		 	}
		 })
	}

	//选择文件后
	let filelist = ref([])
	let successUpfileList = ref([])
	
	const selectFile = (e) => {
		filelist.value.push(e.tempFilePaths[0])
		console.log(filelist.value)
	}
	const deleteFile = (e) => {
		console.log(e)
		const index = filelist.value.indexOf(e.tempFilePath); // 查找元素 3 的索引
		if (index !== -1) {
			filelist.value.splice(index, 1); // 删除索引为 index 的元素
		}

	}
	//上传图片
	const upFile =  (e) => {
		 uni.uploadFile({
			url: UpFileUrl(), //仅为示例，非真实的接口地址
			filePath: e,
			name: 'file',
			header: {
				Authorization: 'Bearer ' + sessionStorage.getItem("access_token")
			},
			success: (uploadFileRes) => {
				
				let res=JSON.parse(uploadFileRes.data);
				console.log(res);
				successUpfileList.value.push(res.data)
				console.log('-----',successUpfileList.value);
				if(successUpfileList.value.length==filelist.value.length){
					submit()
				}
			},
			fail: (err) => {
				console.log(err);
			}
		})

	}
	onMounted(() => {
		GetList()
	})
</script>

<style scoped>
	.time {
		font-size: 20rpx;
		color: #CCC;
		margin-top: 20rpx;
	}

	.workorderlist {
		background-color: #fcfcfc;
		height: 100vh;
	}

	.top {
		width: 100%;
		text-align: right;
		padding-top: 20rpx;
	}

	.addbutton {
		margin-right: 20rpx;
		background-color: #35c6c6;
		color: #fff;
		border: 1px solid #fff;
		margin-bottom: 10rpx;
	}

	.tishi {
		text-align: center;
		font-size: 20rpx;
		color: #ccc;
	}

	.nextButton {
		background-color: #35c6c6;
		height: 60rpx;
		line-height: 60rpx;
		color: #fff;
		font-size: 24rpx;
		margin-top: 20rpx;
	}
</style>