<template>
	<ContentWrap v-loading="formLoading" style="overflow-y: auto;" class="ContentWrap">
		<div class="top" :style="{ height: (winHeight - 230) + 'px' }" style="overflow-y: auto;">
			<OrderBaseInfo ref="baseInfoRef" :is-detail="false" :id="orderId" />
			<OrderProduct ref="infoRef" :id="orderId" />
		</div>
		<div class="bottom">
			<el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="140px" style="" :rules="formRules">
				<el-form-item label="物流公司" prop="logisticsId" style="border: none;"  v-if="spuType != '0'">
					<el-select v-model="formData.logisticsId" style="width: 90%;" 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" style="border: none;" v-if="spuType != '0'">
					<el-input v-model="formData.logisticsNo" style="width: 90%;" placeholder="请录入快递单号" />
				</el-form-item>
				<el-form-item label="发货备注" prop="deliveryRemark" style="border: none;" v-if="spuType == '0'">
								<el-input v-model="formData.deliveryRemark"  />
							</el-form-item>
					<el-form-item label="附件" prop="attachment"  v-if="spuType == '0'" style="border: none;;display: flex;align-items: center">
						<SPuUploadImg v-model="formData.attachment"  :fileSize="1" />
					</el-form-item>
				<!-- <el-form-item>
						<el-button type="primary" plain>扫一扫</el-button>
					</el-form-item> -->
			</el-form>
			<div>
				<el-button @click="goback" :class="{ 'w-31': spuType == '0' }">返 回</el-button>
				<el-button :disabled="formLoading" type="primary" @click="remark"  :class="{ 'w-31': spuType == '0' }">商家备注</el-button>
				<el-button :disabled="formLoading" type="primary" @click="updateAddress" v-if="spuType != '0'">修改地址</el-button>
				<el-button :disabled="formLoading" type="primary" @click="submitForm"  :class="{ 'w-31': spuType == '0' }">发 货</el-button>
			</div>
		</div>
		<el-dialog v-model="dialogFormVisible" title="修改地址" width="90%">
			<el-form ref="formRef" v-loading="formLoading" :model="addressFormData" label-width="80">
      <el-form-item label="收件人" style="border: none;">
        <el-input v-model="addressFormData.receiverName" placeholder="请输入收件人名称" />
      </el-form-item>
      <el-form-item label="手机号" style="border: none;">
        <el-input v-model="addressFormData.receiverMobile" placeholder="请输入收件人手机号" />
      </el-form-item>
      <el-form-item label="所在地" style="border: none;">
        <el-tree-select
          v-model="addressFormData.receiverAreaId"
          :data="areaList"
          :props="defaultProps"
          :render-after-expand="true"
        />
      </el-form-item>
      <el-form-item label="详细地址" style="border: none;">
        <el-input
          v-model="addressFormData.receiverDetailAddress"
          :rows="3"
          placeholder="请输入收件人详细地址"
          type="textarea"
        />
      </el-form-item>
			
    </el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button type="primary" @click="submitAddressForm">
						确认
					</el-button>
				</div>
			</template>
		</el-dialog>
	</ContentWrap>
</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 { useRoute } from 'vue-router';
import { defaultProps } from '@/utils/tree'
import { getAreaTree } from '@/api/system/area'
const areaList = ref([]) // 地区列表
const spuType = ref() //如果值是1是实体商品 要输入物流公司物流单号 如果是0的话只需要输入发货备注
const route = useRoute();
const { push } = useRouter() // 路由跳转

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formRules = reactive({
	logisticsId: [{ required: true, message: '请选择物流公司' }],
	logisticsNo: [{ required: true, message: '请输入快递单号' }],
	attachment: [{ required: true, message: '请上传发货附件' }],
})
const baseInfoRef = ref(null)
const formData = ref<TradeOrderApi.DeliveryVO>({
	id: 0, // 订单编号
	logisticsId: null, // 物流公司编号
	logisticsNo: '', // 物流编号
	deliveryRemark: '',
	attachment: ''
})

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;  // 更新当前的搜索文本
};
const winHeight = window.innerHeight || document.documentElement.clientHeight;
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const orderId = ref(0)

const defaultRemark = ref('')
const deliveryExpressList = ref([])

orderId.value = route.params.id as unknown as number
spuType.value = route.params.spuType as unknown as number

const goback = () => {
	push({ name: 'Order' })
}
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
// 发货
const submitForm = async () => {
	// 提交请求
	formLoading.value = true
	try {
		if (spuType.value != '0') {
			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)
		await TradeOrderApi.deliveryOrder(data)
		message.success("发货成功")

		// 发送操作成功的事件
		emit('success', true)
		goback()
	} finally {
		formLoading.value = false
	}
}
// 获得备注
const getRemark = async (id) => {
	if (id) {
		const res = (await TradeOrderApi.getOrder(id)) as TradeOrderApi.OrderVO
		// 没有表单信息则关闭页面返回
		if (!res) {
			message.error('交易订单不存在')
			close()
		}
		defaultRemark.value = res.remark
	}
}
// 备注
const remark = async () => {
	const { value } = await ElMessageBox.prompt('请输入备注', '备注', {
		inputValue: defaultRemark,
		confirmButtonText: t('common.ok'),
		cancelButtonText: t('common.cancel'),
	})
	try {
		await TradeOrderApi.updateOrderRemark({ id: formData.value.id, remark: value })

		message.success(t('common.updateSuccess'))
		baseInfoRef.value.getDetail()
		// 发送操作成功的事件
		emit('success', true)
	} finally {
		formLoading.value = false
	}
}
let dialogFormVisible = ref(false)
const addressFormData = ref({
  id: 0, // 订单编号
  receiverName: '', // 收件人名称
  receiverMobile: '', // 收件人手机
  receiverAreaId: null, //收件人地区编号
  receiverDetailAddress: '' //收件人详细地址
})
const updateAddress = async () => {
	dialogFormVisible.value = true;
	addressFormData.value.id = baseInfoRef.value.formData.id;
	addressFormData.value.receiverName = baseInfoRef.value.formData.receiverName;
	addressFormData.value.receiverMobile = baseInfoRef.value.formData.receiverMobile;
	addressFormData.value.receiverAreaId = baseInfoRef.value.formData.receiverAreaId;
	addressFormData.value.receiverDetailAddress = baseInfoRef.value.formData.receiverDetailAddress;
};
const submitAddressForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = unref(addressFormData)
    await TradeOrderApi.updateOrderAddress(data)
    message.success(t('common.updateSuccess'))
    dialogFormVisible.value = false
		baseInfoRef.value.getDetail()
    // 发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}
onMounted(async () => {
	formData.value.id = orderId.value;
	addressFormData.value.id = orderId.value;
	await getRemark(formData.value.id)
	deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList();
	areaList.value = await getAreaTree()
	// 当子组件挂载时，改变父组件的样式
	document.getElementsByTagName('section')[1].style.padding = '0px';
	document.getElementsByTagName('section')[1].style.width = '100%';
	document.getElementsByTagName('section')[1].style.background = '#f5f7f9';
	document.getElementsByTagName('section')[1].querySelector('div').style.border = 'none';
});
onUnmounted(() => {
	// 当子组件卸载时，恢复父组件的原始样式
	document.getElementsByTagName('section')[1].style.width = 'auto';
	document.getElementsByTagName('section')[1].style.padding = '20px';
	document.getElementsByTagName('section')[1].style.background = 'var(--el-color-white)';
});
</script>



<style src="@/styles/MobileTab.css"  lang="scss" scoped></style>
<style lang="scss" scoped>
.w-31{
	width: 31% !important;
}
.bottom {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background: white;
	padding: 1rem;
	box-sizing: border-box;

	.el-button {
		width: 22%;
	}
}

.el-select-dropdown .el-select-dropdown__list .el-select-dropdown__item {
	max-width: 200px;
	/* 或者您想要的其他宽度 */
}
::v-deep .el-dialog__body,::v-deep .el-dialog__footer{
	padding: 10px;
}
</style>