<template>
	<a-page-header style="padding: 10px; font-size: 20px" @back="handleBack">
		<template #extra>
			<a-button v-if="route.query.type !== 'SEARCH'" key="1" type="primary" @click="onSubmitForm">保存</a-button>
		</template>
	</a-page-header>

	<a-card :bordered="false" title="物料">
		<DynamicForm
			:allDisabled="route.query.type === 'SEARCH'"
			:formItems="materialFormItems"
			:model="formData"
			:rules="formRules"
			ref="formRef1"
		/>
	</a-card>

	<a-card :bordered="false" class="mt-4">
		<a-tabs v-model:activeKey="activeKey">
			<a-tab-pane key="1" tab="基本信息">
				<DynamicForm
					:allDisabled="route.query.type === 'SEARCH'"
					:formItems="baseFormItems"
					:model="formData"
					:rules="formRules"
					ref="formRef2"
				/>
			</a-tab-pane>
			<a-tab-pane key="2" tab="单位信息" force-render>
				<DynamicForm
					:allDisabled="route.query.type === 'SEARCH'"
					:formItems="unitFormItems"
					:model="formData"
					:rules="formRules"
					ref="formRef3"
				/>
			</a-tab-pane>
			<a-tab-pane key="3" tab="包装关系" force-render>
				<a-table :dataSource="dataSource" :columns="columns">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'enabledState'">
							<a-switch
								:disabled="route.query.type === 'SEARCH'"
								checkedValue="ENABLE"
								unCheckedValue="DISABLED"
								checked-children="启用"
								un-checked-children="停用"
								v-model:checked="record.enabledState"
							/>
						</template>
						<template v-if="column.dataIndex === 'unitId'">
							<a-select
								:disabled="route.query.type === 'SEARCH'"
								style="width: 100%"
								placeholder="请选择单位"
								v-model:value="record.unitId"
								:options="unitOptions"
								:field-names="{
									label: 'name',
									value: 'id'
								}"
							/>
						</template>
						<template v-if="column.dataIndex === 'productQty'">
							<a-input-number
								:disabled="route.query.type === 'SEARCH'"
								style="width: 100%"
								v-model:value="record.productQty"
							/>
						</template>
						<template v-if="column.dataIndex === 'name'">
							<a-input :disabled="route.query.type === 'SEARCH'" v-model:value="record.name" />
						</template>
					</template>
				</a-table>
			</a-tab-pane>
			<a-tab-pane key="4" tab="商品推广" force-render>
				<a-form :model="productFormData" class="w-1/3" layout="vertical">
					<a-form-item label="是否启用" name="promoteEnabledState">
						<a-select
							v-model:value="productFormData.promoteEnabledState"
							:options="tool.dictList('COMMON_STATUS') || []"
						/>
					</a-form-item>
					<a-form-item label="商品推广 （支持上传：.png .jpg且大小为200k的图片，最多可上传5张）">
						<a-upload
							v-model:file-list="fileList"
							name="avatar"
							list-type="picture-card"
							class="avatar-uploader"
							:show-upload-list="false"
							action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
							:before-upload="beforeUpload"
							@change="handleChange"
						>
							<img v-if="imageUrl" :src="imageUrl" alt="avatar" />
							<div v-else>
								<loading-outlined v-if="loading"></loading-outlined>
								<plus-outlined v-else></plus-outlined>
								<div class="ant-upload-text">Upload</div>
							</div>
						</a-upload>
					</a-form-item>
					<a-form-item name="promoteUrl">
						<a-input v-model:value="productFormData.promoteUrl" placeholder="请输入商品链接" />
					</a-form-item>
				</a-form>
			</a-tab-pane>
		</a-tabs>
	</a-card>
</template>

<script setup name="materielDetail">
	import unitGroupsApi from '@/api/base/unit/unitGroupsApi'
	import unitApi from '@/api/base/unit/unitApi'

	import { required } from '@/utils/formRules'
	import useFormHandler from '@/hook/useFormHandler'
	import tool from '@/utils/tool'
	import { useRoute } from 'vue-router'
	import materialApi from '@/api/base/material/materialApi'
	import materialCategoryApi from '@/api/base/material/materialCategoryApi'
	import { message } from 'ant-design-vue'
	import sysBrandApi from '@/api/base/brand/sysBrandApi'
	const route = useRoute()

	const formRef1 = ref(null)
	const formRef2 = ref(null)
	const formRef3 = ref(null)

	let dataSource = ref([])
	let unitOptions = reactive([])
	let productFormData = ref({
		promoteEnabledState: 'ENABLE'
	})

	onMounted(async () => {
		formRefs.value = [formRef1.value, formRef2.value, formRef3.value]
		fetchData(route.query.type).then(async (res) => {
			if (res) {
				productFormData.value.promoteEnabledState = res.promoteEnabledState
				productFormData.value.promoteUrl = res.promoteUrl
				const packageData = await materialApi.materialPackageData({
					materialId: res.id
				})

				const unitList = await unitApi.sysUnitList({
					groupId: res.unitGroupId
				})

				unitFormItems.forEach((item) => {
					if (item.name !== 'unitGroupId') {
						item.attrs.options = unitList || []
					}
				})

				unitOptions = unitList

				dataSource.value = packageData
			}
		})

		if (route.query.type === 'ADD') {
			const packageType = tool.dictList('MATERIAL_PACKAGE_TYPE')
			packageType.forEach((item) => {
				dataSource.value.push({
					enabledState: 'ENABLE',
					number: item.value,
					type: item.label,
					name: item.label,
					unitId: '',
					productQty: ''
				})
			})
		}

		// 单位列表
		const unitList = await unitGroupsApi.sysUnitGroupList({
			enabledState: 'ENABLE'
		})

		unitList &&
			unitFormItems.forEach((item) => {
				if (item.name === 'unitGroupId') {
					item.attrs.options = unitList
				}
			})

		// 物料类型
		const materialCategoryList = await materialCategoryApi.materialCategoryTree({
			enabledState: 'ENABLE'
		})

		materialCategoryList &&
			baseFormItems.forEach((item) => {
				if (item.name === 'categoryId') {
					item.attrs.options = materialCategoryList
				}
			})

		// 品牌列表
		const brandList = await sysBrandApi.sysBrandList({
			enabledState: 'ENABLE'
		})

		brandList &&
			baseFormItems.forEach((item) => {
				if (item.name === 'brandId') {
					item.attrs.options = brandList
				}
			})
	})

	let activeKey = ref('1')

	// 选择单位组
	const handleChangeUnitGroup = (value) => {
		unitFormItems.forEach((item) => {
			if (item.name !== 'unitGroupId') {
				formData[item.name] = null
			}
		})

		unitApi
			.sysUnitList({
				groupId: value
			})
			.then((res) => {
				unitFormItems.forEach((item) => {
					if (item.name !== 'unitGroupId') {
						item.attrs.options = res
					}
				})

				unitOptions = res
				const resFilter = res.filter((item) => item.isBase === 'YES')
				if (resFilter.length > 0) formData.baseUnitId = resFilter[0].id
			})
	}

	const onSubmitForm = () => {
		console.log(productFormData.value, 'productFormData.value')
		onSubmit({
			isDeep: true,
			materialPackageList: dataSource.value,
			...formData,
			...productFormData.value
		})
	}

	// 图片上传

	function getBase64(img, callback) {
		const reader = new FileReader()
		reader.addEventListener('load', () => callback(reader.result))
		reader.readAsDataURL(img)
	}
	const fileList = ref([])
	const loading = ref(false)
	const imageUrl = ref('')
	const handleChange = (info) => {
		if (info.file.status === 'uploading') {
			loading.value = true
			return
		}
		if (info.file.status === 'done') {
			// Get this url from response in real world.
			getBase64(info.file.originFileObj, (base64Url) => {
				imageUrl.value = base64Url
				loading.value = false
			})
		}
		if (info.file.status === 'error') {
			loading.value = false
			message.error('upload error')
		}
	}
	const beforeUpload = (file) => {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
		if (!isJpgOrPng) {
			message.error('You can only upload JPG file!')
		}
		const isLt2M = file.size / 1024 / 1024 < 2
		if (!isLt2M) {
			message.error('Image must smaller than 2MB!')
		}
		return isJpgOrPng && isLt2M
	}

	const formRules = {
		name: [required('请输入名称')],
		type: [required('请输入类型')],
		appid: [required('请输入AppID')],
		secret: [required('请输入AppSecret')]
	}

	const materialFormItems = [
		{
			label: '编码：',
			name: 'number',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入编码'
			}
		},
		{
			label: '名称：',
			name: 'name',
			type: 'a-input',
			span: 6,
			rules: [required('请输入名称')],
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '简称：',
			name: 'shortName',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '别名：',
			name: 'alias',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '规格型号：',
			name: 'specification',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '包装比例：',
			name: 'packageProportion',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '助记码：',
			name: 'mnemonicCode',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '可用状态：',
			name: 'enabledState',
			type: 'a-select',
			span: 6,
			attrs: {
				placeholder: '请选择可用状态',
				options: tool.dictList('COMMON_STATUS')
			},
			defaultValue: 'ENABLE'
		}
	]

	const baseFormItems = reactive([
		{
			label: '物料类型：',
			name: 'categoryId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择物料类型')],
			attrs: {
				placeholder: '请选择物料类型',
				options: tool.dictList('OFFICIAL_ACCOUNT_TYPE'),
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '品牌：',
			name: 'brandId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择品牌')],
			attrs: {
				placeholder: '请选择品牌',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '最高库存：',
			name: 'maxInventory',
			type: 'a-input-number',
			span: 6,
			attrs: {
				placeholder: '请输入最高库存'
			}
		},
		{
			label: '最低库存：',
			name: 'minInventory',
			type: 'a-input-number',
			span: 6,
			attrs: {
				placeholder: '请输入最高库存'
			}
		},
		{
			label: '保质期：',
			name: 'shelfLife',
			type: 'a-input-number',
			span: 6,
			rules: [required('请选择保质期')],
			attrs: {
				placeholder: '请输入保质期',
				allowClear: true
			}
		},
		{
			label: '统一零售价：',
			name: 'retailPrice',
			type: 'a-input-number',
			span: 6,
			attrs: {
				placeholder: '请输入统一零售价',
				allowClear: true
			}
		},
		{
			label: '商品条形码：',
			name: 'barcode',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入商品条形码',
				allowClear: true
			}
		},
		{
			label: '保质期单位：',
			name: 'shelfLifeUnit',
			type: 'a-select',
			span: 6,
			rules: [required('请选择保质期单位')],
			attrs: {
				placeholder: '请选择保质期单位',
				options: tool.dictList('DATE_UNIT')
			}
		},
		{
			label: '最大包装数量：',
			name: 'maxPackageQuantity',
			type: 'a-input-number',
			span: 6,
			rules: [required('请输入最大包装数量')],
			attrs: {
				placeholder: '请输入最大包装数量',
				allowClear: true
			}
		},
		{
			label: '批次管理：',
			name: 'batchManage',
			type: 'a-select',
			span: 6,
			attrs: {
				placeholder: '请选择批次管理',
				options: tool.dictList('COMMON_STATUS')
			}
		},
		{
			label: '备注：',
			name: 'remarks',
			type: 'a-textarea',
			span: 24,
			attrs: {
				placeholder: '请输入备注',
				allowClear: true
			}
		}
	])

	const unitFormItems = reactive([
		{
			label: '单位组：',
			name: 'unitGroupId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择单位组')],
			attrs: {
				placeholder: '请选择类型',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				},
				onChange: handleChangeUnitGroup
			}
		},
		{
			label: '基本单位：',
			name: 'baseUnitId',
			type: 'a-select',
			span: 6,
			attrs: {
				placeholder: '请选择类型',
				options: [],
				disabled: true,
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '采购单位：',
			name: 'purchaseUnitId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择采购单位')],
			attrs: {
				placeholder: '请选择类型',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '分销单位：',
			name: 'distrUnitId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择分销单位')],
			attrs: {
				placeholder: '请输入备注',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},

		{
			label: '生产单位：',
			name: 'produceUnitId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择生产单位')],
			attrs: {
				placeholder: '请输入备注',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '销售单位：',
			name: 'saleUnitId',
			type: 'a-select',
			span: 6,
			rules: [required('请选择销售单位')],
			attrs: {
				placeholder: '请输入备注',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '库存单位：',
			name: 'storeUnitId',
			type: 'a-select',
			rules: [required('请选择库存单位')],
			span: 6,
			attrs: {
				placeholder: '请输入备注',
				options: [],
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		}
	])

	const columns = [
		{
			title: '启用',
			dataIndex: 'enabledState',
			editable: true,
			align: 'center'
		},
		{
			title: '条码类型编码',
			dataIndex: 'number',
			editable: true,
			align: 'center'
		},
		{
			title: '条码类型',
			dataIndex: 'type',
			editable: true,
			align: 'center'
		},
		{
			title: '包装关系名称',
			dataIndex: 'name',
			editable: true,
			align: 'center'
		},
		{
			title: '单位',
			dataIndex: 'unitId',
			editable: true,
			align: 'center'
		},
		{
			title: '产品数',
			dataIndex: 'productQty',
			editable: true,
			align: 'center'
		}
	]

	const { state, formData, submitLoading, formRefs, onSubmit, handleBack, fetchData } = useFormHandler(
		[...materialFormItems, ...baseFormItems, ...unitFormItems],
		{
			submitForm: materialApi.materialSubmitForm,
			getDetail: materialApi.materialDetail
		}
	)
</script>
