<template>
	<view class="contentItem" >
		<uni-collapse>
			<uni-collapse-item title-border="none" v-for="(item,index) in listData" :key="index" :border="false"
				:show-animation="true">
				<template v-slot:title>
					<view style="display: flex;align-items: center;">
						<text class="yuandian"></text>
						<text>{{item.name}}</text>
						<text style="margin-left: auto; color:#ff0000">{{getIsItem(item.children)}}项未填写</text>
					</view>
				</template>
				<view class="xj-content">
					<view class="xj-text" v-for="(o,i) in item.children" :key="i">
						<text>{{o.itemDesc}}</text>
						<view class="subsectioin">
							<u--form labelPosition="left" :model="o" ref="uForm" label-width="80px">
								<u-form-item label="状态" prop="isNormal" borderBottom required >
									<u-subsection :list="list" :current="getNormal(o.isNormal)" mode="subsection"
										@change="(e)=>change(e,o,index,i,'isNormal')"
										style="width:150px"></u-subsection>
								</u-form-item>
								<view class="" v-if="o.isNormal==0">
									<u-form-item label="现场图片" prop="inspectPics" borderBottom required>
										<u-upload accept="image" :fileList="o.inspectPics"
											@afterRead="(e)=>afterRead(e,o,index,i)"
											@delete="(e)=>deletePic(e,o,index,i)" name="inspectPics" multiple
											:maxCount="10"></u-upload>
									</u-form-item>
									<u-form-item label="现场视频" prop="inspectVideos" borderBottom>
										<u-upload accept="video" :fileList="o.inspectVideos"
											@afterRead="(e)=>afterRead(e,o,index,i)"
											@delete="(e)=>deletePic(e,o,index,i)" name="inspectVideos" multiple
											:maxCount="10"></u-upload>
									</u-form-item>
									<u-form-item label="问题描述" prop="problemDesc" borderBottom required>
										<u--textarea v-model="o.problemDesc" placeholder="请输入内容"></u--textarea>
									</u-form-item>
									<u-form-item label="处理状态" prop="isHandle" borderBottom required>
										<u-subsection :list="listStatus" :current="getHandle(o.isHandle)"
											mode="subsection" @change="(e)=>change(e,o,index,i,'isHandle')"
											style="width:150px"></u-subsection>
									</u-form-item>
									<view class="" v-if="o.isHandle == 1">
										<u-form-item label="处理图片" prop="handlePics" borderBottom required>
											<u-upload accept="image" :fileList="o.handlePics"
												@afterRead="(e)=>afterRead(e,o,index,i)"
												@delete="(e)=>deletePic(e,o,index,i)" name="handlePics" multiple
												:maxCount="10"></u-upload>
										</u-form-item>
										<u-form-item label="处理视频" prop="handleVideos" borderBottom>
											<u-upload accept="video" :fileList="o.handleVideos"
												@afterRead="(e)=>afterRead(e,o,index,i)"
												@delete="(e)=>deletePic(e,o,index,i)" name="handleVideos" multiple
												:maxCount="10"></u-upload>
										</u-form-item>
										<u-form-item label="处理描述" prop="handleDesc" borderBottom required>
											<u--textarea v-model="o.handleDesc" placeholder="请输入内容"></u--textarea>
										</u-form-item>
									</view>
									<view class="" v-if="o.isHandle == 0">
										<u-form-item label="责任人" prop="handleUserId" borderBottom	 required>
											<uni-data-picker :localdata="treeList" popup-title="请选择责任人" v-model="o.handleUserId" 
											:border="false"
											:map="{'text':'title','value':'value'}"
											v-slot:default="{data, error, options}"
											>
											<view v-if="error" class="error">
											    <text>{{error}}</text>
											  </view>
											  <view v-else-if="data.length" class="selected">
											      <text>{{data[data.length-1].text}}</text>
											  </view>
											  <view v-else>
											    <text>请选择</text>
											</view>
												</uni-data-picker>
										</u-form-item>

									</view>
								</view>
							</u--form>
							 
						</view>
						
					</view>
				</view>
			</uni-collapse-item>

		</uni-collapse>
		<view class="" style="display: flex;">
		 			<u-button  text="保存" customStyle="margin-top: 50px" @click="submit(1)"></u-button>
		 			<u-button type="primary" text="结束巡检" customStyle="margin-top: 50px" @click="submit(2)"></u-button>
		</view>
		
	</view>
</template>

<script>
	export default {
		props: {
			xjItem: Array
		},
		data() {
			return {
				list: ["异常","正常", ],
				listStatus: ["未处理","已处理"],
				current: 0,
				listData: [],
				showSex: false,
				treeList:[],
				deptUserList:[],
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},
					{
						name: '保密',
					},
				],
			}
		},
		mounted() {
			// this.listData = this.xjItem
			
			this.getTreeList()
		},
		watch: {
			xjItem: function(n, o) {

				this.listData = n.map(item => {
					item.childen = item.children.map(i => {
						
						i.handlePics?.map(item1=>{
							item1.url ='http://223.75.53.141:9102/test.by-lyf.tmp' + item1.filePath 
							return item1
						})
						i.handleVideos?.map(item1=>{
							item1.url ='http://223.75.53.141:9102/test.by-lyf.tmp' + item1.filePath 
							return item1
						})
						i.inspectPics?.map(item1=>{
							item1.url ='http://223.75.53.141:9102/test.by-lyf.tmp' + item1.filePath 
							return item1
						})
						i.inspectVideos?.map(item1=>{
							item1.url ='http://223.75.53.141:9102/test.by-lyf.tmp' + item1.filePath 
							return item1
						})
						if (!i.handlePics) {
							i.handlePics = []
						}
						if (!i.handleVideos) {
							i.handleVideos = []
						}
						if (!i.inspectPics) {
							i.inspectPics = []
						}
						if (!i.inspectVideos) {
							i.inspectVideos = []
						}
						return i
					})
					return item
				})
			}
		},
		methods: {
			nodeclick(e){
				console.log(e,'1212');
			},
			 buildTree (data, parentId)  {
			    let tree = [];
			    data.forEach((node) => {
			        node.title = node.deptName;
			        node.key = node.deptId;
			        
			        if (node.parentId === parentId) {
			        let children = this.buildTree(data, node.deptId);
			        if (children.length) {
			            node.children = children;
			        }
			        tree.push(node);
			        }
			    });
			    return tree;
			},
			handleTreeList(dept, user)  {
			    const deptArr = dept.map(item => {
			      return {
			        ...item,
			        value: item.deptId,
			        title: item.deptName,
			        disabled: item.userId ? false : true,
			        children: user.filter(u => u.deptId == item.deptId).map(u => ({
			          ...u,
			          value: String(u.userId),
			          title: u.nickName
			        }))
			      }
			    }) 
			    console.log("deptArr",deptArr);
			    const treelist = this.buildTree(deptArr,0)
			    return treelist
			  },
			async getTreeList (){
				const res = await uni.$http.get('/gunshiApp/xyt/system/dept/list')
				const resUser = await uni.$http.get('/gunshiApp/xyt/system/user/list?pageNum=1&pageSize=9999')
				this.deptUserList = resUser.data.rows
				 if (res.data.data?.length > 0 && resUser.data.rows?.length > 0) {
				        // return this.handleTreeList(res.data.data,res.data.rows)
						console.log();
						this.treeList = this.handleTreeList(res.data.data,resUser.data.rows)
				    } else {
				      // return []
					  this.treeList =[]
				}	
			},
			getIsItem(arr) {
				return arr.filter(item1 => item1.isNormal !== 1 && item1.isNormal !== 0).length
			},
			getNormal(isNormal) {
				if (isNormal == 0) {
					return 0
				}
				if (isNormal == 1) {
					return 1
				}
				if (isNormal == null) {
					return 3
				}
			},
			getHandle(isHandle) {
				if (isHandle == 0) {
					return 0
				}
				if (isHandle == 1) {
					return 1
				}
				if (isHandle == null) {
					return 3
				}
			},
			async uploadContent(status) {
				try {
					let params = {
						status: status,
						list: []
					}
					console.log(this.listData);
					this.listData.map(i => {
						const arr=i.children.map(item=>{ 
							item.handleUserName = this.deptUserList.find(it=>it.userId==item.handleUserId)?.nickName 
						
						return item
						})
						params.list=[...params.list,...arr]
					})
					console.log(params);
					const {
						data
					} = await uni.$http.post(`/gunshiApp/xyt/inspect/task/finish`, params)
					console.log(data,'2121');
					if(data.code==200){
						uni.$showMsg('提交成功');
						uni.navigateBack()
					}
				} catch (error) {
					uni.$showMsg();
				}
			},
			submit(status) {
				const timer = uni.getStorageSync('timer');
				if(timer) {
					clearInterval(timer);
					uni.removeStorageSync('timer')
				}
				let tigger = true
				let arr =[]
				//判断是否符合提交条件
				this.listData.forEach(item => {
					item.ab = item.children.filter(i => {
						if (i.isNormal == 0) {
							if (i.inspectPics?.length && i.problemDesc) {
								tigger = true
								arr.push(true)
							} else {
								tigger = false
								arr.push(false)
								uni.$showMsg(i.itemDesc+'请填写现场问题描述和上传现场照片');
							}
							if (i.isHandle == 1) {
								if (i.handlePics?.length && i.handleDesc) {
									tigger = true
									arr.push(true)
								} else {
									tigger = false
									arr.push(false)
									uni.$showMsg(i.itemDesc+'请填写处理问题描述和上传处理照片');
								}
							} else if (i.isHandle == 0) {
								console.log(i.handleUserId,'i.handleUserId');
								if(i.handleUserId){
									tigger = true
									arr.push(true)
								}else{
									tigger = false
									arr.push(false)
									uni.$showMsg(i.itemDesc+'请选择责任人');
								}
								
							}else{
								tigger = false
								arr.push(false)
								uni.$showMsg(i.itemDesc+'请选择处理状态');
							}
						} else if (i.isNormal == 1) {
							tigger = true
							arr.push(true)
						}else if(!i.isNormal){
							tigger=false
							arr.push(false)
							uni.$showMsg(i.itemDesc+'请选择正常异常状态');
						}
					})
					return item
				})
				
				if (arr.every(item=>item)) {
					console.log(tigger, arr,this.listData)
					// this.uploadContent(status)
				}else{
					
				}
				// 
				// if()
			},
			// 删除图片
			deletePic(event, o, index, index1) {
				this.listData[index].children[index1][event.name].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event, o, index, index1) {
				console.log(event, index1, this.listData[index]);
				// let file
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.listData[index].children[index1][event.name]?.length
				lists.map((item) => {
					this.listData[index].children[index1][event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name, index, index1)
					console.log(result);
					let item = this.listData[index].children[index1][event.name][fileListLen]
					this.listData[index].children[index1][event.name].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						...result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name, index, index1) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://local.gunshiiot.com:18083/gunshiApp/xyt/inspect/task/file/upload/singleSimple', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								// this.listData[index].children[index1][name].push({...res.data.data,url:res.data.data.filePath})
								console.log(res.data)
								resolve(JSON.parse(res.data).data)
							}, 1000)
						}
					});
					// resolve(a)
				})
			},
			change(e, o, index, i, key) {

				this.listData[index].children[i][key] = e;
				this.$forceUpdate()
			},
			sexSelect(e) {
				// this.model1.userInfo.sex = e.name
				// this.$refs.uForm.validateField('userInfo.sex')
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	.contentItem {
		height: 100%;
		overflow: auto;

		.itemC {
			display: flex;
			justify-content: space-between;
			display: flex;
			color: #666666;
			padding: 10px;
			border-bottom: 1px solid #f0f0f0;
		}

		.itemNo {
			color: #666666;
			padding: 10px;
		}
	}

	.circle-btn {
		width: 120px;
		height: 120px;
		background-color: #007aff;
		border-radius: 50%;
		color: #fff;
		text-align: center;
		line-height: 120px;
	}

	.yuandian {
		display: inline-block;
		width: 10px;
		height: 10px;
		background-color: #409eff;
		border-radius: 50%;
		margin-right: 10px;
	}

	.xj-content {
		// height: 300px;
		// overflow-y: auto;
	}

	.xj-text {
		margin-left: 10%;
		margin-right: 10%;
		margin-top: 2%;
	}

	.subsectioin {
		display: flex;
		column-gap: 10px;
		align-items: center;
		margin-top: 10px;
	}
</style>