<template>
	<view class="dpTask">
		<uni-card  class="progress_card">
			<view class="dp_list">
				<text style="font-size: 17px; color: rgba(51, 51, 51, 1);">任务进度:<text style="color: rgba(190, 163, 117, 1);">{{wwcNumber()}}/{{pageData.totalProgress}}</text></text>
				<view class="bhgs">
					<text class="bhgs_title">不合格数<text class="bhgs_text">{{bhgNumber()}}</text></text>
				</view>
			</view>
			<view class="sub_title">
				<view class="cfbh">
					<text class="cfbh_title">处方编号<text class="cfbh_text">{{pageData.cfbh}}</text></text>
				</view>
			</view>
			<view class="send">
				<uni-forms-item label="配方员" name="id" labelWidth="60px">
					<uni-easyinput v-model="data.reciper" type="" placeholder="请输入配方员姓名" :inputBorder="false" :disabled="pageData.disabledStatus"/>
				</uni-forms-item>
			</view>
			<view class="operator" v-if="pageData.operatorName!=null && pageData.operatorName!=''">
				<text class="operator_title">操作人<text class="operator_text">{{pageData.operatorName}}</text></text>
			</view>
			<uni-table class="dp_table">
				<!-- 表头行 -->
				<uni-tr>
					<uni-th align="center" width="100rpx">贴序</uni-th>
					<uni-th align="center" width="150rpx">应重(克)</uni-th>
					<uni-th align="center" width="150rpx">实重(克)</uni-th>
					<uni-th align="center" width="150rpx">误差(%)</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr v-for="(item, index) in pageData.dpList" :key="index">
					<uni-td align="center">
						<uni-easyinput v-model="item.item" :clearable="false" :disabled="true"></uni-easyinput>
					</uni-td>
					<uni-td align="center" style="width: 200rpx;">
						<view style="display: flex;align-items: center;">
							<span v-if="index==0? true : false">
								<uni-easyinput v-model.number="item.totalScore" :clearable="false" :disabled="pageData.disabledStatus" type="digit" @change="changeYz(item)"></uni-easyinput>
							</span>
							<span v-else>
								{{item.totalScore}}
							</span>
							<!-- <text>{{"(>"+(item.score!=null?item.score:0)+"g)"}}</text> -->
						</view>
					</uni-td>
					<uni-td align="center">
						<uni-easyinput v-model.number="item.score" :clearable="false" :disabled="pageData.disabledStatus" type="digit" @change="changeSz(item)"></uni-easyinput>
					</uni-td>
					<uni-td align="center">
						<uni-easyinput v-model.number="item.resultContent" :clearable="false" :disabled="pageData.disabledStatus" type="digit"></uni-easyinput>
					</uni-td>
				</uni-tr>
				<!-- 均值 -->
				<uni-tr>
					<uni-td align="center">总值</uni-td>
					<uni-td align="center">{{avgYz()}}</uni-td>
					<uni-td align="center">{{avgSz()}}</uni-td>
					<uni-td align="center">{{avgWc() +"%"}}</uni-td>
				</uni-tr>
			</uni-table>
		</uni-card>

		<view class="dpTask_img">
			<uni-card>
				<uni-section title="图片上传" type="line">
				</uni-section>
				<view class="image_upload">
					<uni-file-picker limit="4" :modelValue="showImage(pageData.imageList)" :readonly="pageData.imageStatus" @select="selectImg" @delete="deleteImg"></uni-file-picker>
				</view>
			</uni-card>
		</view>
		<!-- 下一个 -->
		<view class="finish_button" v-if="pageData.operatorStatus=='add'">
			<button class="button" @click="finishTask()">下一个</button>
		</view>
    <view v-if="pageData.taskStatusData == '7001' || pageData.taskStatusData == '7002' || pageData.taskStatusData == '7003'">
      <!-- 任务详情-编辑 -->
      <view class="finish_button" v-if="pageData.taskStatus=='2' && pageData.taskStatusData!='7004'">
        <button class="button" @click="editTask()">编辑</button>
      </view>
      <!-- 任务详情-保存 -->
      <view class="finish_button" style="margin-top: -4px;" v-if="pageData.taskStatus=='1'">
        <button class="button" @click="finishTask()">保存</button>
      </view>
    </view>
	</view>
</template>

<script setup>
import {reactive,onMounted,ref,watch,defineComponent, computed} from 'vue';
import {onLoad,onShow,onUnload,onPullDownRefresh} from "@dcloudio/uni-app";
import http from '@/utils/request';
import {uploadImageModelValue} from '@/pages/controls/image/OssService'
import { UrlPath } from "@/utils/commonuni"

const data = reactive({
	reciper: ''
})

const pageData = reactive({
	// 操作人姓名
	operatorName:'',
	operatorStatus:'',
	cfbh:'',
	detailList: [],
	dpList:[],
	// 图片列表
	imageList: [],
	// 图片状态
	imageStatus:true,
	resData:{},
	id:'',
	// 总任务进度
	totalProgress:0,
	// 控件状态
	disabledStatus:false,
	// 任务状态(编辑为2，保存为1)
	taskStatus:'',
	// 任务状态
	taskStatusData:''
})

const formData=reactive({
	id:''
})

// 临时创建代煎代配企业评估任务内容 入参
const createData=reactive({
	taskId:'',
	pId:'',
	providerType:''
})

const changeSz=(item)=>{
	if(item.score!=null && item.totalScore!=null){
		// 误差率 = (实重 - 应重) / 应重*100%
		item.resultContent=Math.abs(((item.score-item.totalScore)/item.totalScore).toFixed(2)*100)
	}
}

const changeYz=(item)=>{
	if(item.totalScore!="0" || item.totalScore!=0){
		if(item.score!=null && item.totalScore!=null){
			// 误差率 = (实重 - 应重) / 应重*100%
			item.resultContent=Math.abs(((item.score-item.totalScore)/item.totalScore).toFixed(2)*100)
		}
	}else{
		uni.showToast({
			title: '应重不能为0，请重新输入',
			icon:'error'
		});
	}
	for(let i=1;i<pageData.dpList.length;i++){
	  pageData.dpList[i].totalScore=item.totalScore
	}
}

// 均值 应重 保留两位小数
const avgYz=()=>{
	let num=0
	pageData.dpList.forEach((item,index)=>{
		num+=Number(item.totalScore)
	})
  return num.toFixed(2);
	// return (num/pageData.dpList.length).toFixed(2)
}

// 均值 实重 保留两位小数
const avgSz=()=>{
	let num=0
	pageData.dpList.forEach((item,index)=>{
		num+=Number(item.score)
	})
	// return (num/pageData.dpList.length).toFixed(2)
  return num.toFixed(2);
}

// 均值 误差
const avgWc=()=>{
	let num=0
	pageData.dpList.forEach((item,index)=>{
		num+=Number(item.resultContent)
	})
	console.log();
	
	// return (num/pageData.dpList.length).toFixed(2)
	if(avgYz()!=0){
		let pjz = (Math.abs(avgYz()-avgSz()) / avgYz())
		pjz = (pjz * 100).toFixed(2)
		return pjz
	}else{
		return 0
	}
}

// 选中图片，将选中的图片添加列表
const selectImg=(e)=>{
	if(pageData.imageList==null || pageData.imageList == undefined){
		pageData.imageList=[]
	}
	e.tempFiles.forEach(item=>{
		uni.showLoading({
			title: '图片上传....',
			mask: true
		});
		http.upload("admin-api/infra/file/upload",{file:item.file}).then(e => {
			uni.hideLoading()
			pageData.imageList.push(e)
		})
	})
}

// 删除图片，并将其从列表中删除
const deleteImg=(val)=>{
	if (val.index != -1) {
		pageData.imageList.splice(val.index, 1);
	}
}

const countResultContent=()=>{
	pageData.resData.resultContent=0
	pageData.resData.resultContent=avgWc()
	pageData.resData.detail.reciper=data.reciper
	if(pageData.imageList!=null || pageData.imageList!=undefined){
		pageData.resData.detail.imageIds=pageData.imageList.toString()
	}
}

//保存
const saveTask=()=>{
  uni.showLoading({
    title: '提交中....',
    mask: true
  });
  http.post("app-api/zkzy/save",pageData.resData).then(res=>{
    uni.hideLoading()
    if(res==true){
      uni.showToast({
        title: '已提交',
        icon:'success',
      });
    }else{
      uni.showToast({
        title: '提交失败',
        icon:'fail'
      });
    }
  })
}

// 下一个
const finishTask=()=>{
	console.log("内容",pageData.dpList)
	if(pageData.dpList[0].totalScore=="0"){
		uni.showToast({
			title: '应重不能为0',
			icon:'error'
		});
	}else if(wwcNumber()!=pageData.totalProgress){
		uni.showToast({
			title: '提交失败，请检查任务进度',
			icon:'error'
		});
	}else{
		countResultContent()
		uni.showLoading({
			title: '提交中....',
			mask: true
		});
		http.post("app-api/zkzy/save",pageData.resData).then(res=>{
			uni.hideLoading()
			if(res==true){
				uni.showToast({
					title: '已提交',
					icon:'success',
					success: () => {
						uni.navigateBack({
							delta:1
						})
					}
				});
			}else{
				uni.showToast({
					title: '提交失败',
					icon:'fail'
				});
			}
		})
	}
	
	
	// if(pageData.dpList[0].totalScore!="0" && wwcNumber()==pageData.totalProgress){
	// 	countResultContent()
	// 	uni.showLoading({
	// 		title: '提交中....',
	// 		mask: true
	// 	});
	// 	http.post("app-api/zkzy/save",pageData.resData).then(res=>{
	// 		uni.hideLoading()
	// 		if(res==true){
	// 			uni.showToast({
	// 				title: '已提交',
	// 				icon:'success',
	// 				success: () => {
	// 					uni.navigateBack({
	// 						delta:1
	// 					})
	// 				}
	// 			});
	// 		}else{
	// 			uni.showToast({
	// 				title: '提交失败',
	// 				icon:'fail'
	// 			});
	// 		}
	// 	})
	// }else{
	// 	uni.showToast({
	// 		title: '提交失败，请检查任务进度',
	// 		icon:'error'
	// 	});
	// }
}

// 编辑
const editTask=()=>{
	pageData.disabledStatus=!pageData.disabledStatus
	pageData.imageStatus=!pageData.imageStatus
	pageData.taskStatus='1'
}

// 临时创建代配代配企业评估任务内容
const createTask=()=>{
	getTaskId()
	http.get("app-api/zkzy/create",createData).then(res=>{
		if(res=="该处方已质控、不能重复添加"){
			uni.showToast({
				title: '该处方已质控、不能重复添加',
				icon:'none',
				success: () => {
					uni.navigateBack({
						delta: 1
					});
				}
			});
		}else{
			getDpTask(res)
		}
	})
}

// 获取代配质控作业
const getDpTask=(data)=>{
	formData.id=data
	uni.showLoading({
		title: '',
		mask: true
	});
	http.get("app-api/taskDetail/get",formData).then(res=>{
		uni.hideLoading()
		pageData.dpList = res.results
		// 实重、误差初始化赋值
		if(pageData.dpList.length!=0){
			pageData.dpList.forEach(item=>{
				if(item.score==null){
					item.score=0
				}
				if(item.resultContent==null){
					item.resultContent=0
				}
			})
		}
		pageData.resData=res
		pageData.totalProgress=res.results.length
		
		if(res.detail.imageIds!=null){
			pageData.imageList=showImage(res.detail.imageIds)
		}
	})
}

// 显示图片
const showImage = (urlStr) => {
	const rawPrefix = UrlPath.getBaseUrl()
	const prefix = rawPrefix.replace(/\/+$/, '');
	const result = urlStr.map(url => {
		return prefix + url;
	});
	return result;
}

// 任务进度（已完成）
const wwcNumber = () =>{
	let number = 0
	let data = pageData.resData.results
	if(data != null){
		for (var i = 0; i < data.length; i++) {
			if (data[i].score != null && data[i].score != undefined && data[i].score != '')
				number ++;
		}
	}
	return number
}

// 不合格数
const bhgNumber=()=>{
	let number=0
	if(pageData.resData.results!=null){
		pageData.resData.results.forEach(item=>{
			if (item.resultContent > 5){
				number++
			}
			// if(item.score<item.totalScore){
			// 	number++
			// }
		})
	}
	return number
}

// 获取taskId
const getTaskId=()=>{
	uni.getStorage({
		key:'saveTaskId',
		success: (res) => {
			createData.taskId = res.data.taskId
		}
	})
}

const getDpTaskDetail=()=>{
	uni.showLoading({
		title: '',
		mask: true
	});
	http.get("app-api/taskDetail/get",{id:pageData.id}).then(res=>{
		uni.hideLoading()
		pageData.resData=res
		pageData.dpList = res.results
		pageData.totalProgress=res.results.length
		pageData.taskStatus=res.detail.status
		pageData.operatorName=res.detail.creatorName
		data.reciper=res.detail.reciper
		if(res.detail.imageIds!=null && res.detail.imageIds!=''){
			if(typeof(res.detail.imageIds)=='string'){
				var urls=res.detail.imageIds.split(',')
				pageData.imageList=[]
				urls.forEach(e=>{
					pageData.imageList.push(e)
				})
			}
		}
	})
}

onLoad((type)=>{
	if(type.state!=null){
		pageData.operatorStatus=type.state
	}
	if(type.cfbh!=null){
		pageData.cfbh=type.cfbh
	}
	if(type.ptwybh!=null){
		createData.pId=type.ptwybh
		pageData.cfbh=type.ptwybh
	}
	if(type.fyfslx!=null){
		createData.providerType=type.fyfslx
	}
	if(type.id!=null){
		pageData.id=type.id
	}
	if(type.taskStatus!=null){
		pageData.taskStatusData=type.taskStatus
	}
	// 获取代配数据
	if(pageData.operatorStatus=='add'){
		pageData.imageStatus=false
		pageData.disabledStatus=false
		createTask()
	}else{
		pageData.imageStatus=true
		pageData.disabledStatus=true
		getDpTaskDetail()
	}
})
</script>

<style lang="scss" scoped>
	@import 'index.scss';
</style>
