<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<uni-card :is-shadow="false" is-full>
			<text class="uni-h6">{{receiveData.detailedtargenttitle}}</text>
		</uni-card>
		<view class="example">
			<uni-forms ref="baseForm" :rules="baseFormDataViery" :model="baseFormData" labelWidth="80px">
				<uni-forms-item v-if="baseFormData.state!=3" label="考核标准">
					<view class="titleVal">{{baseFormData.standard}}</view>	
				</uni-forms-item>
				<uni-forms-item v-if="baseFormData.state==1" label="次数" required>
					<view class="numVal">
						<uni-number-box :max="100" v-model="baseFormData.frequency" @blur="blur" @focus="focus" @change="changeValue" />
					</view>	
				</uni-forms-item>
				<uni-forms-item v-if="baseFormData.state==2?true:baseFormData.state==3?true:false" label="分数" required >
					<view class="numVal">
						<uni-easyinput type="digit" v-model="baseFormData.fraction" placeholder="请输入分数" />
					</view>	
				</uni-forms-item>
				<uni-forms-item label="发生时间" required name="time">
					<view class="example-body">
						<uni-datetime-picker type="datetime" v-model="baseFormData.time" :clearIcon="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="原因">
					<uni-easyinput type="textarea" v-model="baseFormData.reason" placeholder="请输入这样操作的原因" />
				</uni-forms-item>
				<uni-forms-item label="上传">
					<u-upload
					    :fileList="baseFormData.fileList"
					    @afterRead="afterRead"
					    @delete="deletePic"
					    name="3"
					    multiple
					    :maxCount="10"
					    :previewFullImage="true"
					></u-upload>
				</uni-forms-item>
				<button type="primary" plain="true" :disabled="loading" :loading="loading" @click="sendJiafen('baseForm')">提交</button>
			</uni-forms>
			
			<uni-card :isShadow="false"  padding="15px 0" margin="15px 0 0 0">
				<uni-steps :options="flowList" active-color="#007AFF" :active="active" direction="column" />
			</uni-card>
		</view>
		
		
		
	</view>
</template>

<script>	//定性考核
	export default {
		data() {
			return {
				active:1,
				loading:false,
				headerVerify:{
					userkey:"",
					token:"",
					userCont:""
				},
				receiveData:{
					detailedtargenttitle:""
				},
				baseFormData:{
					state:1,	//1、定分；2、区间分；3、不定性分值
					standard:"",	//考核标准
					frequency:1,	//定分发生次数
					fraction:"",	//分数（区间分操作）
					time:this.getCurrentMonth(), //发生时间
					reason:"",			//操作原因
					fileList: [],		//附件列表
				},
				flowList:[],
				baseFormDataViery:{
					time:{
						rules: [{
							required: true,
							errorMessage: '发生时间不能为空'
						}]
					}
				}
			}
		},
		onLoad(option) {
			console.log("option",option)
			console.log("option",JSON.parse(option.data))
			let _this = this
			//判断Token是否有效
			let systemCache = _this.$commonMethod.getSystemCacheDate('myCache')
			if(!systemCache){
				_this.$commonMethod.JumpUrl('/pages/login/login')
			}else{
				let currentTime = new Date().getTime() - systemCache.tokenTime
				if (currentTime >= 10800000){
					_this.$commonMethod.verifyPowerIsTrue('myCache')
				}
			}
			_this.headerVerify.userkey = systemCache.userKey
			_this.headerVerify.token = systemCache.token
			_this.headerVerify.userCont = systemCache.userInfo
			this.receiveData = JSON.parse(option.data)
			console.log("receiveData------------->",this.receiveData)
			let fenshu = ""
			if(this.receiveData.state == 1){
				fenshu = this.receiveData.score
			}
			this.baseFormData ={
				state:this.receiveData.state,
				standard:this.receiveData.score+this.receiveData.company,
				frequency:1,
				fraction:fenshu,
				time:this.getCurrentMonth(),
				reason:"",
				fileList: [],
			}
			
		},
		onReady(){
			this.getExamFlow()
		},
		methods:{
			//获取年月日时分
			getCurrentMonth () {
				let date = new Date()
				console.log(date)
				let year = date.getFullYear()
				let month = date.getMonth()+1
				let day = date.getDate()
				let hours = date.getHours()
				let minutes = date.getMinutes()
				// this.yserDate = year
				// this.monthDate = month
				month = month > 9 ? month : '0' + month
				day = day > 9 ? day : '0' + day
				hours = hours > 9 ? hours : '0' + hours
				minutes = minutes > 9 ? minutes : '0' + minutes
				console.log("day--->",day)
				return `${year}-${month}-${day} ${hours}:${minutes}`
			},
			changeValue(value) {
				console.log('返回数值：', value);
			},
			blur(e) {
				console.log('-------blur:', e);
			},
			focus(e) {
				console.log('-------focus:', e);
			},
			// 删除图片
			deletePic(event) {
				console.log(event,"event---->")
				this.baseFormData.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.baseFormData.fileList.length
				lists.map((item) => {
					this.baseFormData.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					// console.log(lists[i],"====================>lists[i]")
					// console.log(result,"====================>result")
					let resultData = JSON.parse(result)
					// console.log(resultData,"====================>resultData")
					let item = this.baseFormData.fileList[fileListLen]
					this.baseFormData.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url:resultData.data.url,
						filepath:resultData.data.physicspath,
						type:resultData.data.type
					}))
					fileListLen++
				}
			},
			//上传模组
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let _this = this
					let a = uni.uploadFile({
						url: _this.$commonMethod.localhostUrl+'/api/upordown', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							type: 1
						},
						header: {
							'X-Requested-With': 'XMLHttpRequest',
							// 'Content-Type': 'application/json', //自定义请求头信息
							// 'User-Agent':250,
							'user-key': _this.headerVerify.userkey,
							'user-token': _this.headerVerify.token
						},
						success: (res ) => {
							// console.log(res.data)
							const resData = JSON.parse(res.data)
							// console.log(resData.code,"resData=======>")
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
							// return resData
						}
					});
				})
			},
			//获取流程图
			getExamFlow(){
				
				let _this = this
				uni.request({
					url:_this.$commonMethod.localhostUrl+'/api/eval/examineflow',
					header: {
						'Content-Type': 'application/json', //自定义请求头信息
						// 'User-Agent':250,
						'user-key': _this.headerVerify.userkey,
						'user-token': _this.headerVerify.token
					},
					method:'POST',//请求方式，必须为大写
					data:{
						id:_this.receiveData.id.toString(),
						iscorrection:2
					},
					success: (res) => {
						console.log("getExamFlow----------->",res)
						let callBackDate = res.data
						if(callBackDate.code == 0){
							let chartDate = callBackDate.data
							chartDate.forEach(item=>{
								let userList = new Array				//节点审批人
								console.log(item.userlist,"item.userlist")
								if(item.userlist != null && item.userlist.length > 0){
									item.userlist.forEach(usItem=>{
										let usLog = new Array				//节点审批人审批记录
										if(usItem.log != null && usItem.log.length > 0){
											usItem.log.forEach(logItem=>{
												let logCont = {
													state:logItem.state,
													time:logItem.time,
													enclosure:logItem.enclosure
												}
												usLog.push(logCont)
											});
										}
										let userCont = {					//节点审批人信息
											id:usItem.id,
											name:usItem.name,
											icon:usItem.icon,
											groupname:usItem.groupname,
											departmentname:usItem.departmentname,
											postname:usItem.postname,
											workshopname:usItem.workshopname,
											userlist:usLog
										}
										userList.push(userCont)
									});
								}
								
								let flowCont = {					//流程图
									title: item.nodename,
									desc: item.step,
									state: item.state,
									userlist:userList
								}
								_this.flowList.push(flowCont)
								
							})
							console.log("flowCont----------->",_this.flowList)
							console.log(chartDate)
						}else{
							_this.messageToggle('bottom',callBackDate.msg) 
							
						}
					},
					fail:function(e){
						console.log('接口返回--login--2--',e);
						_this.messageToggle('bottom',e) 
					},
				})
			},
			//提示消息
			messageToggle(type,msg) {
				this.$refs.uToast.show({
					message: msg,
					duration: 1000 * 2,
					position:'bottom',
				})
			},
			//提交表单数据
			sendJiafen(ref){
				let _this=this
				_this.loading=true
				console.log("baseFormData-------》",_this.baseFormData);
				this.$refs[ref].validate().then(res => {
					console.log(_this.baseFormData,"kjljsdlkfjlksd--->")
					switch(_this.baseFormData.state){
						case 2:
							if(_this.baseFormData.fraction == ""){
								_this.baseFormData.fraction = 0
							}
							break;
							// if(_this.baseFormData.fraction > _this.receiveData)
						case 3:
							if(_this.baseFormData.fraction == ""){
								_this.baseFormData.fraction = 0
							}
							break;
						default:
							if(_this.baseFormData.frequency <= 0){
								_this.baseFormData.frequency = 1
							}
					}
					let fileAry = new Array
					if(_this.baseFormData.fileList != null && _this.baseFormData.fileList.length > 0){
						_this.baseFormData.fileList.forEach(itemk=>{
							let filecont = {
								filename:itemk.name,
								filepath:itemk.url,
								type:itemk.type
							}
							fileAry.push(filecont)
						})
					}
					let sendData = {
						planid:_this.receiveData.id.toString(),	//方案id
						time:_this.baseFormData.time,	//检查时间
						type:1,	 //1：加分；2：减分
						score:_this.baseFormData.fraction.toString(),	//分数
						count:_this.baseFormData.frequency,	//次数
						state:_this.receiveData.addreduce,	//1、定分；2、区间分；3、不定性分值
						reason:_this.baseFormData.reason,	//原因
						rectification:2,	//1：整改；2：无需整改
						planversionnumber:_this.receiveData.planversionnumber,	//版本号
						enclosure:fileAry
					}
					uni.request({
						url:_this.$commonMethod.localhostUrl+'/api/eval/plusorminuspointsnew',
						header: {
							'Content-Type': 'application/json', //自定义请求头信息
							// 'User-Agent':250,
							'user-key': _this.headerVerify.userkey,
							'user-token': _this.headerVerify.token
						},
						method:'POST',//请求方式，必须为大写
						data:sendData,
						success: (res) => {
							console.log(res)
							let callBackDate = res.data
							if(callBackDate.code == 0){
								_this.$refs.uToast.show({
									message: callBackDate.msg,
									duration: 1000 * 2,
									position:'bottom',
									complete(){
										uni.navigateBack();
									}
								})
							}else{
								_this.$refs.uToast.show({
									message: callBackDate.msg,
									duration: 1000 * 2,
									position:'bottom',
									complete(){
										_this.loading=false
									}
								})
							}
						},
						fail:function(e){
							console.log('接口返回--login--2--',e);
							_this.$refs.uToast.show({
								message: e,
								duration: 1000 * 2,
								position:'bottom',
							})
						},
					})
				}).catch(err => {
					console.log('err', err);
					_this.loading=false
				})
			},
			
			
			
			
			
			
			
			
			
		}
	}
</script>


<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}
	.titleVal{
		    display: flex;
		    flex-direction: row;
		    align-items: center;
		    text-align: left;
		    font-size: 14px;
		    color: #606266;
		    height: 36px;
		    padding: 0 12px 0 0;
		    vertical-align: middle;
		    flex-shrink: 0;
		    box-sizing: border-box;
	}
	.numVal{
		display: flex;
		flex-direction: row;
		align-items: center;
		text-align: left;
		font-size: 14px;
		color: #606266;
		height: 36px;
		padding: 0 12px 0 0;
		vertical-align: middle;
		flex-shrink: 0;
		box-sizing: border-box;
		
	}
	
	
</style>


