<template>

		<ContentWrap v-loading="formLoading" style="overflow-y: auto;" class="ContentWrap">
			<div class="top" style="position: relative;overflow: hidden;">
				<!-- <SPuUploadImg v-model="formData.picUrl" :disabled="isDetail" /> -->
				<van-tabs v-model:active="activeName">
					<van-tab title="基本信息" name="info" />
					<van-tab title="价格/规格/型号" name="sku" />
					<van-tab title="详情" name="description" />
					<van-tab title="评价" name="comment" />
					<van-tab title="客服" name="service" />
					<van-tab title="售后" name="aftersale" />
					<van-tab title="物流设置" name="delivery" />
					<!-- <van-tab title="其它设置" name="other" /> -->
			</van-tabs>
			</div>
			<div class="bottom">
				<div v-show="activeName == 'info'">
					<InfoForm ref="infoRef" :is-detail="isDetail" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'sku'">
					<SkuForm ref="skuRef" :is-detail="false" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'delivery'">
					<DeliveryForm ref="deliveryRef" :is-detail="isDetail" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'description'">
					<DescriptionForm ref="descriptionRef" :is-detail="isDetail" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'other' ">
					<OtherForm ref="otherRef" :is-detail="isDetail" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'comment' ">
					<Comment  :is-detail="isDetail" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'service'">
					<Service :is-detail="isDetail" :propFormData="formData" />
				</div>
				<div v-show="activeName == 'aftersale'">
					<AfterSale :productId="productId" openSource="Spu" />
				</div>
			</div>

			<div style="clear: both;"></div>
				<el-button v-show="activeName == 'sku'" :loading="formLoading" type="primary" @click="submitForm" style="position: fixed;width: 90%;bottom: 0px;left: 50%;transform: translateX(-50%);z-index: 111111;">
						保存
					</el-button>
		</ContentWrap>

	<!-- </div> -->

</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
const message = useMessage() // 消息弹窗
import * as ProductSpuApi from '@/api/mall/product/spu'
import InfoForm from './InfoForm.vue'
import DescriptionForm from './DescriptionForm.vue'
import OtherForm from './OtherForm.vue'
import SkuForm from './SkuForm.vue'
import DeliveryForm from './DeliveryForm.vue'
import Service from '../components/Service.vue'
import AfterSale from '@/components/ZxTemplate/AfterSale/AfterSale.vue'
// 创建一个响应式对象
const spuTypeChange = reactive({
	value: 0
});
const highPrecisionChange = reactive({
  value: false
});
provide('highPrecisionChange', highPrecisionChange);
const emit = defineEmits(['success']) 
provide('spuTypeChange', spuTypeChange);
import Comment from '../components/Comment.vue'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'
import { number } from 'vue-types'
defineOptions({ name: 'ProductSpuForm' })
const { t } = useI18n() // 国际化
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(true) // 是否查看详情
const infoRef = ref() // 商品信息 Ref
const skuRef = ref() // 商品规格 Ref
const deliveryRef = ref() // 物流设置 Ref
const descriptionRef = ref() // 商品详情 Ref
const otherRef = ref() // 其他设置 Ref
// SPU 表单数据
const formData = ref<ProductSpuApi.Spu>({
	name: '', // 商品名称
	categoryId: undefined, // 商品分类
	keyword: '', // 关键字
	picUrl: '', // 商品封面图
	producerArea:'',
	spuType:undefined,
	sliderPicUrls: [], // 商品轮播图
	introduction: '', // 商品简介
	deliveryTypes: [], // 配送方式数组
	deliveryTemplateId: undefined, // 运费模版
	brandId: undefined, // 商品品牌
	specType: false, // 商品规格
	subCommissionType: false, // 分销类型
	skus: [
		{
			price: 0, // 商品价格
			marketPrice: 0, // 市场价
			costPrice: 0, // 成本价
			barCode: '', // 商品条码
			picUrl: '', // 图片地址
			stock: 0, // 库存
			weight: 0, // 商品重量
			volume: 0, // 商品体积
			promotionFee:0,
			mark:'',
			firstBrokeragePrice: 0, // 一级分销的佣金
			secondBrokeragePrice: 0 // 二级分销的佣金
		}
	],
	description: '', // 商品详情
	sort: 0, // 商品排序
	giveIntegral: 0, // 赠送积分
	virtualSalesCount: 0 // 虚拟销量
})


const parentTabType = ref(0)

const picUrl = ref("")
const parentRow = ref()
const parentNewStatus = ref(0)
const route = useRoute();
const productId = ref(Number(route.params.id)) ;

/** 获得详情 */
const getDetail = async () => {
	const id = productId.value as any as number
	if (id) {
		formLoading.value = true
		try {
			const res = (await ProductSpuApi.getSpu(id)) as ProductSpuApi.Spu
			res.skus?.forEach((item) => {
				if (isDetail.value) {
					item.price = floatToFixed2(item.price)
					item.marketPrice = floatToFixed2(item.marketPrice)
					item.costPrice = floatToFixed2(item.costPrice)
					item.firstBrokeragePrice = floatToFixed2(item.firstBrokeragePrice)
					item.secondBrokeragePrice = floatToFixed2(item.secondBrokeragePrice)
				} else {
					// 回显价格分转元
					item.price = formatToFraction(item.price)
					item.marketPrice = formatToFraction(item.marketPrice)
					item.costPrice = formatToFraction(item.costPrice)
					item.firstBrokeragePrice = formatToFraction(item.firstBrokeragePrice)
					item.secondBrokeragePrice = formatToFraction(item.secondBrokeragePrice)
				}
			})
			formData.value = res
		} finally {
			formLoading.value = false
		}
	}
}
const submitForm = async () => {
	
	// 提交请求
	formLoading.value = true
	try {
		// 校验各表单
		await unref(infoRef)?.validate()
		await unref(skuRef)?.validate()
		await unref(deliveryRef)?.validate()
		await unref(descriptionRef)?.validate()
		// await unref(otherRef)?.validate()
		// 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
		const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu

		// console.log(deepCopyFormData)
		deepCopyFormData.skus!.forEach((item) => {
			// 给sku name赋值
			item.name = deepCopyFormData.name
			// sku相关价格元转分
			item.price = convertToInteger(item.price)
			item.marketPrice = convertToInteger(item.marketPrice)
			item.promotionFee = convertToInteger(item.promotionFee)
			item.costPrice = convertToInteger(item.costPrice)
			item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice)
			item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice)
		})
		// 处理轮播图列表
		const newSliderPicUrls: any[] = []
		deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
			// 如果是前端选的图
			typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
		})
		deepCopyFormData.sliderPicUrls = newSliderPicUrls
		// 校验都通过后提交表单
		const data = deepCopyFormData as ProductSpuApi.Spu
		const id = productId.value as any as number
		if (!id) {
			await ProductSpuApi.createSpu(data)
			message.success(t('common.createSuccess'))
		} else {
			await ProductSpuApi.updateSpu(data)
			message.success(t('common.updateSuccess'))
		}
		close()
		emit('success')
	} finally {
		formLoading.value = false
	}
}
onMounted(() => {
	getDetail()
  // 当子组件挂载时，改变父组件的样式
  document.getElementsByTagName('section')[1].style.padding = '0px';
  document.getElementsByTagName('section')[1].style.width = '100%';
  document.getElementsByTagName('section')[1].querySelector('div').style.border = 'none';
  document.getElementsByTagName('section')[1].style.background = '#f5f7f9';

});
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>
	// 基本信息显示
	
	::v-deep .el-card__body{padding: unset;}
	::v-deep .el-card{border:none}
	::v-deep .el-col-12 {
    max-width: 100%;
    width: 100%;
		flex: none;
	}
	::v-deep .el-row{
		border: none !important;
		padding: 0 1rem;
	}
	::v-deep .el-form-item{
		border-bottom: 1px solid #ebeef5;
		align-items: center;
	}
	::v-deep .el-col , ::v-deep .el-form-item__label{
		border: unset !important;
		justify-content:flex-start
	}

	// 日志显示
	::v-deep .el-timeline{
		margin: unset !important;
	}
	::v-deep .el-timeline-item{
		padding-bottom: 0;
	}
	::v-deep .el-timeline-item__tail{
		position: absolute;
    left: 21px !important;
    top: -19px !important;
    height: 150% !important;
	}
	::v-deep .dot-node-style{
		left: 12px !important;
		top: -39px !important;
		position: absolute !important;
	}
	::v-deep .el-timeline-item__timestamp{
		left: 35px !important;
    top: -22px !important;
	}
	::v-deep .el-timeline-item__content{
		margin-top: 42px;
    margin-left: 6px;
    padding-right: 15px;
	}
	::v-deep .el-timeline .el-timeline-right-content::before{
		top: 0px !important;
    left: 18px !important;
	}
</style> -->