<template>
	<el-dialog :title="!dataForm.id ? '新建产品' : '编辑产品'" :close-on-click-modal="false" :visible.sync="visible"
		class="NCC-dialog NCC-dialog_center" lock-scroll width="800px">
		<el-form ref="elForm" :model="dataForm" size="small" label-width="120px" label-position="right" :rules="rules">
			<el-row :gutter="15">
				<el-col :span="12">
					<el-form-item label="产品名称" prop="productName">
						<el-input v-model="dataForm.productName" placeholder="请输入产品名称" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品类别" prop="productCategory">
						<el-input v-model="dataForm.productCategory" placeholder="请输入产品类别" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="负责部门" prop="departmentId">
						<el-select v-model="dataForm.departmentId" placeholder="请选择负责部门" clearable filterable
							:style='{"width":"100%"}'>
							<el-option v-for="dept in departmentList" :key="dept.id" :label="dept.name"
								:value="dept.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="标准单位" prop="standardUnit">
						<el-input v-model="dataForm.standardUnit" placeholder="请输入标准单位" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12">
					<el-form-item label="上架状态" prop="onShelfStatus">
						<el-select v-model="dataForm.onShelfStatus" placeholder="请选择上架状态" clearable
							:style='{"width":"100%"}'>
							<el-option label="上架" :value="1" />
							<el-option label="下架" :value="0" />
						</el-select>
					</el-form-item>
				</el-col> -->
				<el-col :span="12">
					<el-form-item label="统计分类" prop="statisticsCategory">
						<el-input v-model="dataForm.statisticsCategory" placeholder="请输入统计分类" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="归属仓库" prop="warehouse">
						<el-input v-model="dataForm.warehouse" placeholder="请输入归属仓库" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="供应商名称" prop="supplierName">
						<el-input v-model="dataForm.supplierName" placeholder="请输入供应商名称" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="合同签订日期" prop="contractSignDate">
						<el-date-picker v-model="dataForm.contractSignDate" type="date" placeholder="请选择合同签订日期"
							value-format="yyyy-MM-dd" format="yyyy-MM-dd" :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="合同结束日期" prop="contractEndDate">
						<el-date-picker v-model="dataForm.contractEndDate" type="date" placeholder="请选择合同结束日期"
							value-format="yyyy-MM-dd" format="yyyy-MM-dd" :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="备注" prop="remark">
						<el-input v-model="dataForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息"
							clearable :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
	data() {
		return {
			visible: false,
			btnLoading: false,
			departmentList: [], // 部门列表
			dataForm: {
				id: undefined,
				productName: '',
				productCategory: '',
				departmentId: '',
				standardUnit: '',
				onShelfStatus: 1,
				statisticsCategory: '',
				warehouse: '',
				supplierName: '',
				contractSignDate: '',
				contractEndDate: '',
				remark: ''
			},
			rules: {
				productName: [
					{ required: true, message: '请输入产品名称', trigger: 'blur' }
				],
				onShelfStatus: [
					{ required: true, message: '请选择上架状态', trigger: 'change' }
				]
			}
		}
	},
	methods: {
		init(id) {
			this.visible = true
			this.dataForm = {
				id: undefined,
				productName: '',
				productCategory: '',
				departmentId: '',
				standardUnit: '',
				onShelfStatus: 1,
				statisticsCategory: '',
				warehouse: '',
				supplierName: '',
				contractSignDate: '',
				contractEndDate: '',
				remark: ''
			}
			this.getDepartmentList()
			if (id) {
				// 编辑模式，获取产品详情
				this.getProductDetail(id)
			}
		},
		// 获取部门列表
		getDepartmentList() {
			request({
				url: `/api/permission/Organize/96240625-934F-490B-8AA6-0BC775B18468/Department`,
				method: 'GET',
			}).then((res) => {
				if (res.code == 200 && res.data.list && res.data.list.length > 0) {
					this.departmentList = res.data.list.map(item => ({
						id: item.id,
						name: item.fullName,
					}))
				} else {
					this.departmentList = []
				}
			}).catch(() => {
				this.departmentList = []
			})
		},
		// 格式化日期：从ISO格式或Date对象转换为 yyyy-MM-dd 格式字符串
		formatDateToYYYYMMDD(dateValue) {
			// 处理空值
			if (!dateValue && dateValue !== 0) return ''
			
			let date = null
			
			// 如果是 Date 对象
			if (dateValue instanceof Date) {
				date = dateValue
			}
			// 如果是字符串
			else if (typeof dateValue === 'string') {
				// 如果已经是 yyyy-MM-dd 格式，直接返回
				if (/^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
					return dateValue
				}
				// 尝试解析为日期
				date = new Date(dateValue)
			}
			// 如果是数字（时间戳）
			else if (typeof dateValue === 'number') {
				date = new Date(dateValue)
			}
			// 其他类型，尝试转换为字符串再解析
			else {
				date = new Date(String(dateValue))
			}
			
			// 验证日期是否有效
			if (date && !isNaN(date.getTime())) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			}
			
			// 如果无法解析，返回空字符串
			return ''
		},
		// 获取产品详情
		getProductDetail(id) {
			request({
				url: `/api/Extend/LqProduct/GetInfo`,
				method: 'GET',
				data: {
					id: id
				}
			}).then(res => {
				if (res.code == 200 && res.data) {
					const product = res.data
					this.dataForm = {
						id: product.id,
						productName: product.productName || '',
						productCategory: product.productCategory || '',
						departmentId: product.departmentId || '',
						standardUnit: product.standardUnit || '',
						onShelfStatus: product.onShelfStatus !== undefined ? product.onShelfStatus : 1,
						statisticsCategory: product.statisticsCategory || '',
						warehouse: product.warehouse || '',
						supplierName: product.supplierName || '',
						contractSignDate: this.formatDateToYYYYMMDD(product.contractSignDate),
						contractEndDate: this.formatDateToYYYYMMDD(product.contractEndDate),
						remark: product.remark || ''
					}
				} else {
					this.$message({
						type: 'error',
						message: res.msg || '获取产品详情失败'
					})
				}
			}).catch(err => {
				console.error('获取产品详情失败:', err)
				this.$message({
					type: 'error',
					message: '获取产品详情失败'
				})
			})
		},
		dataFormSubmit() {
			this.$refs.elForm.validate((valid) => {
				if (!valid) {
					return false
				}
				this.btnLoading = true
				const url = this.dataForm.id ? '/api/Extend/LqProduct/Update' : '/api/Extend/LqProduct/Create'
				const method = this.dataForm.id ? 'PUT' : 'POST'
				// 处理日期格式，确保提交ISO格式
				let contractSignDate = this.dataForm.contractSignDate
				let contractEndDate = this.dataForm.contractEndDate
				if (contractSignDate && !contractSignDate.includes('T')) {
					const date = new Date(contractSignDate)
					contractSignDate = date.toISOString()
				}
				if (contractEndDate && !contractEndDate.includes('T')) {
					const date = new Date(contractEndDate)
					contractEndDate = date.toISOString()
				}
				request({
					url: url,
					method: method,
					data: {
						id: this.dataForm.id,
						productName: this.dataForm.productName,
						productCategory: this.dataForm.productCategory,
						departmentId: this.dataForm.departmentId,
						standardUnit: this.dataForm.standardUnit,
						onShelfStatus: this.dataForm.onShelfStatus,
						statisticsCategory: this.dataForm.statisticsCategory,
						warehouse: this.dataForm.warehouse,
						supplierName: this.dataForm.supplierName,
						contractSignDate: contractSignDate,
						contractEndDate: contractEndDate,
						remark: this.dataForm.remark
					}
				}).then(res => {
					this.btnLoading = false
					this.$message({
						type: 'success',
						message: res.msg || (this.dataForm.id ? '编辑成功' : '创建成功'),
						onClose: () => {
							this.visible = false
							this.$emit('refresh')
						}
					})
				}).catch(() => {
					this.btnLoading = false
				})
			})
		}
	}
}
</script>

<style lang="scss" scoped>
</style>

