<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 === true" :rules="rules">
					<el-col :span="24">
						<el-form-item label="关联产品" prop="sssb">
							<el-select v-model="sssbValue" placeholder="请选择关联产品" clearable filterable :style='{"width":"100%"}' @change="handleSssbChange">
								<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="sbm">
							<el-input v-model="dataForm.sbm" placeholder="自动填充" :disabled="true" :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 :style='{"width":"100%"}' >
								<el-option label="安装" value="安装" />
								<el-option label="维修" value="维修" />
								<el-option label="保养" value="保养" />
								<el-option label="检查" value="检查" />
								<el-option label="操作" value="操作" />
								<el-option label="理论" value="理论" />
								<el-option label="其他" value="其他" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="概要" prop="gy">
							<el-input v-model="dataForm.gy" type="textarea" placeholder="请输入概要" :autosize="{ minRows: 3, maxRows: 6 }" :style='{"width":"100%"}' />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="详情" prop="sbjs">
							<NCC-Quill v-model="dataForm.sbjs" placeholder="请输入内容..." >
							</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 :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="发布时间" prop="fbsj">
							<el-date-picker v-model="dataForm.fbsj" placeholder="请选择" clearable :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="fj1">
							<NCC-UploadFz v-model="dataForm.fj1" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" >
							</NCC-UploadFz>
						</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="点击上传" >
							</NCC-UploadFz>
						</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,
				dataForm: {
					id:'',
					sbm:undefined,
					sbjs:undefined,
					gy:undefined,
					fl:undefined,
					gg:undefined,
					fbsj:undefined,
					sssb:undefined,
					fj1:[],
					fj2:[],
				},
				rules: {
				},
				cpglOptions: [], // 产品管理选项
				sssbValue: '', // 关联产品选择值
			}
		},
		computed: {},
        watch: {
			visible(val) {
				if (!val) {
					// 对话框关闭时，重置 isDetail 为 false
					this.isDetail = false
				}
			}
		},
        created() {
			this.getCpglOptions();
		},
		mounted() {
        },
		methods: {
			getCpglOptions() {
				return request({
					url: '/api/Extend/Cpgl',
					method: 'GET',
					data: { currentPage: 1, pageSize: 1000 }
				}).then(res => {
					this.cpglOptions = res.data.list || []
					return Promise.resolve()
				}).catch(err => {
					console.error('获取产品管理列表失败:', err)
					this.cpglOptions = []
					return Promise.reject(err)
				})
			},
			handleSssbChange(val) {
				// 选择关联产品后，自动填充设备名
				if (val) {
					const product = this.cpglOptions.find(item => item.id === val);
					if (product) {
						this.dataForm.sssb = product.id;
						this.dataForm.sbm = product.cpmc || '';
					}
				} else {
					this.dataForm.sssb = '';
					this.dataForm.sbm = '';
				}
			},
			goBack() {
                this.$emit('refresh')
            },
			init(id, isDetail) {
				// 强制重置 isDetail，确保表单可编辑
				this.isDetail = false;
				// 如果明确传入 isDetail 为 true，才设置为详情模式
				if (isDetail === true) {
					this.isDetail = true;
				}
				this.dataForm.id = id || 0;
				console.log('Zsk Form init - id:', id, 'isDetail:', this.isDetail);
				this.visible = true;
				// 初始化选择值
				this.sssbValue = '';
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						request({
							url: '/api/Extend/Zsk/' + 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=[];
							// 根据关联产品ID查找对应的产品
							if (this.dataForm.sssb) {
								// 如果 cpglOptions 还未加载，等待加载完成
								if (this.cpglOptions.length === 0) {
									this.getCpglOptions().then(() => {
										const product = this.cpglOptions.find(item => item.id === this.dataForm.sssb);
										if (product) {
											this.sssbValue = product.id;
											// 如果设备名为空，自动填充
											if (!this.dataForm.sbm) {
												this.dataForm.sbm = product.cpmc || '';
											}
										}
									});
								} else {
									const product = this.cpglOptions.find(item => item.id === this.dataForm.sssb);
									if (product) {
										this.sssbValue = product.id;
										// 如果设备名为空，自动填充
										if (!this.dataForm.sbm) {
											this.dataForm.sbm = product.cpmc || '';
										}
									}
								}
							}
						})
					} else {
						// 新建时清空字段
						this.dataForm.sssb = '';
						this.dataForm.sbm = '';
						this.dataForm.fl = '';
						this.dataForm.gy = '';
					}
				})
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
						// 确保 sssbValue 同步到 dataForm.sssb
						// 如果 sssbValue 为空字符串，设置为 null；否则使用 sssbValue 的值
						this.dataForm.sssb = this.sssbValue && this.sssbValue !== '' ? this.sssbValue : null;
						// 调试：输出提交的数据
						console.log('提交数据前，sssbValue:', this.sssbValue);
						console.log('提交数据前，dataForm.sssb:', this.dataForm.sssb);
						console.log('完整提交数据:', JSON.stringify(this.dataForm, null, 2));
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/Zsk`,
                                method: 'post',
                                data: this.dataForm,
                            }).then((res) => {
								console.log('新建成功，响应:', res);
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false,
                                            this.$emit('refresh', true)
                                    }
                                })
                            })
                        } else {
							console.log('更新数据前，sssbValue:', this.sssbValue);
							console.log('更新数据前，dataForm.sssb:', this.dataForm.sssb);
							console.log('完整更新数据:', JSON.stringify(this.dataForm, null, 2));
                            request({
                                url: '/api/Extend/Zsk/' + this.dataForm.id,
                                method: 'PUT',
                                data: this.dataForm
                            }).then((res) => {
								console.log('更新成功，响应:', res);
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
                            })
                        }
                    }
                })
			},
		}
	}
</script>
