<template>
	<view class="container">
		<VNavigationBar background-color="#fff" :title="title" title-color="#333"></VNavigationBar>
		<view class="listBox">
			<view class="list">
				<view class="formItem">
					<text class="formLabel require">配件名称</text>
					<input type="text" style="text-align: right" v-model="formData.name" placeholder="请输入配件名称" />
				</view>
				<view class="formItem">
					<text class="formLabel require">进价</text>
					<input type="text" style="text-align: right" v-model="formData.purPrice" placeholder="请输入配件名称" />
				</view>
				<view class="formItem">
					<text class="formLabel require">销售价格</text>
					<input type="text" style="text-align: right" v-model="formData.price" placeholder="请输入配件名称" />
				</view>
				<view class="formItem">
					<text class="formLabel require">所属分类</text>
					<picker @change="typePickerChange" :value="typeIndex" :range="allTypeNameList">
						<view class="uni-input">{{allTypeNameList[typeIndex]}}</view>
					</picker>
				</view>
				<view class="formItem">
					<text class="formLabel require">计量单位</text>
					<picker @change="unitPickerChange" :value="unitIndex" :range="allUnitNameList">
						<view class="uni-input">{{allUnitNameList[unitIndex]}}</view>
					</picker>
				</view>
				<view class="formItem">
					<text class="formLabel">规格型号</text>
					<input type="text" style="text-align: right" v-model="formData.model" placeholder="请输入规格型号" />
				</view>
				<view class="formItem">
					<text class="formLabel">来源</text>
					<picker @change="fromPickerChange" :value="fromIndex" :range="allFromNameList">
						<view class="uni-input">{{allFromNameList[fromIndex]}}</view>
					</picker>
				</view>
				<view class="formItem">
					<text class="formLabel">配件属性</text>
					<picker @change="attributePickerChange" :value="attributeIndex" :range="allAttributeNameList">
						<view class="uni-input">{{allAttributeNameList[attributeIndex]}}</view>
					</picker>
				</view>
				<view class="formItem">
					<text class="formLabel">状态</text>
					<view>
						<radio-group v-model="formData.status">
							<label class="radio-label" v-for="(item, index) in radioOptions" :key="index">
								<radio :value="item.value" :checked="item.checked">{{ item.label }}</radio>
							</label>
						</radio-group>
					</view>
				</view>
				<view class="formItem">
					<text class="formLabel">条形码</text>
					<input type="text" style="text-align: right" v-model="formData.barCode" placeholder="请输入条形码" />
				</view>
				<view class="formItem">
					<text class="formLabel">商品编码</text>
					<input type="text" style="text-align: right" v-model="formData.code" placeholder="请输入商品编码" />
				</view>
				<view class="formItem">
					<text class="formLabel">适用子公司</text>
					<text class="formValue"></text>
				</view>
				<view style="padding-bottom: 60rpx;border-bottom: 1px solid #ddd;" class="formItem">
					<checkbox-group v-model="checkedCorpIdList" @change="cs">
						<checkbox v-for="(item, index) in allCompanyList" :key="index" :value="item.id"
							:checked="item.checked">{{ item.corpName }}</checkbox>
					</checkbox-group>
				</view>
				<view class="formItem">
					<text class="formLabel">适用车型</text>
					<text class="formValue"></text>
				</view>
				<view style="padding-bottom: 60rpx;border-bottom: 1px solid #ddd;" class="formItem">
					<textarea style="height: 50px" auto-height placeholder="请输入适用车型" v-model="formData.carModel" />
				</view>
				<view class="formItem">
					<text class="formLabel">备注</text>
					<text class="formValue"></text>
				</view>
				<view style="padding-bottom: 60rpx;border-bottom: 1px solid #ddd;" class="formItem">
					<textarea style="height: 50px" auto-height placeholder="请输入备注" v-model="formData.remark" />
				</view>
			</view>
		</view>
		<view class="footer">
			<text class="label"></text>
			<text class="repairNum"></text>
			<view class="submit" @click="submit">保存</view>
		</view>
	</view>
</template>

<script>
	import VNavigationBar from "@/components/VNavigationBar.vue";
	import request from '@/utils/request';
	import {
		getDictTextByCodeAndValue,
		createUniqueCodeByHead
	} from "@/utils/utils";
	import {
		getUserInfo,
		getJSONData
	} from '@/utils/auth.js'

	export default {
		components: {
			VNavigationBar
		},
		data() {
			return {
				//父组件传入的数据
				formData: {
					name: "",
					type: "",
					unit: "",
					model: "",
					dataForm: "",
					attribute: "",
					status: "",
					barCode: "",
					code: "",
					corpId: "",
					carModel: "",
					remark: "",
				},
				// 状态单选按钮的选项数组
				radioOptions: [{
						label: '启用',
						value: '01',
						checked: true
					},
					{
						label: '禁用',
						value: '02',
						checked: false
					}
				],
				//所有可选分类
				allTypeList: [],
				//所有可选分类-只有名称
				allTypeNameList: [],
				//选中的分类下标
				typeIndex: 0,
				//所有可选计量单位
				allUnitList: [],
				//所有可选计量单位-只有名称
				allUnitNameList: [],
				//选中的计量单位下标
				unitIndex: 0,
				//所有可选来源
				allFromList: [],
				//所有可选来源-只有名称
				allFromNameList: [],
				//选中的来源下标
				fromIndex: 0,
				//所有可选配件属性
				allAttributeList: [],
				//所有可选配件属性-只有名称
				allAttributeNameList: [],
				//选中的配件属性下标
				attributeIndex: 0,
				//所有可选子公司
				allCompanyList: [],
				//选中的子公司id
				checkedCorpIdList: [],
				//页面标题
				title: '新增配件',
			};
		},
		onLoad(options) {
			if (options.id) {
				this.title = '修改配件'
				// 初始化完成后查询配件信息
				this.init().then(() => {
					this.selectWares(options.id)
				})
			} else {
				this.init()
			}
		},
		computed: {

		},
		methods: {
			cs(e) {
				this.checkedCorpIdList = e.detail.value
			},
			/**
			 * 初始化配件数据
			 */
			async init() {
				try {
					// 等待所有数据加载完成
					await Promise.all([
						this.selectBaseType(),
						this.selectBaseUnit(),
						this.selectDataFrom(),
						this.selectAttribute(),
						this.selectCompany()
					])
				} catch (error) {
					console.error('初始化数据失败:', error)
				}
			},
			/**
			 * 查所有可选分类
			 */
			selectBaseType() {
				request({
					url: '/admin-api/conf/baseType/list',
					method: 'get',
					params: {
						type: "02"
					}
				}).then((res) => {
					console.log(res)
					if (res.code == 200 && res.data.length > 0) {
						this.allTypeList = res.data
						this.allTypeNameList = res.data.map((item) => {
							return item.name
						})
					}
				})
			},
			/**
			 * 查所有可选计量单位
			 */
			selectBaseUnit() {
				request({
					url: '/admin-api/system/dict-data/type',
					method: 'get',
					params: {
						type: "repair_unit"
					}
				}).then((res) => {
					console.log(res)
					if (res.code == 200) {
						this.allUnitList = res.data
						this.allUnitNameList = res.data.map((item) => {
							return item.label
						})
					}
				})
			},
			/**
			 * 查询配件信息
			 */
			selectWares(id) {
				request({
					url: `/admin-api/repair/wares/get`,
					method: 'get',
					params: {
						id
					}
				}).then((res) => {
					if (res.code === 200 && res.data) {
						this.formData = res.data

						// 设置分类选中项
						if (this.allTypeList.length > 0 && res.data.type) {
							const typeIndex = this.allTypeList.findIndex(item => item.id === res.data.type)
							if (typeIndex !== -1) {
								this.typeIndex = typeIndex
							}
						}

						// 设置计量单位选中项
						if (this.allUnitList.length > 0 && res.data.unit) {
							const unitIndex = this.allUnitList.findIndex(item => item.value === res.data.unit)
							if (unitIndex !== -1) {
								this.unitIndex = unitIndex
							}
						}

						// 设置来源选中项
						if (this.allFromList.length > 0 && res.data.dataForm) {
							const fromIndex = this.allFromList.findIndex(item => item.value === res.data.dataForm)
							if (fromIndex !== -1) {
								this.fromIndex = fromIndex
							}
						}

						// 设置配件属性选中项
						if (this.allAttributeList.length > 0 && res.data.attribute) {
							const attributeIndex = this.allAttributeList.findIndex(item => item.value === res.data
								.attribute)
							if (attributeIndex !== -1) {
								this.attributeIndex = attributeIndex
							}
						}

						// 设置子公司选中项
						if (res.data.corpIds && res.data.corpIds.length > 0) {
							this.checkedCorpIdList = res.data.corpIds
							// 同时更新checkbox的选中状态
							this.allCompanyList.forEach(item => {
								item.checked = res.data.corpIds.includes(item.id)
							})
						}

						// 设置状态单选按钮
						if (res.data.status) {
							this.radioOptions.forEach(item => {
								item.checked = item.value === res.data.status
							})
						}
					}
				})
			},
			/**
			 * 查所有可选属性
			 */
			selectAttribute() {
				request({
					url: '/admin-api/system/dict-data/type',
					method: 'get',
					params: {
						type: "wares_attribute"
					}
				}).then((res) => {
					console.log(res)
					if (res.code == 200) {
						this.allAttributeList = res.data
						this.allAttributeNameList = res.data.map((item) => {
							return item.label
						})
					}
				})
			},
			/**
			 * 查所有可选子公司
			 */
			selectCompany() {
				request({
					url: '/admin-api/base/company/list',
					method: 'get'
				}).then((res) => {
					console.log(res)
					if (res.code == 200 && res.data.length > 0) {
						this.allCompanyList = res.data
						this.allCompanyList.map((item) => {
							item.checked = false
						})
					}
				})
			},
			/**
			 * 查所有可选来源
			 */
			selectDataFrom() {
				request({
					url: '/admin-api/system/dict-data/type',
					method: 'get',
					params: {
						type: "wares_data_form"
					}
				}).then((res) => {
					console.log(res)
					if (res.code == 200) {
						this.allFromList = res.data
						this.allFromNameList = res.data.map((item) => {
							return item.label
						})
					}
				})
			},
			/**
			 * 选分类
			 */
			typePickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.typeIndex = e.detail.value
			},
			/**
			 * 选计量单位
			 */
			unitPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.unitIndex = e.detail.value
			},
			/**
			 * 选来源
			 */
			fromPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.fromIndex = e.detail.value
			},
			/**
			 * 选属性
			 */
			attributePickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.attributeIndex = e.detail.value
			},
			/**
			 * 新增/修改配件
			 */
			submit() {
				// 校验必填
				if (!this.formData.name) {
					uni.showToast({
						title: '请输入配件名称！',
						icon: 'none'
					})
					return
				}

				// 组装可用的子公司
				if (this.checkedCorpIdList.length > 0) {
					this.formData.corpId = this.checkedCorpIdList.join()
				}

				// 组装其他字段
				this.formData.type = this.allTypeList[this.typeIndex].id
				this.formData.unit = this.allUnitList[this.unitIndex].value
				this.formData.dataForm = this.allFromList[this.fromIndex].value
				this.formData.attribute = this.allAttributeList[this.attributeIndex].value

				// 判断是新增还是修改
				const isEdit = !!this.formData.id
				const url = isEdit ? '/admin-api/repair/wares/update' : '/admin-api/repair/wares/create'
				const method = isEdit ? 'put' : 'post'
				const successMsg = isEdit ? '修改成功！' : '新增成功！'

				request({
					url: url,
					method: method,
					data: this.formData
				}).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: successMsg,
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 700)
					} else {
						uni.showToast({
							title: '操作失败，请联系管理员！',
							icon: 'none'
						})
					}
				})
			}

		}
	}
</script>

<style lang="scss">
	.container {
		height: 100%;
		background-color: #F3F5F7;
		display: flex;
		flex-direction: column;
	}

	.listBox {
		padding: 30 rpx 32 rpx;
		flex: 1;
		height: 0;
	}

	.list {
		background-color: #fff;
		padding: 0 30rpx;
		height: 100%;
		overflow: auto;
	}

	.formItem {
		box-sizing: border-box;
		margin: 0 auto;
		padding: 30rpx;

		display: flex;
		align-items: center;
		justify-content: space-between;
		column-gap: 20rpx;

		border-bottom: 1rpx solid #DDDDDD;
	}

	.require::before {
		content: "*";
		color: red;
	}

	.formLabel {
		font-size: 32rpx;
		color: #333333;
	}

	.formValue {
		flex: 1;
		width: 0;
		text-align: right;
		font-size: 32rpx;
		color: #999999;
	}

	.repairBottom {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.repairDesc {
		font-size: 28rpx;
		color: #858BA0;
	}

	.repairUnit {
		color: #333333;
	}

	.footer {
		padding: 14rpx 32rpx;
		background-color: #fff;
		display: flex;
		align-items: center;

		.repairNum {
			flex: 1;
			width: 0;
			margin-right: 10rpx;
		}

		.submit {
			width: 208rpx;
			height: 72rpx;
			background: #0174F6;
			border-radius: 38rpx 38rpx 38rpx 38rpx;
			text-align: center;
			line-height: 72rpx;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}
</style>