<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<uni-card :is-shadow="false" is-full padding="10px 0">
			<!-- <uni-row>
				<uni-col :span="4">部门</uni-col>
				<uni-col :span="8">{{receiveData.parentname}}</uni-col>
				<uni-col :span="4">考核指标</uni-col>
				<uni-col :span="8">{{receiveData.targetname}}</uni-col>
			</uni-row> -->
			<uni-table ref="table" :loading="loading" border stripe  emptyText="暂无数据" width="100%">
				<uni-tr>
					<uni-td>部门</uni-td>
					<uni-td>{{receiveData.parentname}}</uni-td>
					<uni-td>考核指标</uni-td>
					<uni-td>{{receiveData.targetname}}</uni-td>
				</uni-tr>
				<uni-tr>
					<uni-td>达成率</uni-td>
					<uni-td colspan=3 style="color:#FF0000">{{receiveData.reach}}</uni-td>
				</uni-tr>
				<uni-tr v-if="receiveData.content != ''">
					<uni-td>考核说明</uni-td>
					<uni-td colspan=3 >{{receiveData.content}}</uni-td>
				</uni-tr>
			</uni-table>
		</uni-card>
		<view class="example">
			<uni-forms ref="baseForm" :rules="baseFormDataViery" :model="baseFormData" labelWidth="80px">
				<uni-forms-item  label="全奖值"  >
					<view class="numVal">
						<view class="wenzhi" >{{receiveData.allprize}}</view>
					</view>	
				</uni-forms-item>
				<uni-forms-item  label="零奖值"  >
					<view class="numVal">
						<view class="wenzhi" >{{receiveData.zeroprize}}</view>
					</view>	
				</uni-forms-item>
				<uni-forms-item  label="封顶值"  >
					<view class="numVal">
						<view class="wenzhi" >{{receiveData.cappingcal}}</view>
					</view>	
				</uni-forms-item>
				<uni-forms-item  label="指标权重"  >
					<view class="numVal">
						<view class="wenzhi" >{{receiveData.targetweight}}</view>
					</view>	
				</uni-forms-item>
				<uni-forms-item  label="考核周期"  >
					<view class="example-body">
						<picker mode="date" :value="baseFormData.time" fields="month" @change="dateChange">
						     <view class="wenzhi">
								<uni-icons type="calendar" color="#c0c4cc" size="22"  style="margin-right: 10px;"></uni-icons>	{{baseFormData.time}}
							 </view>
						</picker>
					</view>
				</uni-forms-item>
				<uni-forms-item  label="实际值" required name="actualvalue">
					<view class="numVal">
						<uni-easyinput type="digit" v-model="baseFormData.actualvalue" placeholder="请输入实际值" @input="calculateScore" />
					</view>	
				</uni-forms-item>
				<uni-forms-item  label="达成率"  >
					<view class="numVal">
						<view class="wenzhi" >{{baseFormData.completionrate}}</view>
					</view>	
				</uni-forms-item>
				<uni-forms-item  label="指标得分"  >
					<view class="numVal">
						<view class="wenzhi" >{{baseFormData.havescore}}</view>
					</view>	
				</uni-forms-item>
				
				
				<uni-forms-item  v-if="receiveData.scoringmethod!=1" label="手动打分"  >
					<view class="numVal">
						<uni-easyinput type="digit" v-model="baseFormData.manualscoring" placeholder="请输入实际值" />
					</view>	
				</uni-forms-item>
				<uni-forms-item v-if="receiveData.scoringmethod!=1" label="打分说明">
					<uni-easyinput type="textarea" v-model="baseFormData.reason" placeholder="请输入这样操作的原因" />
				</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() {
			// 设置日期
			const currentDate = this.getDate({
			    format: 'yyyy-mm'
			})
			return {
				active:1,
				startTime: currentDate,
				loading:false,
				headerVerify:{
					userkey:"",
					token:"",
					userCont:""
				},
				receiveData:{
					parentname:"",
					targetname:"",
					allprize:"",
					zeroprize:"",
					cappingcal:"",
					targetweight:"",
					scoringmethod:1,
					reach:"",
					content:""
				},
				baseFormData:{
					time:currentDate,
					actualvalue:"",
					manualscoring:"",
					reason:"",
					havescore:"",
					completionrate:""
				},
				baseFormDataViery:{
					actualvalue:{
						rules: [{
							required: true,
							errorMessage: '请输入实际数据！'
						}]
					}
				},
				flowList:[],
			}
		},
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			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)
			// this.baseFormData ={
				
			// }
		},
		onReady(){
			this.getExamFlow()
		},
		methods: {
			// 获取年月日信息
			getDate(type) {
			    const date = new Date();
			    let year = date.getFullYear();
			    let month = date.getMonth() + 1;
			    if (type === 'start') {
			        year = year - 60;
			    } else if (type === 'end') {
			        year = year + 2;
			    }
			    month = month > 9 ? month : '0' + month;
			    // day = day > 9 ? day : '0' + day;
			    return `${year}-${month}`;
			},
			//选择时间
			dateChange(e){
				console.log("选择时间",e.detail.value)
				let _this = this
				_this.baseFormData.time = e.detail.value
			},
			//计算得分
			calculateScore(e){
				e = e*1
				// console.log("实际值---》",e)
				let _this=this
				if(_this.receiveData.allprize == 0 && _this.receiveData.zeroprize == 0){		//当零奖值与全奖值都未零时
				// console.log("实际值-------1-------》",e)
					if(e != null && e != '' && e != 0){	//实际值存在数值且都大约0
						_this.baseFormData.havescore = _this.receiveData.targetweight
						_this.baseFormData.completionrate = "100%"
						// console.log("实际值-------3-------》",e)
					}
				}else{
					if(_this.receiveData.allprize > _this.receiveData.zeroprize){//如果全奖值大于零奖值 执行一下操作
					// console.log("实际值-------31-------》",e)
						if(e <= _this.receiveData.zeroprize){//第一步判断 实际结算值小于零奖值 那么达成率和实际得分都是0
							_this.baseFormData.havescore = 0
							_this.baseFormData.completionrate = "0%"
							// console.log("实际值-------4-------》",e,_this.receiveData.zeroprize)
						}else{  //第二步判断 实际结算值大于零奖值
						// console.log("实际值-------5-------》",e)
							//计算达成率
							let chuShu = e - _this.receiveData.zeroprize
							let beiChuShu = _this.receiveData.allprize - _this.receiveData.zeroprize
							
							if(beiChuShu != 0){ //判断被除数不能为零
								let zhuHuaLv = chuShu/beiChuShu
								// console.log("实际值-------6-------》",zhuHuaLv)
								if(zhuHuaLv <= 0){ //如果在全奖值大于零奖值的情况下出现达成率为0或负数，则达成率和实际得分都是0
									_this.baseFormData.havescore = 0
									_this.baseFormData.completionrate = "0%"
								}else{									
									let tempVal = parseFloat(zhuHuaLv).toFixed(3)
									_this.baseFormData.completionrate = tempVal*100+"%"
									if(zhuHuaLv*100 >= _this.receiveData.cappingcal){
										// console.log("实际值-------7-------》",zhuHuaLv)
										if(_this.receiveData.cappingcal > 0){
											let deFen = _this.baseFormData.havescore = _this.receiveData.cappingcal * _this.receiveData.targetweight / 100
											_this.baseFormData.havescore  = _this.numFilter(deFen)
										}else{
											_this.baseFormData.havescore = _this.receiveData.targetweight
										}
									}else{
										let deFen =  _this.receiveData.targetweight * zhuHuaLv
										_this.baseFormData.havescore  = _this.numFilter(deFen)
									}
								}
							}else{
								//被除数为0时 那么达成率和实际得分都是0
								_this.baseFormData.havescore = 0
								_this.baseFormData.completionrate = "0%"
							}
						}
					}else{	//如果全奖值小于零奖值 执行一下操作
					// console.log("实际值-------4-------》",e)
						if (e >= _this.receiveData.zeroprize){ //实际结算值大于零奖值 那么达成率和实际得分都是0
							_this.baseFormData.havescore = 0
							_this.baseFormData.completionrate = "0%"
						}else{
							//计算达成率
							let chuShu = e - _this.receiveData.zeroprize
							let beiChuShu = _this.receiveData.allprize - _this.receiveData.zeroprize
							if(beiChuShu != 0){ //判断被除数不能为零
								let zhuHuaLv = chuShu/beiChuShu
								if(zhuHuaLv <= 0){ //如果在全奖值大于零奖值的情况下出现达成率为0或负数，则达成率和实际得分都是0
									_this.baseFormData.havescore = 0
									_this.baseFormData.completionrate = "0%"
								}else{									
									let tempVal = parseFloat(zhuHuaLv).toFixed(3)
									_this.baseFormData.completionrate = tempVal*100+"%"
									if(zhuHuaLv*100 >= _this.receiveData.cappingcal){
										if(_this.receiveData.cappingcal > 0){
											let deFen = _this.baseFormData.havescore = _this.receiveData.cappingcal * _this.receiveData.targetweight / 100
											_this.baseFormData.havescore  = _this.numFilter(deFen)
										}else{
											_this.baseFormData.havescore = _this.receiveData.targetweight
										}
									}else{
										let deFen =  _this.receiveData.targetweight * zhuHuaLv
										_this.baseFormData.havescore  = _this.numFilter(deFen)
									}
								}
							}else{
								//被除数为0时 那么达成率和实际得分都是0
								_this.baseFormData.havescore = 0
								_this.baseFormData.completionrate = "0%"
							}
						}
					}
				}
			},
			
			//第二保留小数点后两位的，不会四舍五入
			numFilter (value) {
				// 截取当前数据到小数点后三位
				let tempVal = parseFloat(value).toFixed(3)
				let realVal = tempVal.substring(0, tempVal.length - 1)
				return realVal
			},
			//获取流程图
			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--->")
					
					if(_this.receiveData.scoringmethod != 1){
						if(_this.baseFormData.manualscoring == ""){
							_this.baseFormData.manualscoring = _this.baseFormData.havescore
						}
					}else{
						_this.baseFormData.manualscoring = 0
					}
					
					
					
					let targetList = new Array
					let targetCont = {
						id:_this.receiveData.id, //方案ID
						actual: _this.baseFormData.actual, //实际值
						unit: _this.receiveData.unit, //单位
						reason: _this.baseFormData.reason, //原因
						scoringmethod:_this.receiveData.scoringmethod, //计分方式（1：自动；2：手动）"`
						target:_this.receiveData.target,					//指标ID
						scoringscore:_this.baseFormData.manualscoring //手动分
					}
					targetList.push(targetCont)
					
					let sendData = {
						groupid:_this.receiveData.group	,//公司
						departmentid:_this.receiveData.parentid ,//部门
						planversionnumber:_this.receiveData.planversionnumber ,//考核方案编号
						time:_this.baseFormData.time			,//提交时间
						list:targetList
					}
					uni.request({
						url:_this.$commonMethod.localhostUrl+'/api/quan/operation',
						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 * 1,
									position:'bottom',
									complete(){
										uni.navigateBack();
									}
								})
							}else{
								_this.$refs.uToast.show({
									message: callBackDate.msg,
									duration: 1000 * 4,
									position:'bottom',
								})
							}
						},
						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>
	.example {
		padding: 15px;
		background-color: #fff;
	}
	.wenzhi{
		display: flex;
		box-sizing: border-box;
		flex-direction: row;
		align-items: center;
		border: 1px solid #DCDFE6;
		border-radius: 4px;
		height: 35px;
		width: 100%;
		padding-left: 10px;
	}
	.selestDate{
	    border: 2rpx solid #e5e5e5;
	    border-radius: 100rpx;
	    background-color: #EAF4FF;
	    color: #3399FF;
	    font-size: 30rpx;
	    font-family: PingFangSC;
	    font-weight: Regular;
	    max-width: 600rpx;
	    height: 70rpx;
	    line-height: 70rpx;
	    padding-left: 30rpx;
	}
</style>
