<template>
	<view class="djhjTask">
		<!-- 任务进度 -->
		<view class="djhjTask_progress">
			<text class="djhjTask_progress_title">任务进度：<text class="djhjTask_progress_text">{{wwcNumber()}}/{{pageData.taskNum}}</text></text>
			<text class="djhjTask_progress_title">不合格数<text class="djhjTask_progress_text">{{bhgNumber()}}</text></text>
		</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-card padding="0" spacing="0" v-for="(item,index) in pageData.resList.results" class="djhjList">
			<view class="djhjList_title">
				<view class="djhjList_text">检查项目</view>
				<view class="djhjList_righttext">{{item.item}}</view>
			</view>
			<view class="djhjList_title">
				<view class="djhjList_text">检查方式</view>
				<view class="djhjList_righttext">{{item.assessmentCriteria}}</view>
			</view>
			<view class="djhjList_title">
				<view class="djhjList_text">检查内容</view>
				<view class="djhjList_righttext">{{item.assessmentContent}}</view>
			</view>
			<view class="djhjList_title">
				<view class="djhjList_text">检查结果</view>
				<view :class="item.assessmentResult=='不合格'? 'djhjList_redtext' : item.assessmentResult=='待检' ? 'djhjList_bluetext':'djhjList_greentext'">{{item.assessmentResult}}</view>
			</view>
			<view class="djhjList_title" v-if="item.resultContent">
				<view class="djhjList_text">原因</view>
				<view class="djhjList_righttext">{{item.resultContent}}</view>
			</view>
			<view class="button_group">
				<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)" @select="selectImg" @delete="deleteImg"></uni-file-picker>
				</view>
			</uni-card>
		</view>
		<!-- 按钮组 -->
		<view class="operator_button">
			<!-- <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" v-if="pageData.resList.results!=0" @click="next">下一个</button> -->
				<button class="next_or_finish_button_save" v-if="pageData.resList.results!=0" @click="save">保存</button>
				<button class="next_or_finish_button_allSave" v-if="pageData.taskNum != wwcNumber()" @click="openPassDialog">一键通过</button>
				<!-- <button class="next_or_finish_button_save" @click="finish" v-else>完成</button> -->
				<button class="next_or_finish_button" v-if="pageData.resList.results!=0" @click="next">提交</button>
			<!-- </view>	 -->
		</view>
		<!-- 不合格弹出框 -->
		<uni-popup ref="bhgDialog" type="dialog">
			<uni-popup-dialog type="info" mode="input" confirmText="提交" cancelText="取消" title="不合格原因" value="" placeholder="请填写不合格原因" @confirm="bhgDialogConfirm"
				@close="bhgDialogClose"></uni-popup-dialog>
		</uni-popup>

    <!-- 一键通过确认弹出框 -->
    <uni-popup ref="passDialog" type="dialog">
      <uni-popup-dialog type="info" confirmText="确定" cancelText="取消" :content="passMessage.showMessage" @confirm="operatorDialogConfirm" @close="operatorDialogClose"></uni-popup-dialog>
    </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({
	bhgNum:0,
	finishNum:'',
	taskNum:'',
	djhjList:[],
	imageList:[],
	resList:[],
	taskStatus:'',
	buttonDisabled:true,
	// 操作人姓名
	operatorName:''
})

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

const passMessage = reactive({
  showMessage:''
})

const passDialog = ref(null)

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

// 任务进度（已完成）
const wwcNumber = () =>{
	let number = 0
	let data = pageData.resList.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 bhgNumber=()=>{
	let number=0
	if(pageData.resList.results!=null){
		pageData.resList.results.forEach(item=>{
			if(item.assessmentResult=='不合格'){
				number++
			}
		})
	}
	return number
}

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

// 提交不合格原因
const bhgDialogConfirm=(val)=>{
	// 获取输入的不合格原因
	item.value.resultContent = val
	pageData.bhgNum=pageData.bhgNum+1
	pageData.resList.results.forEach((e,idx)=>{
		if(e.id==item.value.id){
			pageData.resList.results[idx]=item.value
		}
	})
	bhgDialog._value.close()
	item.value = {}
}

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

// 选中图片，将选中的图片添加列表
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)
		})
	})
	console.log("上传后",pageData.imageList)
}

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

const item = ref({})
// 不合格
const bhgCheck=(e)=>{
	e.score=0
	if(e.assessmentResult=="合格" || e.assessmentResult=="待检"){
		e.assessmentResult="不合格"
		item.value = e
		// 打开不合格弹出输入框
		bhgDialog._value.open()
	}
}

// 合格
const hgCheck=(e)=>{
	if(e.assessmentResult=='不合格' || e.assessmentResult=='待检'){
		e.assessmentResult='合格'
		e.score=e.totalScore
		e.resultContent=''
	}
}

// 一键通过
const pass=()=>{
	pageData.finishNum=pageData.taskNum
	pageData.resList.results.forEach(item=>{
		if(item.isDj == null && (item.resultContent == null || item.resultContent == "")) {
			item.assessmentResult='合格'
			item.resultContent=''
		}
	})
}

// 打开一键通过弹窗
const openPassDialog=()=>{
  passMessage.showMessage = "未填选项目是否一键通过？"
  passDialog.value.open()
}
// 弹窗确认事件
const operatorDialogConfirm = () => {
  pass()
  operatorDialogClose()
}


// 关闭一键通过弹窗
const operatorDialogClose=()=>{
  passDialog.value.close()
}

// 计算环境质控总分
const countTotal=()=>{
	pageData.resList.resultContent=0
	pageData.resList.results.forEach(item=>{
		pageData.resList.resultContent+=Number(item.score)
	})
}

// 保存环境质控
const saveHjTask=()=>{
	if(pageData.imageList!=null && pageData.imageList!=undefined && pageData.imageList.length!=0){
		pageData.resList.detail.imageIds=pageData.imageList.toString()
		console.log("内容",pageData.resList.detail)
		console.log("内容2",pageData.imageList)
		uni.showLoading({
			title: '提交中.......',
			mask: true
		});
		http.post("app-api/zkzy/save",pageData.resList).then(res=>{
			uni.hideLoading()
			if(res==true){
				uni.showToast({
					title: '提交成功',
					success: () => {
						uni.navigateBack({
							delta:1
						})
					}
				});
			}else{
				uni.showToast({
					title: '提交失败'
				});
			}
		})
	}else{
		uni.showToast({
			title: '请上传图片',
			icon: 'none'
		});
	}
}

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

// 下一个
const next=()=>{
	pageData.resList.detail.fyfsyf="xcpg"
	if(wwcNumber()==pageData.taskNum){
		countTotal()
		saveHjTask()
	}else{
		uni.showToast({
			title: '提交失败，请检查任务进度',
			icon:'error'
		});
	}

}

// 完成
const finish=()=>{
	pageData.resList.detail.fyfsyf="xcpg"
	saveHjTask()
}

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

// 临时创建代煎代配企业评估任务内容
const createTask=()=>{
	createData.providerType="xcpg"
	getTaskId()
	http.get("app-api/zkzy/create",createData).then(res=>{
		getHJTask(res)
	})
}

// 获取环境质控质控作业
const getHJTask=(data)=>{
	formData.id=data
	http.get("app-api/taskDetail/get",formData).then(res=>{
		pageData.resList=res
		pageData.finishNum=0
		pageData.bhgNum=0
		pageData.taskNum = pageData.resList.results.length
		pageData.operatorName=res.detail.creatorName
		if(pageData.resList.detail.status=="2" || pageData.resList.detail.status=="1"){
			pageData.resList.results.forEach(item=>{
				if(item.score==item.totalScore && !item.isDj){
					item.assessmentResult='合格'
				}else{
					item.assessmentResult = item.isDj ? '待检' : '不合格'
				}
			})
		}else{
			pageData.resList.results.forEach(item=>{
				// 一开始均为“待检状态”
				item.assessmentResult='待检'
			})
		}
		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)
				})
			}
		}
	})
}

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

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

onLoad(()=>{
	createTask()
})

</script>

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