<template>
	<view class="djTask">
		<!-- 任务进度 -->
		<view class="progress_title">
			<view class="progress">
				<text class="progress_text">任务进度:<text
						class="progress_text_1">{{wwcNumber()}}/{{pageData.totalProgress}}</text></text>
			</view>
			<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="operator" v-if="pageData.operatorName!=null && pageData.operatorName!=''">
			<text class="operator_title">操作人<text class="operator_text">{{pageData.operatorName}}</text></text>
		</view>
		<!-- 查看处方内容按钮 -->
		<view class="detail">
			<view @click="showDetail" class="showDetail_button">查看处方内容<uni-icons type="calendar"
					color="#FFFFFF"></uni-icons></view>
		</view>
		<!-- 检查结果 -->
		<uni-card padding="0" spacing="0" v-for="(item,index) in pageData.resData.results" class="djList">
			<view class="djList_title">
				<view class="djList_text">检查项目</view>
				<view class="djList_righttext">{{item.item}}</view>
			</view>
			<view class="djList_title">
				<view class="djList_text">检查内容</view>
				<view class="djList_righttext">{{item.assessmentCriteria}}</view>
			</view>
			<view class="djList_title">
				<view class="djList_text">检查结果</view>
				<view :class="item.assessmentResult=='不合格'? 'djList_redtext' : item.assessmentResult=='待检' ? 'djList_bluetext':'djList_greentext'">
					{{item.assessmentResult}}
				</view>
			</view>
			<view class="djList_title">
				<view class="djList_text">备注</view>
				<view class="djList_righttext">
					{{item.remark}}
				</view>
			</view>
			<view class="djList_title" v-if="item.resultContent">
				<view class="djList_text">原因</view>
				<view class="djList_righttext">{{item.resultContent}}</view>
			</view>
			<view class="button_group" v-if="pageData.operatorStatus=='add' || pageData.taskStatus=='1'">
				<view class="bhg_button" @click="bhgCheck(item)">不合格</view>
				<view class="hg_button" @click="hgCheck(item)">合格</view>
			</view>
		</uni-card>
		<!-- 图片上传 -->
		<view class="image_upload">
			<uni-card>
				<uni-section title="图片上传" type="line"></uni-section>
				<view class="img_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="operator_button" v-if="pageData.operatorStatus=='add'">
			<!-- 			<button :class="pageData.buttonDisabled==false?'pass_button':'pass_button_grey'" @click="pass" :disabled="pageData.buttonDisabled">一键通过</button>
 --> <!-- 如果还有数据按钮显示为“下一个”，数据全部加载完毕显示为“完成” -->
			<!-- <view class="finish_button_grop"> -->
			<button class="next_or_finish_button_save" @click="save">保存</button>
			<!-- </view> -->
			<!-- <view class="finish_button_grop"> -->
			<button class="next_or_finish_button" @click="next">提交</button>
			<!-- </view> -->
		</view>
		<!-- 任务详情-编辑 -->
		<view
			v-if="pageData.taskStatusData == '7001' || pageData.taskStatusData == '7002' || pageData.taskStatusData == '7003'">
			<view class="operator_button" v-if="pageData.taskStatus=='2' && pageData.taskStatusData!='7004'">
				<!-- <button class="pass_button" @click="back">返回</button> -->
				<!-- <view class="finish_button_grop"> -->
				<button class="next_or_finish_button" @click="editTask()">编辑</button>
				<!-- </view> -->
			</view>
		</view>
		<!-- 任务详情-保存 -->
		<view class="operator_button" v-if="pageData.taskStatus=='1'">
			<button class="next_or_finish_button_save" @click="save">保存</button>
			<button class="next_or_finish_button" @click="next">提交</button>
		</view>
		<!-- 不合格弹出框 -->
		<uni-popup ref="bhgDialog" type="dialog">
			<uni-popup-dialog type="info" mode="input" confirmText="确定" cancelText="取消" title="原因" value=""
				placeholder="请填写原因" @confirm="bhgDialogConfirm" @close="bhgDialogClose">
				<uni-easyinput type="textarea" maxlength="50" autoHeight v-model="pageData.reason"
					placeholder="请输入原因"></uni-easyinput>
			</uni-popup-dialog>
		</uni-popup>
		<!-- 一键通过弹出框 -->
		<uni-popup ref="passDialog" type="dialog">
			<view class="passDialog">
				<view class="passDialog_title">
					<uni-title type="h2" title="一键通过" align="center"></uni-title>
					<!-- 倒计时 -->
					<smh-countDown second="10" radius="60" lineWidth="3rpx" color="#BFA578"
						@end="countDownEnd"></smh-countDown>
				</view>
				<view class="passDialog_content">
					<view>10秒后将自动跳转下一个处方</view>
					<view class="passDialog_content_cancel">点击取消可停留本页面</view>
				</view>
				<view class="passDialog_button">
					<view class="passDialog_button_cancel" @click="passCancel">取消</view>
					<view class="passDialog_button_confirm" @click="passConfirm">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		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 pageData = reactive({
		// 处方编号
		cfbh: '',
		// 操作人姓名
		operatorName: '',
		// 操作状态，是编辑/查看
		operatorStatus: '',
		djList: [],
		// 检查项目Id
		checkId: '',
		// 合格列表
		hgList: [],
		// 不合格列表
		bhgList: [],
		// 不合格原因
		reason: '',
		resData: [],
		imageIdList: [],
		// 图片列表
		imageList: [],
		imageStatus: true,
		id: '',
		totalProgress: 0,
		// 任务状态(编辑为2，保存为1)
		taskStatus: '',
		taskStatusData: '',
		buttonDisabled: true,
		// 处方信息
		detail: {},
		// 药品
		medicines: []
	})

	const formData = reactive({
		id: '',
		pageSize: 1,
		pageNum: 10
	})

	const createData = reactive({
		taskId: '',
		pId: '',
		providerType: ''
	})

	const saveTaskData = reactive({
		detail: '',
		unHgStateName: ''
	})

	// 查看处方内容
	const showDetail = () => {
		console.log(pageData.detail);
		console.log(pageData.medicines);
		uni.navigateTo({
			url: '/pages/ypczk/zkTask/prescriptionInfo/prescriptionInfo?detail=' + encodeURIComponent(JSON
				.stringify(pageData.detail)) + '&medicines=' + encodeURIComponent(JSON.stringify(pageData
				.medicines))
		})
	}

	// 不合格数
	const bhgNumber = () => {
		let number = 0
		if (pageData.resData.results != null) {
			pageData.resData.results.forEach(item => {
				if (item.assessmentResult == '不合格') {
					number++
				}
			})
		}
		return number
	}

	// 定义不合格弹出输入框
	const bhgDialog = ref()

	// 提交不合格原因
	const bhgDialogConfirm = () => {
		// 获取输入的不合格原因
		if (hgTc.value == true) {
			if (pageData.reason == null || pageData.reason == '' || pageData.reason == undefined) {
				return
			} else {
        item.value.assessmentResult = assessmentResult.value
				item.value.resultContent = pageData.reason
				pageData.resData.results.forEach((e, idx) => {
					if (e.id == item.value.id) {
						pageData.resData.results[idx] = item.value
					}
				})
				pageData.reason = ''
				bhgDialog._value.close()
				item.value = {}
			}
		} else {
      item.value.assessmentResult = assessmentResult.value
			item.value.resultContent = pageData.reason
			pageData.resData.results.forEach((e, idx) => {
				if (e.id == item.value.id) {
					pageData.resData.results[idx] = item.value
				}
			})
			pageData.reason = ''
			bhgDialog._value.close()
			item.value = {}
		}
	}

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

	// 取消不合格弹出输入框
	const bhgDialogClose = () => {
    // 关闭不合格弹出框
    pageData.reason = ''
    bhgDialog._value.close()

	}

	// 一键通过弹出框
	const passDialog = ref()

	// 一键通过弹出框确定事件
	const passConfirm = () => {
		countTotal()
		saveDjTask()
	}

	// 一键通过弹出框取消事件
	const passCancel = () => {
		passDialog._value.close()
	}

	// 一键通过弹出框倒计时接收事件
	const countDownEnd = () => {
		countTotal()
		saveDjTask()
	}

	// 选中图片，将选中的图片添加列表
	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 item = ref({})
  const assessmentResult =  ref('')
	// 不合格
	const bhgCheck = (e) => {
		e.score = 0
		if (e.assessmentResult == "合格" || e.assessmentResult == "待检") {
      item.value = e
			assessmentResult.value = "不合格"
      e.score = 0
			hgTc.value = false
			// 打开不合格弹出输入框
			if (e.isInput == '1') {
				hgTc.value = true
			}
			bhgDialog._value.open()
		}
	}
	const hgTc = ref(false)
	// 合格
	const hgCheck = (e) => {
		pageData.hgList.push(e.id)
		if ((e.assessmentResult == '不合格' || e.assessmentResult == '待检') && e.isInput != '1') {
			e.assessmentResult = '合格'
			e.score = e.totalScore
			e.resultContent = ''
		}
		if (e.isInput == '1') {
      assessmentResult.value = '合格'
      e.score = e.totalScore
			hgTc.value = true
			item.value = e
			// 打开不合格弹出输入框
			bhgDialog._value.open()
		}
	}

	// 一键通过
	const pass = () => {
		pageData.resData.results.forEach(item => {
			item.assessmentResult = '合格'
			item.resultContent = ''
		})
		passDialog._value.open()
	}

	// 计算代煎总分
	const countTotal = () => {
		pageData.resData.resultContent = 0
		pageData.resData.results.forEach(item => {
			if (!item.isDj && item.assessmentResult != '待检'){
				pageData.resData.resultContent += Number(item.score)
			} else {
				pageData.resData.resultContent += 0
			}

		})
		if (pageData.imageList != null || pageData.imageList != undefined) {
			pageData.resData.detail.imageIds = pageData.imageList.toString()
		}
	}

	const saveDjTask = () => {
		uni.showLoading({
			title: '提交中....',
			mask: true
		});
		http.post("app-api/zkzy/save", pageData.resData).then(res => {
			uni.hideLoading()
			if (res == true) {
				uni.showToast({
					title: '提交成功',
					success: () => {
						uni.navigateBack({
							delta: 1
						})
					}
				});
			} else {
				uni.showToast({
					title: '提交失败'
				});
			}
		})
	}

	//保存
	const save = () => {
		uni.showLoading({
			title: '提交中....',
			mask: true
		});
		if (pageData.imageList != null || pageData.imageList != undefined) {
			pageData.resData.detail.imageIds = pageData.imageList.toString()
		}
		countTotal()
		http.post("app-api/zkzy/save", pageData.resData).then(res => {
			uni.hideLoading()
			if (res == true) {
				uni.showToast({
					title: '提交成功',
				});
			} else {
				uni.showToast({
					title: '提交失败'
				});
			}
		})
	}

	// 下一个
	const next = () => {
		if (wwcNumber() == pageData.totalProgress) {
			countTotal()
			saveDjTask()
      back()
		} else {
			uni.showToast({
				title: '提交失败，请检查任务进度',
				icon: 'error'
			});
		}
	}

	// 完成
	const finish = () => {
		countTotal()
		saveDjTask()
	}

	// 返回
	const back = () => {
		uni.navigateBack({
			delta: 1
		});
	}

	// 编辑
	const editTask = () => {
		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 {
				getDjTask(res)
			}
		})
	}

	// 获取代煎质控作业
	const getDjTask = (data) => {
		formData.id = data
		http.get("app-api/taskDetail/get", formData).then(res => {
			pageData.djList = res.results
			pageData.cfbh = res.detail.ptwybm

			pageData.detail = res.detail
			pageData.medicines = res.medicines

			saveTaskData.detail = res.results
			pageData.resData = res
			pageData.djList.forEach(item => {
				// 一开始均为“待检状态”
				item.assessmentResult = '待检'
			})
			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;
	}

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

	const getDjTaskDetail = () => {
		// getTaskId()
		http.get("app-api/taskDetail/get", {
			id: pageData.id
		}).then(res => {
			pageData.resData = res
			pageData.totalProgress = res.results.length
			pageData.taskStatus = 2
			pageData.operatorName = res.detail.creatorName
			pageData.detail = res.detail
			pageData.medicines = res.medicines
			res.results.forEach(item => {
				// 检查内容（分数与总分相同为合格，反之不合格）
				if (item.score == item.totalScore && !item.isDj) {
					item.assessmentResult = '合格'
				} else {
					item.assessmentResult = item.isDj ? '待检' : '不合格'
					pageData.bhgNum = pageData.bhgNum + 1
				}
			})
			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)
					})
				}
			}
		})
	}


	onShow(() => {
		setTimeout(() => {
			pageData.buttonDisabled = false
		}, 5000)
	})

	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
		}
		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
			createTask()
		} else {
			pageData.imageStatus = true
			getDjTaskDetail()
		}
	})
</script>

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