<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" v-if="false" >
						<el-form-item label="宣传编号" prop="id">
							<el-input v-model="dataForm.id" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<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="sbmc">
							<el-input v-model="dataForm.sbmc" placeholder="自动填充" :disabled="true" :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="新闻概要" prop="xwgy">
							<el-input v-model="dataForm.xwgy" type="textarea" :rows="3" placeholder="请输入新闻概要" clearable :style='{"width":"100%"}' />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="新闻分类" prop="xwfl">
							<el-select v-model="dataForm.xwfl" placeholder="请选择新闻分类" clearable :style='{"width":"100%"}'>
								<el-option label="新产品" value="xcp" />
								<el-option label="产品升级" value="cpsj" />
								<el-option label="系统升级" value="xtsj" />
								<el-option label="资料更新" value="zlgx" />
								<el-option label="市场动态" value="scdt" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="宣传对象" prop="xcdx">
							<ComSelect v-model="xcdxValue" :multiple="true" placeholder="按公司选择宣传指定对象" style="width:100%" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备编号" prop="sbbh">
							<el-input v-model="dataForm.sbbh" placeholder="自动填充" :disabled="true" :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="升级亮点" prop="sjld">
							<NCC-Quill v-model="dataForm.sjld" placeholder="请输入内容..." >
							</NCC-Quill>
						</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="cpys">
							<NCC-Quill v-model="dataForm.cpys" placeholder="请输入内容..." >
							</NCC-Quill>
						</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="sbfl">
							<el-input :value="getFlName(dataForm.sbfl)" placeholder="自动填充" readonly :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备出厂编号" prop="sbccbh">
							<el-input v-model="dataForm.sbccbh" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备出厂日期" prop="sbccrq">
							<el-date-picker v-model="dataForm.sbccrq" 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="xgfj">
							<NCC-UploadFz v-model="dataForm.xgfj" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="相关图片" prop="xgtp">
							<NCC-UploadImg v-model="dataForm.xgtp" :fileSize="1" sizeUnit="GB" :limit="9" >
							</NCC-UploadImg>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建用户" prop="creatorUser">
							<el-input v-model="dataForm.creatorUser" placeholder="系统自动生成" readonly >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建时间" prop="creatorTime">
							<el-input :value="dataForm.creatorTime | dateFormat('YYYY-MM-DD HH:mm:ss')" placeholder="系统自动生成" readonly >
							</el-input>
						</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 { getDictionaryDataSelector } from '@/api/systemData/dictionary'
	import { previewDataInterface } from '@/api/systemData/dataInterface'
	import ComSelect from '@/components/Generator/components/ComSelect'
	export default {
		components: { ComSelect },
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				dataForm: {
					id:'',
					id:undefined,
					sssb:undefined,
					sbmc:undefined,
					sbbh:undefined,
					xwgy: undefined,
					xwfl: undefined,
					xcdx: undefined,
					sjld:undefined,
					fbsj:undefined,
					cpys:undefined,
					sbjs:undefined,
					gg:undefined,
					sbfl:undefined,
					sbccbh:undefined,
					sbccrq:undefined,
					xgfj:[],
					xgtp:[],
					creatorUser:undefined,
					creatorTime:undefined,
				},
				rules: {
				},
				cpglOptions: [], // 产品管理选项
				sssbValue: '', // 关联产品选择值
				xcdxValue: [], // 宣传对象（公司）多选值，提交时转为逗号分隔
				flOptions: [], // 设备分类选项
			}
		},
		computed: {},
        watch: {
			visible(val) {
				if (!val) {
					// 对话框关闭时，重置 isDetail 为 false
					this.isDetail = false
				}
			}
		},
        created() {
			this.getCpglOptions();
			this.getflOptions();
		},
		mounted() {
        },
		methods: {
			getflOptions() {
				getDictionaryDataSelector('626798132465763589').then(res => {
					this.flOptions = res.data.list
				});
			},
			getFlName(flId) {
				if (!flId) return '';
				const flOption = this.flOptions.find(item => item.id === flId);
				return flOption ? flOption.fullName : flId;
			},
			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.sbmc = product.cpmc || '';
						this.dataForm.sbbh = product.cpid || product.id || '';
					}
				} else {
					this.dataForm.sssb = '';
					this.dataForm.sbmc = '';
					this.dataForm.sbbh = '';
				}
			},
			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('Xccpgl 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/Xccpgl/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.dataForm = res.data;
							if(!this.dataForm.xgfj)this.dataForm.xgfj=[];
							if(!this.dataForm.xgtp)this.dataForm.xgtp=[];
							// 宣传对象：逗号分隔转数组
							this.xcdxValue = this.dataForm.xcdx ? this.dataForm.xcdx.split(',').filter(Boolean) : [];
							// 根据关联产品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.sbmc) {
												this.dataForm.sbmc = product.cpmc || '';
											}
											if (!this.dataForm.sbbh) {
												this.dataForm.sbbh = product.cpid || product.id || '';
											}
										}
									});
								} else {
									const product = this.cpglOptions.find(item => item.id === this.dataForm.sssb);
									if (product) {
										this.sssbValue = product.id;
										// 如果设备名称或设备编号为空，自动填充
										if (!this.dataForm.sbmc) {
											this.dataForm.sbmc = product.cpmc || '';
										}
										if (!this.dataForm.sbbh) {
											this.dataForm.sbbh = product.cpid || product.id || '';
										}
									}
								}
							}
						})
					} else {
						// 新建时清空字段
						this.dataForm.sssb = '';
						this.dataForm.sbmc = '';
						this.dataForm.sbbh = '';
						this.dataForm.sbfl = '';
						this.dataForm.xwgy = '';
						this.dataForm.xwfl = '';
						this.dataForm.xcdx = '';
						this.xcdxValue = [];
					}
				})
			},
			dataFormSubmit() {
				// 宣传对象：数组转逗号分隔
				this.dataForm.xcdx = Array.isArray(this.xcdxValue) ? this.xcdxValue.join(',') : (this.xcdxValue || '');
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/Xccpgl`,
                                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/Xccpgl/' + 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>
