<script setup>
	import { ref,onMounted,reactive,defineAsyncComponent,markRaw,shallowRef,computed } from 'vue'
	import { useRoute,useRouter } from 'vue-router'
	import { customerList,supplierList,sellerList,addLog,getLog }  from '@/api'
	import { inquiryInfo,inquiryGoodsList,update,removeSupplyInquiry } from '@/api/inquiry'
	import { HomeFilled,Search,EditPen,Flag,ShoppingCartFull } from '@element-plus/icons-vue'
	import { useUserStore } from '@/store'
	import { ElMessage, ElMessageBox } from 'element-plus'

	const user_store = useUserStore()
	const userId = user_store.userId

	const route = useRoute()
	const router = useRouter()
	const order_id = ref(0)
	const order = ref({})
	const status = ref(0)
	const goods_list = ref([])

	const currentPage = ref('base')
	const startShow = ref(false)
	const tableHeight = ref(0)

	const load = async () => {
		order_id.value = route.params.id ? +route.params.id : 0
		currentPage.value = 'base'
		if(order_id.value != 0) {
			const {data:res} = await inquiryInfo(order_id.value)
			if(res.data.id && parseInt(res.data.id) == order_id.value) {
				order.value = res.data
				status.value = +order.value.status
				const { data:goods } = await inquiryGoodsList(order_id.value)
				goods_list.value = goods.data
			}
			changeStatus(status.value)
		}
		startShow.value = true
	}

	onMounted(async () => {
		await load()
		if(order_id.value != 0 && user_store.userId != +order.value.creator && !user_store.partner.includes(order.value.creator)) {
			router.replace('/error-page')
			return
		}
		tableHeight.value = window.innerHeight - 180
		comId.value = tabs['base'].component
	})

	const Base = defineAsyncComponent(() => import('@/components/Base.vue'))
	const Inquiry = defineAsyncComponent(() => import('@/components/Inquiry.vue'))
	const Offer = defineAsyncComponent(() => import('@/components/Offer.vue'))
	const Result = defineAsyncComponent(() => import('@/components/Result.vue'))
	const OrderResult = defineAsyncComponent(() => import('@/components/OrderResult.vue'))
	const comId = shallowRef(Base)
	const tabs = reactive({
		base: {
			label: '1.询盘基础',
			icon: markRaw(HomeFilled),
			disabled: false,
			component: markRaw(Base)
		},
		inquiry: {
			label: '2.供应商询件',
			icon: markRaw(Search),
			disabled: true,
			component: markRaw(Inquiry)
		},
		offer: {
			label: '3.优选报价',
			icon: markRaw(EditPen),
			disabled: true,
			component: markRaw(Offer)
		},
		result: {
			label: '4.询盘结果',
			icon: markRaw(Flag),
			disabled: true,
			component: markRaw(Result)
		},
		order_result: {
			label: '5.询盘结题',
			icon: markRaw(ShoppingCartFull),
			disabled: true,
			component: markRaw(OrderResult)
		}
	})

	const changeStatus = (status) => {
		switch(status) {
			case 0:
				tabs.result.disabled = true
				if(goods_list.value.length == 0) {
					tabs.inquiry.disabled = true
					tabs.offer.disabled = true
				} else {
					tabs.inquiry.disabled = false
					tabs.offer.disabled = false
				}
				tabs.order_result.disabled = true
				break
			case 1:
				tabs.result.disabled = true
				tabs.inquiry.disabled = false
				tabs.offer.disabled = false
				tabs.order_result.disabled = true
				break
			case 2:
			case 3:
				tabs.inquiry.disabled = false
				tabs.offer.disabled = false
				tabs.result.disabled = false
				tabs.order_result.disabled = true
				break
			case 4:
			case 5:
				tabs.inquiry.disabled = false
				tabs.offer.disabled = false
				tabs.result.disabled = false
				tabs.order_result.disabled = false
				break
			default:
				tabs.inquiry.disabled = true
				tabs.offer.disabled = true
				tabs.result.disabled = true
				tabs.order_result.disabled = true
				break
		}
	}

	const handleChange = (tab,evt) => {
		comId.value = tabs[tab.props.name].component
	}

	const handleStatusChange = async (id,state) => {
		if(!id) {
			return
		}
		switch(state) {
			case 'create-inquiry':
			case 'subject-change':
			case 'note-change':
			case 'customer-change':
				break
			case 'save-goods':
				const { data:res } = await inquiryGoodsList(id)
				goods_list.value = res.data
				if(goods_list.value.length > 0) {
					tabs.inquiry.disabled = false
					currentPage.value = 'inquiry'
				} else {
					tabs.inquiry.disabled = true
				}
				break
			case 'make-offer':
				status.value = 3
				currentPage.value = 'result'
				break
			case 'share-offer':
				currentPage.value = 'result'
				break
			case 'user-cancel':
				ElMessageBox.prompt('请填写取消用户取消理由：', '用户取消', {
					type: 'warning',
					showCancelButton: true,
					cancelButtonText: '取消',
					confirmButtonText: '确定'
				}).then(async ({ value }) => {
					 await update(id,{is_del:3,reason:value})
					 router.push('/inquiry/list')
					 ElMessage.success('用户取消成功！')
					 await addLog(id,user_store.logName,'客户取消',value)
				}).catch(() => {+
					ElMessage.warning('没有启用用户取消！')
				})
				break;
			case 'remove-supply-inquiry':
				tabs.inquiry.disabled = false
				tabs.offer.disabled = false
				break
		}
		const { data:res } = await inquiryInfo(id)
		let _status = 0
		if(res.data.id && +res.data.id == id) {
			order_id.value = id
			order.value = res.data
			_status = +order.value.status
		}
		changeStatus(_status)
	}
	const nextStep = async (id) => {
		if(!id) {
			return
		}
		const {data:res} = await inquiryInfo(id)
		let status = 0
		if(res.data.id && parseInt(res.data.id) == id) {
			order_id.value = id
			order.value = res.data
			status = parseInt(order.value.status)
		}
		changeStatus(status)
	}

	const noGo = () => {
		if(!order_id.value) {
			return
		}
		ElMessageBox.prompt('请填写提前中断流程理由：', '客服中断', {
			type: 'warning',
			showCancelButton: true,
			cancelButtonText: '取消',
			confirmButtonText: '确定'
		}).then(async (val) => {
			await update(order_id.value, {is_del: 2,reason: val.value})
			router.push('/inquiry/list')
			await addLog(order_id.value,user_store.logName,'客服中断',val.value)
			ElMessage.success('询盘已提前终止！')
		}).catch(() => {
			ElMessage.error('无法中断流程！')
		})
	}

	const rollback = async () => {
		switch(currentPage.value) {
			case 'base':
				return
			case 'inquiry':
				ElMessageBox.confirm('确定要回滚到询盘基础节点吗？', '流程回滚', {
					type: 'warning',
					showCancelButton: true,
					cancelButtonText: '取消',
					confirmButtonText: '确定'
				}).then(async () => {
					await removeSupplyInquiry(order_id.value)
					await update(order_id.value,{status: 0})
					await addLog(order_id.value,user_store.logName,'流程回滚','回滚到询盘基础节点')
					ElMessage.success('已回退到询盘基础！')
					currentPage.value = 'base'
				}).catch(() => {
					ElMessage.error('无法回滚流程！')
				})
				break
			case 'offer':
				ElMessageBox.confirm('确定要新建报价吗？', '新建报价', {
					type: 'warning',
					showCancelButton: true,
					cancelButtonText: '取消',
					confirmButtonText: '确定'
				}).then(async () => {
					await update(order_id.value,{status: 1,o_time: null,offer: null})
					await addLog(order_id.value,user_store.logName,'流程回滚','新建报价')
					ElMessage.success('已回退到询盘基础！')
					currentPage.value = 'inquiry'
				}).catch(() => {
					ElMessage.error('无法重建报价！')
				})
				break
			case 'result':
				break
			case 'result':
				break
		}
	}
</script>

<template>
    <el-tabs v-model="currentPage" type="border-card" @tab-click="handleChange">
		<el-tab-pane v-for="(item,index) in tabs" :name="index" :key="index" :disabled="item.disabled">
			<template #label>
				<span class="tabs-label">
					<el-icon>
						<component :is="item.icon"></component>
					</el-icon>
					<span>{{item.label}}</span>
				</span>
			</template>
		</el-tab-pane>
		<Suspense v-if="startShow">
			<component
				@status-change="handleStatusChange"
				:is="tabs[currentPage].component"
				:order-id="order_id"
				:order-status="+order.status"
				@next-step="nextStep"
			>
				<template #nogo>
					<span v-if="order_id">
						<el-button color="#b23b2f" @click="noGo" size="large" class="ml-4"><i class="fa fa-stop pr-2"></i>业务中止</el-button>
					</span>
				</template>
				<template #rollback>
					<span v-if="order_id && currentPage != 'base'">
						<el-button
							type="warning"
							@click="rollback"
							size="large"
							class="ml-4"
						>
							<i class="fa fa-reply pr-2"></i>流程回滚
						</el-button>
					</span>
                <!-- <el-button v-if="!editable" color="#485827" @click="rebuild" size="large" :icon="Money">重建报价</el-button> -->
				</template>
			</component>
			<template #fallback>
				功能加载中，请稍候...
			</template>
		</Suspense>
	</el-tabs>
</template>

<style scoped>
	.tabs-label .el-icon {
		vertical-align: middle;
	}
	.tabs-label span {
		vertical-align: middle;
		margin-left: 10px;
		font-weight: 600;
	}
</style>