<template>
	<div class="body">	
		<uni-forms ref="form" label-position="top" :rules="rules" :model="formData">
			<uni-forms-item label="预警标题" name="desc" required>
				<uni-easyinput v-model="formData.hdangerTitle" placeholder="请输入描述"></uni-easyinput>
			</uni-forms-item>	
			<uni-forms-item label="采空区" name="goafId" required>
				<uni-data-select
					v-model="formData.goafId"
					:localdata="goafList"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="预警类型" name="hdangerType" required>
				<uni-data-select :clear="false"
					v-model="formData.hdangerType"
					:localdata="hdangerTypes"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item v-if="formState!=='form_checkList'" label="检查表" name="checklistId" required>
				<uni-data-select
					v-model="formData.checklistId"
					:localdata="checkList"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="评审人" name="reviewAccountId" required>
				<view style="padding-bottom: 16rpx;">
					<uni-data-picker :map='groupMap'
					placeholder="请选择组织"
					 popup-title="请选择组织" 
					:localdata="groupList"
					@change="onchangeGroup">  
					</uni-data-picker> 					
				</view> 
				<uni-data-select
					v-model="formData.reviewAccountId"
					:localdata="userList"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="预警等级" name="hdangerLevel" required>
				<uni-data-checkbox v-model="formData.hdangerLevel" :localdata="hdangerLevels"></uni-data-checkbox>
			</uni-forms-item>							  
			<uni-forms-item label="发生时间" name="submitTime" required>
				<uni-datetime-picker
					type="datetime"
					v-model="formData.submitTime"
				/>
			</uni-forms-item>
			<uni-forms-item label="截止时间" name="dangerDeadline" required>
				<uni-datetime-picker
					type="datetime"
					v-model="formData.dangerDeadline"
				/>
			</uni-forms-item>
			<uni-forms-item label="描述" name="hdangerDesc" required>
				<uni-easyinput type="textarea" autoHeight v-model="formData.hdangerDesc" placeholder="请输入描述"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="附件">
				<div class="upload-container">
					<image @click="upload" class="upload" src="/static/icon/upload.png" mode="widthFix"></image>
					<p class="tip">注：单个附件上传不超过10M，附件累计不超过20M</p>					
				</div>
				<view class="preview" v-if="formData.attachList.length>0">
					<image class="preview-item" :src="attach.fileUrl" mode="widthFix" v-for="(attach,index) in formData.attachList" :key="index"></image>
				</view>
			</uni-forms-item>
		</uni-forms>	
		<view class="footer" @click="onSubmit">提交</view>
	</div>
</template>

<script>
	import { getGroupByList } from '@/api/system/groupApi'
	import {getUserByPage} from '@/api/user.js'
	import {upload} from '@/api/index.js'
	import { getChecklist } from '@/api/check'
	import { getGoafBaseInfo } from '@/api/goaf'
    import { startWorkflow, getWorkflowById, handleWorkflow } from '@/api/system/wfApi'
	import { handleDanger, getDangerById } from '@/api/dangerApi'
	import {parseTime,packageTreeData} from '@/libs'
	export default {
		data() {
			return {
				formData:{
					'hdangerId': undefined,
					'formCode': 'submit',
					'hdangerTitle': '', // 预警标题
					'dangerCatId': undefined, // 预警类别ID
					'hdangerLevel': 0, // 预警等级
					'hdangerDesc': '', // 描述
					'submitTime': parseTime(new Date()),
					'dangerDeadline': '', // 截止时间
					'goafId': undefined,
					'checklistId': '',
					'hdangerType':0,
					"attachList":[]
				},
				formState:undefined,
				flowData:{},
				groupList:[],
				groupMap:{text:"groupName",value:"groupId"},
				userList:[],
				checkList:[],
				goafList:[],
				hdangerTypes:[
					{"value": 0,"text": "人员巡检"	},
					{"value": 1,"text": "传感器巡检"},					
				],
				hdangerLevels:[
					{"value": 0,"text": "较低"	},
					{"value": 1,"text": "一般"},
					{"value": 2,"text": "较大"},
					{"value": 3,"text": "重大"},
				],
				rules:{
					reviewAccountId:{
						rules:[
							{
								required: true,
								errorMessage: '请选择评审人',
							},						
						],
					},
					desc:{
						rules:[
							{
								required: true,
								errorMessage: '请填写描述',
							},						
						]						
					}
				},
			}
		},
		created() {
			this.init()
		},
		methods: {
			// 启动流程
			async start(wfDefId) {
			  const { code, data, msg } = await startWorkflow(wfDefId)
			  if (code === 0) {
				this.flowData = data
				this.flowData.wfDefId = data.wfDefId
				this.flowData.wfInsId = data.wfInsId
				this.flowData.activityDefId = data.curActivityIns.activityDefId
				this.flowData.activityInsId = data.curActivityIns.activityInsId
				this.flowData.activityCode = data.curActivityIns.activityCode
				this.formData.hdangerId=data.wfInsId
				this.renderAction()
				return data.wfInsId
			  }
			},
			// 获取流程
			get(wfInsId) {
			  this.resetFormData()
			  getWorkflowById(wfInsId).then((resp) => {
				const { code, data, msg } = resp
				if (code === 0) {
				  this.flowData = data
				  this.flowData.wfDefId = data.wfDefId
				  this.flowData.wfInsId = data.wfInsId
				  this.flowData.activityDefId = data.curActivityIns.activityDefId
				  this.flowData.activityInsId = data.curActivityIns.activityInsId
				  this.flowData.activityCode = data.curActivityIns.activityCode
				  this.renderAction()
				} else {
				  this.$message.error(msg)
				}
			  })
			},
			
			init(){
				let data=uni.getStorageSync('submit-data')
				if(data){
					this.formData.checklistId = data.checklistId
					this.formData.goafId = data.goafId
					this.formData.hdangerDesc = data.checkItemNopass
					this.formData.hdangerTitle = `${data.taskTitle}未通过检查`	
					this.formState = 'form_checkList'
				}
				this.getUser()
				this.getGroup()
				this.getChecklist()
				this.getGoafBaseInfo()
				//初始化流程
				this.start(1)
			},
			getGroup(){
				getGroupByList().then((res)=>{
					let items=packageTreeData({
						data:res.data,
						id:"groupId"
					})
					this.groupList=items
				})
			},
			getUser(groupId){
				getUserByPage({
					page: 1,
					limit: 999999,
					groupId
				}).then((res)=>{
					this.userList=res.data.map(item=>{
						return{
							...item,
							value:item.accountId,
							text:item.accountName
						}
					})
				})
			},
			getChecklist(){
				getChecklist().then((res)=>{
					this.checkList=res.data.map(item=>{
						return{
							...item,
							value:item.checklistId,
							text:item.checklistTitle
						}
					})
				})
			},
			getGoafBaseInfo(){
				getGoafBaseInfo().then((res)=>{
					this.goafList=res.data.map(item=>{
						return{
							...item,
							value:item.goafId,
							text:item.goafName
						}
					})
				})				
			},
			onSubmit(){
				let user=this.userList.filter(item=>item.accountId===this.formData.reviewAccountId)[0]
				if(!this.verify()){
					return
				}
				handleWorkflow({
				    "wfDefId": this.flowData.wfDefId,
				    "wfInsId": this.flowData.wfInsId,
				    "activityDefId": this.flowData.activityDefId,
				    "activityInsId": this.flowData.activityInsId,
				    "activityCode": this.flowData.activityCode,
				    "actionId": this.flowData.actionId,
				    "actionCode": this.flowData.actionCode,
				    "actionRemark": this.flowData.hdangerDesc,
					"attachList":this.formData.attachList,
					"groupIdTo": user.groupId,
					"positionIdTo": user.positionId,
					"accountIdTo": this.formData.reviewAccountId,
					"groupNameTo": user.groupName,
					"positionNameTo": user.positionName,
					"accountNameTo": user.accountName,
				}).then((flow_resq)=>{
				  let flow=flow_resq.data
				  if (flow.curActivityCode === 'review') {
					this.formData.status = 1
				  }
				  if (flow.curActivityCode === 'rectify') {
					this.formData.status = 2
				  }
				  if (flow.curActivityCode === 'accept') {
					this.formData.status = 3
				  }
				  /**提交人*/
					let userData=uni.getStorageSync('accountInfo');
					this.formData.submitGroupId = userData.groupId
					this.formData.submitGroupName = userData.groupName
					this.formData.submitPositionId = userData.positionId
					this.formData.submitPositionName = userData.positionName
					this.formData.submitAccountId = userData.userId
					this.formData.submitAccountName = userData.userName	
				/*评审人信息*/
					this.formData.reviewRemark = this.flowData.hdangerDesc			
					this.formData.reviewAccountName = user.accountName
					this.formData.reviewGroupId = user.groupId
					this.formData.reviewGroupName = user.groupName
					this.formData.reviewPositionId = user.positionId
					this.formData.reviewPositionName = user.positionName	
					this.formData.ocId=user.ocId
					this.formData.submitTime=parseTime(this.formData.submitTime)
					this.formData.dangerDeadline=parseTime(this.formData.dangerDeadline)
					handleDanger(this.formData).then((resp) => {
						uni.switchTab({
							url:'/pages/risk/risk'
						})
					})					
				})
			},
			upload(){
				let self=this;
				let attachList= JSON.parse(JSON.stringify(this.formData.attachList))
				uni.chooseImage({
					success:(files)=>{
						let filePath = files.tempFilePaths[0]
						upload({
							filePath
						}).then((res)=>{
							let result=JSON.parse(res);
							attachList.push(result.data)
							self.$set(self.formData,'attachList',attachList)
							self.$nextTick(()=>{
								self.scrollBottom()
							})
						})
					}
				})
			},
			// 渲染功能操作按钮
			renderAction() {
			  if (this.flowData && this.flowData.curActivityIns && this.flowData.curActivityIns.actionList) {
				const arr = this.flowData.curActivityIns.actionList
				if (arr.length > 1) {
				  this.actionVisible = true
				  const item = arr[0]
				  this.flowData.actionId = item.actionId
				  this.flowData.actionCode = item.actionCode
				  this.actionId = item.actionId
				} else if (arr.length === 1) {
				  const item = arr[0]
				  this.flowData.actionId = item.actionId
				  this.flowData.actionCode = item.actionCode
				  this.actionId = item.actionId
				} else {
					uni.showToast({
						icon:'none',
						title:'数据配置有误！请联系管理员'
					})
				}
			  }
			},
			onchangeGroup({detail}){
				let groupVal=detail.value
				let groupId=groupVal[groupVal.length-1].value
				this.formData.reviewAccountId=""
				this.getUser(groupId)
			},
			scrollBottom(duration=100){
				　uni.createSelectorQuery().select(".footer").boundingClientRect((res)=>{
					const scrollH = res.top;
				　　uni.pageScrollTo({
				　　　　duration,// 过渡时间
				　　　　scrollTop: scrollH,// 滚动的实际距离
				　　})
				}).exec()
			},
			verify(){
				let items={
					'hdangerTitle': '预警标题', // 
					"reviewAccountId":'评审人',
					'hdangerLevel': "预警等级", // 预警等级
					// 'hdangerDesc': '描述', // 
					'submitTime': "发生时间",
					'dangerDeadline': '截止时间', // 
					'goafId': "采空区",
					'checklistId': '检查表',
					// 'attachList':"附件"			
				}
				for(let key in items){
					if(this.formData[key]===""||this.formData[key]===undefined||this.formData[key]==="undefined"){
						uni.showToast({
							icon:'none',
							title:`请填写${items[key]}`
						})	
						return false;
					}
				}
				return true
			}
		}
	}
</script>
<style lang="scss" scoped>
.body{
	min-height: 100vh;
	box-sizing: border-box;
	padding:21rpx 16rpx;
	background-color: #F3F5FB;
	padding-bottom: 160rpx;
	.status-item{
		padding: 22rpx 32rpx;
		background-color: #fff;
		font-size: 28rpx;
		line-height: 1;
		display: inline-block;
		color: #434343;
		margin-right: 20rpx;
		border-radius: 2px;
		&.active{
			background: rgba(22, 141, 236, 0.16);
			color:#168DEC ;
		}
	}
	::v-deep .uni-forms-item__content{
		.uni-easyinput,.uni-select{
			background-color: #fff;
		}	
	}
	.upload-container{
		.upload{
			width: 216rpx;
			display: block;
		}
		.tip{
			font-size: 24rpx;
			line-height: 28rpx;
			color: #999999;
			padding-top: 20rpx;
		}
	}
	.footer{
		width: 100%;
		height: 136upx;
		background: #FFFFFF;
		border-radius: 16upx 16upx 0px 0px;
		position: fixed;
		left: 0;
		bottom: 0;
		text-align: center;
		color: #168DEC;
		font-size: 32upx;
		padding-top: 20upx;
		letter-spacing: 2px;
	}
	.preview{
		padding-top: 50rpx;
		.preview-item{
			width: 200rpx;
			height: 200rpx;
		}
	}
}
</style>
