<template>
	<Dialog v-model="dialogVisible" title="订单发货" width="70%">
		<el-form v-loading="formLoading" label-width="80px" style="padding: 10px;">
			<OrderBaseInfo ref="infoRef" :is-detail="true" :isDelivery="true" :id="formData.id" style="margin-bottom:30px" />
			<OrderProduct ref="infoRef" :isDelivery="true" :id="formData.id" />
		</el-form>
		<template #footer>
			<div style="text-align: left; display: flex; align-items: center">
				
				<el-form
ref="formRef" v-loading="formLoading" :model="formData" label-width="100px" style="display: flex;align-items: center"
					:rules="formRules">

					<el-form-item label="物流公司" prop="logisticsId" v-if="spuType == null">
						<el-select v-model="formData.logisticsId" placeholder="请选择" filterable :filter-method="customFilter">
							<el-option v-for="item in filteredList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="物流单号" prop="logisticsNo" v-if="spuType == null">
						<el-input v-model="formData.logisticsNo" placeholder="请录入快递单号"  onkeyup="this.value=this.value.replace(/[^\w]/g,'')"/>
					</el-form-item>
					<el-form-item label="发货备注" prop="deliveryRemark" v-if="spuType != null">
						<el-input v-model="formData.deliveryRemark"  />
					</el-form-item>
					<el-form-item label="附件" prop="attachment" v-if="spuType != null" style="display: flex;align-items: center">
						<SPuUploadImg v-model="formData.attachment"  :fileSize="5" />
					</el-form-item>
					<!-- <el-form-item>
						<el-button type="primary" plain>扫一扫</el-button>
					</el-form-item> -->
				</el-form>
			</div>
			<div style='text-align: right;'>
				<el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="dialogVisible = false">取 消</el-button>
			</div>

		</template>
	</Dialog>
</template>
<script lang="ts" setup>
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import * as TradeOrderApi from '@/api/mall/trade/order'
import OrderBaseInfo from '../components/OrderBaseInfo.vue'
import OrderProduct from '../components/OrderProduct.vue'
import { FormRules } from 'element-plus'

defineOptions({ name: 'OrderDeliveryForm' })

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const expressType = ref('express') // 如果值是 express，则是快递；none 则是无；未来做同城配送；
const spuType = ref() //如果值是1是实体商品 要输入物流公司物流单号 如果是0的话只需要输入发货备注
const formData = ref<TradeOrderApi.DeliveryVO>({
	id: 0, // 订单编号
	logisticsId: null, // 物流公司编号
	logisticsNo: '', // 物流编号
	deliveryRemark:'',
	attachment:''
})
const formRef = ref() // 表单 Ref
const formRules = reactive<FormRules>({
	logisticsId: [{ required: true,message: '请选择物流公司' }],
	logisticsNo: [{ required: true,message: '请输入快递单号' }],
	attachment: [{ required:true,message: '请上传发货附件' }],
})
/** 打开弹窗 */
const open = async (openType: any, orderId: any,sputype:any) => {
	console.log(sputype)
	resetForm()
	// 设置数据
	//如果是首页待办点进来的，即点进来将id设为从待办传来的id
	formData.value.id = orderId
	spuType.value = sputype 

	dialogVisible.value = true
	
}
const searchText = ref('');  // 用户输入的搜索文本

// 过滤列表基于搜索文本
const filteredList = computed(() => {
	if (!searchText.value) return deliveryExpressList.value;
	return deliveryExpressList.value.filter(item =>
		item.name.toLowerCase().includes(searchText.value.toLowerCase())
	);
});
const customFilter = (input) => {
	searchText.value = input;  // 更新当前的搜索文本
};
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
	// 提交请求
	formLoading.value = true
	try {
		if(spuType.value == null){
			if (formData.value.logisticsId === null) {
				message.error("请选择物流公司")
				return false
			} else if (formData.value.logisticsNo === "") {
				message.error("请输入物流单号")
				return false
			}
		}else{
			
			if (!formData.value.attachment) {
				message.error("请上传发货附件")
				return false
			}
		}
		const data = unref(formData)
		if (expressType.value === 'none') {
			// 无需发货的情况
			data.logisticsId = 0
			data.logisticsNo = ''
		}
		await TradeOrderApi.deliveryOrder(data)
		message.success("发货成功")
		dialogVisible.value = false
		// 发送操作成功的事件
		emit('success', true)
	} finally {
		formLoading.value = false
	}
}

/** 重置表单 */
const resetForm = () => {
	formData.value = {
		id: 0, // 订单编号
		logisticsId: null, // 物流公司编号
		logisticsNo: '' // 物流编号
	}
	formRef.value?.resetFields()
}
const deliveryExpressList = ref([])
onMounted(async () => {
	deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()
})

</script>

<style scoped lang="scss">
footer {
	.el-form-item {
		margin-right: 10px;
	}
}
</style>