<template>
	<el-dialog :title="!dataForm.id ? '新建' :  isDetail ? '详情':'编辑'" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll append-to-body width="600px">
		<el-row :gutter="15" class="" >
				<el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
					<el-col :span="24">
						<el-form-item label="资料名称" prop="zlm">
							<el-input v-model="dataForm.zlm" placeholder="请输入" clearable :disabled="fieldDisabled" :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="关联产品" prop="fl">
							<el-select v-model="dataForm.fl" placeholder="请选择关联产品" clearable filterable :disabled="fieldDisabled" :style='{"width":"100%"}' >
								<el-option v-for="item in cpglOptions" :key="item.id" :label="item.cpmc + ' (' + (item.cpid || item.id) + ')'" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="发布日期" prop="fbsj">
							<el-date-picker v-model="dataForm.fbsj" placeholder="请选择" clearable :disabled="fieldDisabled" :style='{"width":"100%"}' type='date' format="yyyy-MM-dd" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="资料版本" prop="bh">
							<el-input v-model="dataForm.bh" placeholder="请输入" clearable :disabled="fieldDisabled" :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备图号" prop="th">
							<el-input v-model="dataForm.th" placeholder="请输入" clearable :disabled="fieldDisabled" :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备信息" prop="sbjs">
							<NCC-Quill v-model="dataForm.sbjs" placeholder="请输入内容..." :disabled="fieldDisabled" >
							</NCC-Quill>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="规格" prop="gg">
							<el-input v-model="dataForm.gg" placeholder="请输入" clearable :disabled="fieldDisabled" :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="附件（图片）" prop="fj1">
							<NCC-UploadImg v-model="dataForm.fj1" :fileSize="1" sizeUnit="GB" :limit="9" :disabled="fieldDisabled" >
							</NCC-UploadImg>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="附件（其它）" prop="fj2">
							<NCC-UploadFz v-model="dataForm.fj2" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" :disabled="fieldDisabled" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="技术资料" prop="jszl">
							<NCC-UploadFz v-model="dataForm.jszl" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" :disabled="fieldDisabled" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="质量资料" prop="zlzl">
							<NCC-UploadFz v-model="dataForm.zlzl" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" :disabled="fieldDisabled" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="其他资料" prop="qtzl">
							<NCC-UploadFz v-model="dataForm.qtzl" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" :disabled="fieldDisabled" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备图片" prop="xctp">
							<NCC-UploadImg v-model="dataForm.xctp" :fileSize="1" sizeUnit="GB" :limit="9" :disabled="fieldDisabled" >
							</NCC-UploadImg>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备维护人员" prop="sbwhry">
							<el-select v-model="sbwhryValue" placeholder="请选择设备维护人员" multiple clearable filterable :disabled="fieldDisabled" :style='{"width":"100%"}' @change="handleSbwhryChange">
								<el-option v-for="item in sbwhryOptions" :key="item.id" :label="item.xm + ' (' + item.id + ')'" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import request from '@/utils/request'
	import { previewDataInterface } from '@/api/systemData/dataInterface'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				formKey: 0, // 用于强制重新渲染表单
				dataForm: {
					id:'',
					zlm:undefined,
					sbbh:undefined,
					gg:undefined,
					fl:undefined,
					fbsj:undefined,
					bh:undefined,
					th:undefined,
					ccbh:undefined,
					ccrq:undefined,
					sbjs:undefined,
					fj1:[],
					fj2:[],
					jszl:[],
					zlzl:[],
					qtzl:[],
					xctp:[],
					sbwhry:'', // 存储为字符串格式
				},
				rules: {
				},
				cpglOptions : [], // 产品管理选项
				sbwhryOptions : [],
				sbwhryValue: [], // 用于 el-select 的数组值
			}
		},
		computed: {
			formDisabled() {
				// 明确返回布尔值，确保表单禁用状态正确
				const disabled = this.isDetail === true;
				console.log('Zlgl Form computed formDisabled - isDetail:', this.isDetail, 'disabled:', disabled, 'type:', typeof this.isDetail);
				return disabled;
			},
			// 为每个字段提供禁用状态的计算属性
			fieldDisabled() {
				return this.isDetail === true;
			}
		},
        watch: {
			visible(val) {
				if (val) {
					// 对话框打开时，强制确保 isDetail 为 false（除非是详情模式）
					console.log('Zlgl Form visible changed to true, current isDetail:', this.isDetail);
					if (this.isDetail !== true) {
						this.isDetail = false;
						console.log('Zlgl Form - forced isDetail to false');
					}
				} else {
					// 对话框关闭时，重置 isDetail 为 false
					this.isDetail = false;
					console.log('Zlgl Form visible changed to false, reset isDetail to false');
				}
			},
			isDetail(val) {
				console.log('Zlgl Form isDetail changed to:', val, 'type:', typeof val);
			}
		},
        created() {
			this.getCpglOptions();
			this.getsbwhryOptions();
		},
		mounted() {
        },
		methods: {
			getCpglOptions(){
				request({
					url: '/api/Extend/Cpgl',
					method: 'GET',
					data: { currentPage: 1, pageSize: 1000 }
				}).then(res => {
					this.cpglOptions = res.data.list || []
				}).catch(err => {
					console.error('获取产品管理列表失败:', err)
					this.cpglOptions = []
				})
			},
			getsbwhryOptions(){
				request({
					url: '/api/Extend/Sbwhry',
					method: 'GET',
					data: { currentPage: 1, pageSize: 1000 }
				}).then(res => {
					this.sbwhryOptions = res.data.list || []
					this.sbwhryOptions = this.sbwhryOptions.filter(item => item && item.id && item.xm)
				}).catch(err => {
					console.error('获取设备维护人员列表失败:', err)
					this.sbwhryOptions = []
				})
			},
			handleSbwhryChange(val) {
				// 将数组转换为逗号分隔的字符串存储到 dataForm
				this.dataForm.sbwhry = val ? val.join(',') : '';
			},
			goBack() {
                this.$emit('refresh')
            },
			init(id, isDetail) {
				console.log('Zlgl Form init called - id:', id, 'isDetail param:', isDetail);
				this.dataForm.id = id || 0;
				// 强制重置 isDetail，确保表单可编辑
				// 使用 Vue.set 确保响应式更新
				this.$set(this, 'isDetail', false);
				// 如果明确传入 isDetail 为 true，才设置为详情模式
				if (isDetail === true) {
					this.$set(this, 'isDetail', true);
				}
				console.log('Zlgl Form init - after setting, isDetail:', this.isDetail, 'type:', typeof this.isDetail);
				// 直接设置 visible，不使用 $nextTick
				this.visible = true;
				console.log('Zlgl Form visible set to true, isDetail:', this.isDetail);
				// 初始化 sbwhryValue 为空数组
				this.sbwhryValue = [];
				// 确保 isDetail 已经设置后再显示对话框
				this.$nextTick(() => {
					// 再次确认 isDetail 的值
					if (this.isDetail !== true) {
						this.isDetail = false;
					}
					this.visible = true;
					console.log('Zlgl Form visible set to true, isDetail:', this.isDetail, 'formDisabled:', this.formDisabled);
					// 等待 DOM 更新完成后再调用 resetFields 和加载数据
					this.$nextTick(() => {
						if (this.$refs && this.$refs['elForm']) {
							this.$refs['elForm'].resetFields();
						}
						if (this.dataForm.id) {
							request({
								url: '/api/Extend/Zlgl/' + this.dataForm.id,
								method: 'get'
							}).then(res =>{
								this.dataForm = res.data;
								if(!this.dataForm.fj1)this.dataForm.fj1=[];
								if(!this.dataForm.fj2)this.dataForm.fj2=[];
								if(!this.dataForm.jszl)this.dataForm.jszl=[];
								if(!this.dataForm.zlzl)this.dataForm.zlzl=[];
								if(!this.dataForm.qtzl)this.dataForm.qtzl=[];
								if(!this.dataForm.xctp)this.dataForm.xctp=[];
								// 将逗号分隔的字符串转换为数组，用于 el-select
								if (this.dataForm.sbwhry && typeof this.dataForm.sbwhry === 'string') {
									this.sbwhryValue = this.dataForm.sbwhry.split(',').filter(item => item);
								} else {
									this.sbwhryValue = [];
								}
							})
						} else {
							// 新建时确保 sbwhryValue 是空数组
							this.sbwhryValue = [];
							this.dataForm.sbwhry = '';
						}
					});
				});
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
						// 确保 sbwhry 是字符串格式（从 sbwhryValue 同步）
						if (Array.isArray(this.sbwhryValue) && this.sbwhryValue.length > 0) {
							this.dataForm.sbwhry = this.sbwhryValue.join(',');
						} else {
							this.dataForm.sbwhry = '';
						}
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/Zlgl`,
                                method: 'post',
                                data: this.dataForm,
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false,
                                            this.$emit('refresh', true)
                                    }
                                })
                            })
                        } else {
                            request({
                                url: '/api/Extend/Zlgl/' + this.dataForm.id,
                                method: 'PUT',
                                data: this.dataForm
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
                            })
                        }
                    }
                })
			},
		}
	}
</script>
