<template>
	<view class="todo-page">
		<step-title :stepPage="stepsPage" :stepText="stepsText"></step-title>
		<view class="allview">
			<view class="card">
				<u--form labelWidth="auto" :model="model" ref="wForm" class="demo-ruleForm">
					<view style="position: relative;">
						<view style="position: absolute;left: -10px;color: #3d4b70;top: -3px;">*</view>
					</view>

					<view style="font-size: 15px; font-weight: bold;color: #3d4b70;margin-bottom: 10px;">基本信息</view>
					<u-form-item label="发起时间：" prop="Product_Unit">
						<u--input v-model="model.CREATE_TIME" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<u-form-item label="发起部门：" prop="Product_Unit">
						<u--input v-if="model.Nav_ApplyDepartment" v-model="model.Nav_ApplyDepartment.NAME" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<u-form-item label="发起人：" prop="Product_Unit">
						<u--input v-if="model.Nav_ApplyUser" v-model="model.Nav_ApplyUser.NAME" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<u-form-item label="生产单元：" prop="Product_Unit">
						<u--input v-model="model.Product_Unit" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<u-form-item label="检查类型：" prop="Check_Type">
						<u--input v-if="model.Nav_CheckType" v-model="model.Nav_CheckType.NAME" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="检查周期：" prop="Check_Period">
						<u--input v-model="model.PLANCHECKFREQUENCYName" disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="检查层级：" prop="Check_Level">
						<u--input v-model="model.DEPARTMENT_TYPEName" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<u-form-item label="检查时间：" prop="Check_Date">
						<u--input v-model="model.CHECK_TIME" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<!-- <u-form-item label="检查人员：" prop="Check_Date">
						<u--input v-model="model.CHECK_PERSON" disabled disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item> -->
					<u-form-item label="检查人员：" prop="UserNames">
					</u-form-item>
					<rich-text 
					  style="line-height: 30px;" 
					  autoHeight 
					  type="textarea" 
					  v-html="formattedCheckUsers" 
					  border="none" 
					  inputAlign="right" 
					  disabled 
					  class="richtext"
					></rich-text>
					<view class="upload-title">附件：</view>
					<full-upload v-model="model.Nav_CheckNoticeFiles" :isShowBtn='false' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>

				</u--form>
				<u--form labelWidth="auto" :model="model" ref="wForm" class="sub-form" v-if="model.Nav_CheckNoticeDetails.length!==0">
					<view style="position: relative;">
						<view style="position: absolute;left: -10px;color: #3d4b70;top: -3px;">*</view>
					</view>

					<view style="font-size: 15px; font-weight: bold;color: #3d4b70;margin-bottom: 10px;margin-top: 20px;">检查内容</view>
					<uni-collapse :border="false" accordion>
						<view v-for="(item, index) in model.Nav_CheckNoticeDetails" :key="index">
							<uni-collapse-item title-border="none" :border="false">
								<template v-slot:title>
									<view class="uni-collapse-item__title-box">
										<view class="uni-collapse-item__title-text">
											{{item.Nav_RiskArea?index+1+'.'+item.Nav_RiskArea.NAME:index+1+'.'}}
										</view>
										<view @click.stop>
											<!-- <u-icon @click="handleDelRowBefore(index)" name="trash" color="#ff4d4f" size="21" style="margin-right: 10px;"></u-icon> -->
										</view>
									</view>
								</template>
								<view class="content">
									<u-form-item label="检查区域：" prop="CHECK_TIME">
										<u--input disabled v-if="item.Nav_RiskArea" v-model="item.Nav_RiskArea.NAME" disabledColor="#ffffff" border="none" inputAlign="right" fontSize="14px">

										</u--input>

									</u-form-item>
									<u-form-item label="检查人员">
										<!-- <u-icon name="man-add" size="24" color="#3d9cff" slot="right"></u-icon> -->
									</u-form-item>
									<view class="tag-view" v-if="item.Nav_CheckNoticeDetailUsers">
										<uni-tag class="tag" v-for="(i, k) in item.Nav_CheckNoticeDetailUsers.filter(i => !i.IS_DELETED)" :key="k" :inverted="true" :text="i.Nav_User.NAME" type="primary" />
									</view>
									<u-form-item label="检查内容：" prop="CHECK_TIME">

									</u-form-item>
									<u-textarea v-model="(item.Nav_Contents||{}).CHECKCONTENT" disabled></u-textarea>

								</view>


							</uni-collapse-item>
						</view>
					</uni-collapse>

				</u--form>
			</view>
			<check-action v-if="isLoadOK && tableKey === '1'&&isAudit" :okApi="okApi" :refuseApi="refuseApi" :dataSource="$store.state.auditModel"></check-action>
			<view style="padding: 10px 16px;display: flex;flex-direction: row;" class="bottom-button" v-if="isLoadOK&&tableKey==='1'&&!isAudit">
				<u-button type="primary" @click="submit" color="#3d4b70">确认</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup,
		extendIgnoreDataRule
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		CheckPeriod,
		CheckLevel,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		GetIdentityNewEdit,
		IdentityUpdate
	} from '../../../../services/apply/subPages/SK/SKServices.js'
	import stepTitle from '@/components/custom/step-title.vue'
	import {
		getEnum
	} from '../../../../services/common';
	export default {
		components: {
			stepTitle,
		},
		data() {
			return {
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				isAudit: false,
				isLoadOK: false,
				tableKey: 0,
				model: {
					Nav_CheckNoticeFiles: [],
					Product_Unit: '',
					Check_Type: '',
					Check_Period: '',
					Check_Level: '',
					Check_Date: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
					Nav_CheckNoticeDetails: [{
						Nav_RiskArea: {
							NAME: ''
						},
						Nav_Contents: {
							CHECKCONTENT: ''
						},
					}],
				},
				dateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
				stepsText: ['发起', '审批', '确认', '归档'],
				stepsPage: 0,
				stepsPageList: 0,
				Pu: '',
				Check_Type_ID: '',
				TypeListres: {},
				modelID: '',
				TaskID: '',
				STATUS: 0,
				ID: '',
				stepLoad: true,
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {} // 存储枚举文本列表（用于下拉选择等场景）
			}
		},
		onLoad(option) {
			this.TaskID = option.taskID
			this.ID = option.ID
			this.tableKey = option.tableKey ? option.tableKey : '0'
			this.isAudit = option.isAudit
			this.okApi = option.okApi
			this.refuseApi = option.refuseApi
			this.auditModel = {
				...this.$store.state.auditModel,
				TaskID: option.taskID ? option.taskID : ''
			}
			this.fetchEnums(['SKProductionUnit', 'SKPLANCHECKFREQUENCYEnum', 'SKDepartmentTypeEnum']);
		},
		methods: {
			async fetchEnums(enumNames) {
				try {
					// 存储所有枚举请求的Promise
					const enumPromises = enumNames.map(name => {
						return getEnum({
							name
						}).then(res => {
							// 统一处理枚举格式：添加name/code字段，便于后续映射
							return {
								enumName: name,
								data: res.map(item => ({
									...item,
									name: item.NAME, // 统一显示名称字段
									code: item.ID // 统一值字段
								}))
							};
						});
					});

					// 等待所有枚举请求完成
					const results = await Promise.all(enumPromises);
					// 存储枚举结果到data中（键为枚举名称，值为处理后的数据）
					results.forEach(({
						enumName,
						data
					}) => {
						this.enumsData[enumName] = data;
						// 生成文本列表（如需要）
						this.enumsText[enumName] = data.map(item => item.name);
					});
					// 所有枚举获取完成后，执行loadData
					this.loadData();
				} catch (error) {
					console.error('枚举请求失败:', error);
					uni.showToast({
						title: '枚举数据加载失败',
						icon: 'none'
					});
				}
			},

			loadData() {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "")
				extendRule(json, 'ID', 1, this.ID)
				extendIgnoreDataRule(json)
				GetIdentityNewEdit(json).then(res => {
					if (res) {
						this.stepLoad = false
						this.model = res
						this.model.ID = this.ID
						this.model.CREATE_TIME = uni.$u.timeFormat(this.model.CREATE_TIME, 'yyyy-mm-dd')
						this.model.Product_Unit = res.MineType !== undefined ? this.enumsData['SKProductionUnit'].find(item => item.code === res.MineType).name : '';
						this.model.PLANCHECKFREQUENCYName = res.PLANCHECKFREQUENCY !== undefined ? this.enumsData['SKPLANCHECKFREQUENCYEnum'].find(item => item.code === res.PLANCHECKFREQUENCY).name : '';
						this.model.DEPARTMENT_TYPEName = res.DEPARTMENT_TYPE !== undefined ? this.enumsData['SKDepartmentTypeEnum'].find(item => item.code === res.DEPARTMENT_TYPE).name : '';
						this.stepsPage = res.STATUS == 0 ? 0 : res.STATUS == 20 ? 1 : res.STATUS == 10 ? 2 : 3
					}


				})
				this.isLoadOK = true

			},
			submit() {
				let json = {};
				json.ID = this.ID;
				json.TaskID = this.TaskID;
				IdentityUpdate(json).then(res => {
					uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						},
						'success', 1000)
				})
			}


		},
		computed: {
		  formattedCheckUsers() {
		    // 收集所有检查人员并去重
		    const userMap = new Map();
		    
		    // 遍历所有检查内容
		    (this.model.Nav_CheckNoticeDetails || []).forEach(detail => {
		      // 遍历当前检查内容的检查人员
		      (detail.Nav_CheckNoticeDetailUsers || []).forEach(user => {
		        // 过滤已删除的用户
		        if (!user.IS_DELETED && user.Nav_User?.NAME) {
		          // 使用用户名作为去重依据，也可以根据实际情况使用ID
		          if (!userMap.has(user.Nav_User.NAME)) {
		            userMap.set(user.Nav_User.NAME, user.ISCHECK);
		          }
		        }
		      });
		    });
		    
		    // 生成带颜色样式的HTML
		    let html = '';
		    userMap.forEach((isCheck, userName) => {
		      const color = isCheck === true ? '#000000' : '#ff0000';
		      html += `<span style="color: ${color}; margin-right: 10px;">${userName}</span>`;
		    });
		    
		    return html;
		  }
		}



	}
</script>

<style scoped>
	@import url("../../../../style/css/newTemplate.css");
</style>