<template>
	<el-dialog :title="!dataForm.id ? '新建' :  isDetail ? '详情':'编辑'" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll 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" 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="dysb">
							<el-select v-model="dysbValue" placeholder="请选择关联产品" clearable filterable :style='{"width":"100%"}' @change="handleDysbChange">
								<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="dysbbh">
							<el-input v-model="dataForm.dysbbh" placeholder="自动填充" clearable :style='{"width":"100%"}' :disabled="true" >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备名称" prop="sbmc">
							<el-input v-model="dataForm.sbmc" placeholder="自动填充" clearable :style='{"width":"100%"}' :disabled="true" >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="出厂编号" prop="ccbh">
							<el-input v-model="dataForm.ccbh" placeholder="请输入出厂编号" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="生产厂家" prop="sccj">
							<el-input v-model="dataForm.sccj" placeholder="请输入生产厂家" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="所属钻机编号" prop="sszjbh">
							<el-input v-model="dataForm.sszjbh" placeholder="请输入所属钻机编号" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="所属井队编号" prop="ssjdbh">
							<el-input v-model="dataForm.ssjdbh" placeholder="请输入所属井队编号" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="所属钻机型号" prop="sszjxh">
							<el-input v-model="dataForm.sszjxh" placeholder="请输入所属钻机型号" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="购入时间" prop="gmsj">
							<el-date-picker v-model="dataForm.gmsj" 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="sbzt">
							<el-select v-model="dataForm.sbzt" placeholder="请选择设备状态" clearable :style='{"width":"100%"}' >
								<el-option label="运行中" value="运行中"></el-option>
								<el-option label="检修中" value="检修中"></el-option>
								<el-option label="停机" value="停机"></el-option>
								<el-option label="报废" value="报废"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="维护历史" prop="whls">
							<el-date-picker v-model="dataForm.whls" placeholder="请选择维护历史" clearable :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="维护周期" prop="whzq">
							<el-select v-model="dataForm.whzq" placeholder="请选择维护周期" clearable :style='{"width":"100%"}' >
								<el-option v-for="item in whzqOptions" :key="item.value" :label="item.label" :value="item.value" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="维护计划" prop="whjh">
							<el-date-picker v-model="dataForm.whjh" placeholder="请选择维护计划" clearable :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="备件信息" prop="bjxx">
							<el-select v-model="bjxxValue" placeholder="请选择备件信息" multiple clearable filterable :style='{"width":"100%"}' @change="handleBjxxChange">
								<el-option v-for="item in bjxxOptions" :key="item.id" :label="item.mc + ' (' + item.bh + ')'" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="历史故障" prop="lsgz">
							<NCC-Quill v-model="dataForm.lsgz" placeholder="请输入历史故障内容..." >
							</NCC-Quill>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备图片" prop="sbtp">
							<NCC-UploadImg v-model="dataForm.sbtp" :fileSize="1" sizeUnit="GB" :limit="9" >
							</NCC-UploadImg>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="设备资料" prop="sbzl">
							<NCC-UploadFz v-model="dataForm.sbzl" :fileSize="1" sizeUnit="GB" :limit="9" buttonText="点击上传" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="所属客户" prop="sskh">
							<NCC-TreeSelect 
								v-model="sskhValue" 
								:options="userTreeData" 
								placeholder="请选择所属客户（人员/部门/组织）" 
								clearable 
								:style='{"width":"100%"}' 
								@change="handleSskhChange">
							</NCC-TreeSelect>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="所属客户编号" prop="sskhbh">
							<el-input v-model="dataForm.sskhbh" placeholder="自动填充" clearable :style='{"width":"100%"}' :disabled="true" >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="客户销售人员" prop="khxsry">
							<NCC-TreeSelect 
								v-model="khxsryValue" 
								:options="userTreeData" 
								placeholder="请选择客户销售人员" 
								clearable 
								:style='{"width":"100%"}' 
								lastLevel 
								lastLevelKey='type' 
								lastLevelValue='user'
								@change="handleKhxsryChange">
							</NCC-TreeSelect>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="客户销售人员编号" prop="khxsrybh">
							<el-input v-model="dataForm.khxsrybh" placeholder="自动填充" clearable :style='{"width":"100%"}' :disabled="true" >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="下次维护时间" prop="xcwhsj">
							<el-date-picker v-model="dataForm.xcwhsj" placeholder="请选择下次维护时间" clearable :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" >
							</el-date-picker>
						</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 { getUserSelector } from '@/api/permission/user'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				dataForm: {
					id:'',
					sskh:undefined,
					sskhbh:undefined,
					dysb:undefined,
					dysbbh:undefined,
					fl:undefined, // 关联产品/设备ID（对应 Cpgl.id）
					khxsry:undefined,
					khxsrybh:undefined,
					gmsj:undefined,
					sbmc:undefined,
					ccbh:undefined,
					sccj:undefined,
					sszjbh:undefined,
					ssjdbh:undefined,
					sszjxh:undefined,
					sbzt:undefined,
					whls:undefined,
					xcwhsj:undefined,
					whzq:undefined,
					whjh:undefined,
					bjxx:'', // 存储为字符串格式（逗号分隔）
					lsgz:undefined,
					sbtp:[], // 设备图片数组
					sbzl:[], // 设备资料数组
				},
				rules: {
				},
				userTreeData: [],
				cpglOptions: [], // 产品管理选项
				bjxxOptions: [], // 备件信息选项
				sskhValue: '', // 所属客户选择值
				dysbValue: '', // 关联产品选择值
				khxsryValue: '', // 客户销售人员选择值
				bjxxValue: [], // 备件信息选择值（数组）
				whzqOptions: [ // 维护周期选项
					{ label: '1天', value: '1天' },
					{ label: '3天', value: '3天' },
					{ label: '1周', value: '1周' },
					{ label: '2周', value: '2周' },
					{ label: '1月', value: '1月' },
					{ label: '2月', value: '2月' },
					{ label: '3月', value: '3月' },
					{ label: '6月', value: '6月' },
					{ label: '1年', value: '1年' },
				],
			}
		},
		computed: {},
        watch: {},
        created() {
			this.getUserTreeData();
			this.getCpglOptions();
			this.getBjxxOptions();
		},
		mounted() {
        },
		methods: {
			getUserTreeData() {
				getUserSelector().then(res => {
					this.userTreeData = res.data.list || []
				}).catch(err => {
					console.error('获取用户列表失败:', err)
					this.userTreeData = []
				})
			},
			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)
				})
			},
			getBjxxOptions() {
				return request({
					url: '/api/Extend/Bjxx',
					method: 'GET',
					data: { currentPage: 1, pageSize: 1000 }
				}).then(res => {
					this.bjxxOptions = res.data.list || []
					return Promise.resolve()
				}).catch(err => {
					console.error('获取备件信息列表失败:', err)
					this.bjxxOptions = []
					return Promise.reject(err)
				})
			},
			handleBjxxChange(val) {
				// 将数组转换为逗号分隔的字符串存储到 dataForm
				this.dataForm.bjxx = val ? val.join(',') : '';
			},
			handleSskhChange(val) {
				// 选择人员/部门/组织后，自动填充编号和名称
				if (val) {
					this.dataForm.sskhbh = val;
					const node = this.findNodeInTree(this.userTreeData, val);
					if (node) {
						this.dataForm.sskh = node.fullName;
					}
				} else {
					this.dataForm.sskh = '';
					this.dataForm.sskhbh = '';
				}
			},
			handleDysbChange(val) {
				// 选择产品后，自动填充产品编号、产品名称、设备名称，并将设备id保存到fl字段
				if (val) {
					const product = this.cpglOptions.find(item => item.id === val);
					if (product) {
						this.dataForm.fl = val; // 保存关联产品/设备id到fl字段
						this.dataForm.dysbbh = product.cpid || product.id || '';
						this.dataForm.dysb = product.cpmc || '';
						this.dataForm.sbmc = product.cpmc || '';
					}
				} else {
					this.dataForm.fl = '';
						this.dataForm.fl = '';
						this.dataForm.dysb = '';
						this.dataForm.dysbbh = '';
						this.dataForm.sbmc = '';
				}
			},
			handleKhxsryChange(val) {
				// 选择销售人员后，自动填充销售人员编号和销售人员名称
				if (val) {
					this.dataForm.khxsrybh = val;
					// 从树形数据中查找用户名称
					const user = this.findUserInTree(this.userTreeData, val);
					if (user) {
						this.dataForm.khxsry = user.fullName;
					}
				} else {
					this.dataForm.khxsry = '';
					this.dataForm.khxsrybh = '';
				}
			},
			findUserInTree(tree, id) {
				// 递归查找树形数据中的用户（仅 type=user）
				for (let item of tree) {
					if (item.id === id && item.type === 'user') {
						return item;
					}
					if (item.children && item.children.length > 0) {
						const found = this.findUserInTree(item.children, id);
						if (found) return found;
					}
				}
				return null;
			},
			findNodeInTree(tree, id) {
				// 递归查找树形数据中的节点（人员/部门/组织均可）
				for (let item of tree) {
					if (item.id === id) {
						return item;
					}
					if (item.children && item.children.length > 0) {
						const found = this.findNodeInTree(item.children, id);
						if (found) return found;
					}
				}
				return null;
			},
			goBack() {
                this.$emit('refresh')
            },
			init(id, isDetail) {
				this.dataForm.id = id || 0;
                this.visible = true;
                this.isDetail = isDetail || false;
				// 初始化选择值
				this.sskhValue = '';
				this.dysbValue = '';
				this.khxsryValue = '';
				this.bjxxValue = [];
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						request({
							url: '/api/Extend/Khsb/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.dataForm = res.data;
							// 处理数组字段
							if (!this.dataForm.sbtp) this.dataForm.sbtp = [];
							if (!this.dataForm.sbzl) this.dataForm.sbzl = [];
							
							// 根据编号设置选择值
							if (this.dataForm.sskhbh) {
								this.sskhValue = this.dataForm.sskhbh;
							}
							// 优先用 fl（设备id）还原关联产品选择，否则用 dysbbh 查找
							const resolveDysbValue = () => {
								if (this.dataForm.fl) {
									this.dysbValue = this.dataForm.fl;
									return;
								}
								if (this.dataForm.dysbbh) {
									const product = this.cpglOptions.find(item => (item.cpid || item.id) === this.dataForm.dysbbh);
									if (product) {
										this.dysbValue = product.id;
										this.dataForm.fl = product.id;
										if (!this.dataForm.sbmc) this.dataForm.sbmc = product.cpmc || '';
									}
								}
							};
							if (this.cpglOptions.length === 0) {
								this.getCpglOptions().then(() => resolveDysbValue());
							} else {
								resolveDysbValue();
							}
							if (this.dataForm.khxsrybh) {
								this.khxsryValue = this.dataForm.khxsrybh;
							}
							// 处理备件信息（从逗号分隔的字符串转换为数组）
							if (this.dataForm.bjxx && typeof this.dataForm.bjxx === 'string') {
								this.bjxxValue = this.dataForm.bjxx.split(',').filter(item => item);
							} else {
								this.bjxxValue = [];
							}
						})
					} else {
						// 新建时清空所有字段
						this.dataForm.sskh = '';
						this.dataForm.sskhbh = '';
						this.dataForm.dysb = '';
						this.dataForm.dysbbh = '';
						this.dataForm.khxsry = '';
						this.dataForm.khxsrybh = '';
						this.dataForm.sbmc = '';
						this.dataForm.ccbh = '';
						this.dataForm.sccj = '';
						this.dataForm.sszjbh = '';
						this.dataForm.ssjdbh = '';
						this.dataForm.sszjxh = '';
						this.dataForm.sbzt = '';
						this.dataForm.whls = undefined;
						this.dataForm.xcwhsj = undefined;
						this.dataForm.whzq = '';
						this.dataForm.whjh = undefined;
						this.dataForm.bjxx = '';
						this.dataForm.lsgz = '';
						this.dataForm.sbtp = [];
						this.dataForm.sbzl = [];
						this.bjxxValue = [];
					}
				})
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
						// 确保 bjxx 是字符串格式（从 bjxxValue 同步）
						if (Array.isArray(this.bjxxValue) && this.bjxxValue.length > 0) {
							this.dataForm.bjxx = this.bjxxValue.join(',');
						} else {
							this.dataForm.bjxx = '';
						}
						
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/Khsb`,
                                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/Khsb/' + 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>
