<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="900px" @confirm="handleSubmit"
			@close="handleClose">
			<div>
				<el-form ref="formRef" :model="formData" label-width="90px">
					<el-form-item label="转出类型">
						<el-radio-group v-model="formData.one_type">
							<el-radio label="1">门店</el-radio>
							<el-radio label="2">仓库</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="转出门店" prop="one_id" v-if="formData.one_type == 1">
						<el-select v-model="formData.one_id" filterable remote reserve-keyword placeholder="请选择转出方"
							remote-show-suffix :remote-method="remoteMethodStore" :loading="storeloading"
							@change="changeStore" style="width: 300px">
							<el-option v-for="item in storeList" :key="item.id"
								:label="`${item.name}|${item.phone}  (ID:${item.id})`" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="转出仓库" prop="one_id" v-if="formData.one_type == 2">
						<el-select v-model="formData.one_id" filterable remote reserve-keyword placeholder="请选择转出方"
							remote-show-suffix :remote-method="remoteMethodWarehouse" :loading="warehouseloading"
							@change="changeWarehouse" style="width: 300px">
							<el-option v-for="item in warehouseList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="转入类型">
						<el-radio-group v-model="formData.two_type">
							<el-radio label="1">门店</el-radio>
							<el-radio label="2">仓库</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="转入门店" prop="two_id" v-if="formData.two_type == 1">
						<el-select v-model="formData.two_id" filterable remote reserve-keyword placeholder="请选择转入方"
							remote-show-suffix :remote-method="remoteMethodStore" :loading="storeloading"
							style="width: 300px">
							<el-option v-for="item in storeList" :key="item.id"
								:label="`${item.name}|${item.phone}  (ID:${item.id})`" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="转入仓库" prop="two_id" v-if="formData.two_type == 2">
						<el-select v-model="formData.two_id" filterable remote reserve-keyword placeholder="请选择转出方"
							remote-show-suffix :remote-method="remoteMethodWarehouse" :loading="warehouseloading"
							style="width: 300px">
							<el-option v-for="item in warehouseList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="商品" prop="store_id">
						<div class="flex-1 w-full">
							<div class="mb-2">
								<el-button type="primary" @click="showProduct = true">添加商品</el-button>
							</div>
							<el-table :data="productList">
								<el-table-column label="商品ID" prop="id" show-overflow-tooltip />
								<el-table-column label="商品图片" prop="image" min-width="80">
									<template #default="{ row }">
										<el-image style="width: 50px; height: 50px" :src="row.image"
											:preview-teleported="true" />
									</template>
								</el-table-column>
								<el-table-column label="商品名称" prop="store_name" min-width="200" show-overflow-tooltip />
								<el-table-column label="单位" prop="unit_name" min-width="80" show-overflow-tooltip />
								<el-table-column label="数量" min-width="150">
									<template #default="{ row }">
										<el-input v-model="row.nums" />
									</template>
								</el-table-column>
								<el-table-column label="操作" width="120" fixed="right">
									<template #default="{ row }">
										<el-button type="danger" link @click="handleDeleteProdut(row.id)">
											删除
										</el-button>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</el-form-item>
				</el-form>
			</div>
			<el-dialog v-model="showProduct" title="选择商品" width="70%">
				<product-pop @onBindStore="onBindProduct" :is_branch="1" :store_id="store_id"
					:warehouse_id="warehouse_id" :is_warehouse="is_warehouse" :key="productModalKey"></product-pop>
			</el-dialog>
		</popup>
	</div>
</template>

<script lang="ts" setup name="storeProductEdit">
	import { ElMessage, type FormInstance } from 'element-plus'
	import { timeFormat } from '@/utils/util'
	import type { PropType } from 'vue'
	import { onMounted } from 'vue'
	import { apiWarehouseLists } from '@/api/warehouse'
	import {
		apiInventoryTransferAdd,
		apiInventoryTransferEdit,
		apiInventoryTransferDetail
	} from '@/api/inventory_transfer'
	import { apiSystemStoreLists } from '@/api/system_store'

	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()

	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')
	const store_id = ref(0) // 门店id
	const warehouse_id = ref(0) //仓库id
	const is_warehouse = ref(0) //是否仓库

	// 表单数据
	const formData = reactive({
		id: '',
		product_id: '',
		product_name: '',
		nums: '',
		before_nums: '',
		after_nums: '',
		one_type: '1',
		two_type: '1',
		one_id: '',
		one_name: '',
		two_id: '',
		two_name: '',
		warehouse_name: '',
		warehouse_name_two: ''
	})

	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '编辑商品调拨' : '新增商品调拨'
	})

	const showProduct = ref(false) // 选择商品列表是否显示
	// 商品列表
	const productList = ref([])
	// 删除已有商品
	const handleDeleteProdut = (id : number) => {
		productList.value = productList.value.filter((item : any) => item.id !== id)
	}
	// 选择商品
	const onBindProduct = (e : any[]) => {
		console.log(e);
		e.forEach((item : any) => {
			if (!productList.value.find((t : any) => t.id == item.id)) {
				productList.value.push(item)
			}
		})
		showProduct.value = false
	}

	const changeStore = (e : any) => {
		store_id.value = e
		resetUserId()
	}

	const changeWarehouse = (e : any) => {
		warehouse_id.value = e
		is_warehouse.value = 1
		resetUserId()
	}

	const storeloading = ref(false)
	const storeList = ref([])
	const remoteMethodStore = (e = '') => {
		storeloading.value = true
		apiSystemStoreLists({ name: e }).then((res) => {
			storeList.value = res.lists
			setTimeout(() => {
				storeloading.value = false
			}, 300)
		})
	}

	const warehouseloading = ref(false)
	const warehouseList = ref([])
	const remoteMethodWarehouse = (e = '') => {
		warehouseloading.value = true
		apiWarehouseLists({ name: e }).then((res) => {
			warehouseList.value = res.lists
			setTimeout(() => {
				warehouseloading.value = false
			}, 300)
		})
	}

	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}

	const handleClose = () => {
		emit('close')
	}

	// 提交按钮
	const handleSubmit = async () => {
		const product_arr = productList.value.map((item : any) => {
			return {
				product_id: item.product_id,
				nums: item.nums,
				purchase: item.purchases || 0,
				total_price: item.total_price || 0,
				manufacture: item.manufacture,
				expiration_date: item.expiration_date
			}
		})
		const data = { product_arr, ...formData }
		await formRef.value?.validate()
		mode.value == 'edit'
			? await apiInventoryTransferEdit(data)
			: await apiInventoryTransferAdd(data)
		popupRef.value?.close()
		emit('success')
	}

	// 获取详情
	const setFormData = async (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				formData[key] = data[key]
			}
		}
	}

	const getDetail = async (row : Record<string, any>) => {
		const data = await apiInventoryTransferDetail({
			id: row.id
		})
		setFormData(data)
	}

	const productModalKey = ref(0)
	const resetUserId = () => {
		productModalKey.value++
	}

	defineExpose({
		open,
		setFormData,
		getDetail
	})
</script>