<template>
	<view class="container uni-container">
		<view class=" flex  flex-direction width100">
			<text class="text-xl font-weight-700">任务介绍</text>
			<!-- <view class="">
				任务介绍
			</view> -->
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<u--form ref="uForm" :model="formData" labelPosition="left" labelWidth="70" labelAlign="right">
				<u-form-item label="任务名称" prop="name" ref="item1">
					<text class="text-cut padding-sm">{{formData.name}}</text>
				</u-form-item>
				<u-form-item label="发布单位" prop="unit" ref="item1">
					<text class="text-cut padding-sm"> {{formData.unit}}</text>
				</u-form-item>
				<u-form-item label="时间" prop="starttime" ref="item1">
					<text class="text-cut padding-sm"> {{formData.starttime}}--{{formData.endtime}}</text>
				</u-form-item>
				<u-form-item label="状态" prop="status" ref="item1">
					<text class="text-cut padding-sm"
						:style="{color:(formData.status==='0'||formData.status==='3'?'red':formData.status==='1'?'green':'blue')}">
						{{statusListTran(formData.status)}}</text>
				</u-form-item>
				<u-form-item label="任务描述" prop="introduction" ref="item1">
					<text class="  padding-sm"> {{formData.introduction}}</text>
				</u-form-item>
				<text class="text-xl text-black font-weight-700">任务完成详情</text>
				<u-form-item label="结果描述" prop="resultdescription" ref="item1">
					<text v-if="formData.status=='1'||formData.status=='2'" class="  padding-sm">
						{{formData.resultdescription}}</text>
					<u--textarea v-if="formData.status=='0'||formData.status=='3'" v-model="formData.resultdescription"
						placeholder="请输入内容" count height="100">
					</u--textarea>
				</u-form-item>
				<u-form-item label="附件" prop="sex" ref="item1">
					<u-album v-if="formData.status=='1'||formData.status=='2'" :urls="formData.img"></u-album>
					<u-upload v-if="formData.status=='0'||formData.status=='3'" :fileList="fileList1"
						@afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10"></u-upload>
				</u-form-item>
				<!-- 	<u-form-item label="附件" prop="sex" ref="item1" >
					<u-upload ref="uUpload" :action="action" :auto-upload="true" :file-list="listImg"
						@on-remove="onRemove" @on-success="onSuccess" :max-size="2 * 1024 * 1024" max-count="9"
						width="300" height="300" :multiple="false" :limitstatus="limitstatus"></u-upload>
					
				</u-form-item> -->
			</u--form>
			<!-- 审核时不通过时提交 -->
			<view class="position-fixed">
				<u-button v-if="formData.status=='3'" shape="circle" size="small" color="#2563EB" text="确认提交"
				customStyle="margin-top: 50px" @click="submit">
			</u-button>
			</view>
			
			<!-- 待完成任务 提交 -->
			<view class="position-fixed">
				<uni-row :gutter="20" v-if="formData.status=='0'">
				<uni-col :span="12">
					<u-button @click="submit" shape="circle" size="small" color="#2563EB" text="确认提交"></u-button>
				</uni-col>
				<uni-col :span="12">
					<!-- <u-modal  :show="show" :title="title" :content='content' :asyncClose="true" @cancel="cancel" @confirm="confirm" :showCancelButton='true' :showConfirmButton='true'></u-modal> -->
					<u-button @click="errorSubmit" shape="circle" size="small" color="#ff7980" text="生成隐患"></u-button>
				</uni-col>
			</uni-row>
			</view>
			
		</view>
	</view>
</template>
<script>
	import config from '@/config'
	import {
		getTaskDetails,
		getTaskSubmit,
		getTaskErrorsubmit,
	} from "@/api/task";
	import {
		uploadAvatar
	} from "@/api/system/user"
	import {
		getTasDetails
	} from "@/api/task";
	let that = null;
	const baseUrl = config.baseUrl + config.baseApi;
	export default {
		data() {
			return {
				statusList: {
					0: "未完成",
					1: "已完成",
					2: "审核中",
					3: "审核未通过"
				},
				// 自定义表单数据
				formData: {
					id: '',
					name: '',
					unit: '',
					starttime: '',
					endtime: '',
					status: '',
					introduction: '',
					resultdescription: '',
					img: [],
				},
				fileList1: [],
				limitstatus: ['png', 'jpg', 'jpeg'], // 允许的图片后缀 
				rules: {
					name: [{
						status: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}, {
						min: 2,
						max: 12,
						message: '长度在2-12个字符之间'
						// // 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
						// validator: (rule, value, callback) => {
						// 	// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
						// 	return uni.$u.test.chinese(value);
						// },
						// message: "姓名必须为中文",
						// // 触发器可以同时用blur和change，二者之间用英文逗号隔开
						// trigger: ["change", "blur"],
					}],
					code: {
						status: 'string',
						required: true,
						len: 4,
						message: '请填写4位验证码',
						trigger: ['blur']
					},
				},
			}
		},
		computed: {},
		//目的页面接收
		//这里用onshow()也可以
		onLoad(options) {
			var data = options.id;
			this.getData(data)
		},
		// onLoad: function(option) {
		// 	that = this;
		// 	const eventChannel = this.getOpenerEventChannel();
		// 	// eventChannel.emit('acceptDataFromOpenedPage', {
		// 	// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
		// 	eventChannel.on('acceptDataFromOpenerPage', function(val) {
		// 		that.getData(val.id)
		// 	})
		// },
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			// console.log('this.$refs.uForm', this.$refs.uForm);
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			// =================数据转换==================
			statusListTran(val) { //status状态转换
				return this.statusList[val]
			},
			// =============获取数据===================s
			// 获取数据
			getData(id) {
				this.loading = true
				getTaskDetails({
					id: id
				}).then(response => {
					// 为数据赋值：通过展开运算符的形式，进行新旧数据的拼接 
					this.formData = response.data
					this.loading = false;
				});
			},
			// ==============照片处理=================
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				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
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				let data = {
					name: 'avatarFile',
					filePath: url
				}
				return uploadAvatar(data).then(response => {
					uni.showToast({
						title: "成功",
						icon: 'success'
					})
				})
				// return new Promise((resolve, reject) => {
				// 	let a = uni.uploadFile({
				// 		url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
				// 		filePath: url,
				// 		name: 'file',
				// 		formData: {
				// 			user: 'test'
				// 		},
				// 		success: (res) => {
				// 			setTimeout(() => {
				// 				resolve(res.data.data)
				// 			}, 1000)
				// 		}
				// 	});
				// })
			},
			// ==============照片处理结束==================
			// ==============提交================================
			// 待完成任务提交
			submit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true  
				this.$refs.uForm.validate().then(res => {
					getTaskSubmit(this.formData).then(response => {
						uni.showLoading({
							title: response.data.msg
						});
						setTimeout(() => {
							uni.hideLoading();
							this.$tab.navigateTo('/pagesA/fire/check_tasks/index')
						}, 2000);
					});
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			// 隐患提交
			errorSubmit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.uForm.validate().then(res => {
					getTaskErrorsubmit(this.formData).then(response => {
						uni.showLoading({
							title: response.data.msg
						});
						setTimeout(() => {
							uni.hideLoading();
							this.$tab.navigateTo('/pagesA/fire/check_tasks/index')
						}, 2000);
					});
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
		}
	}
</script>
<style lang="scss">
	/deep/ .u-form-item__body {
		padding: 5rpx 0rpx;
	}

	/deep/ .u-form-item {
		font-size: 13px;
	}
</style>
