<script setup lang="ts">
import {
	Storehouse_Product_List,
	Storehouse_Product_Model_List,
	Storehouse_Product_Name_List,
	Storehouse_ProductClass_List,
	Storehouse_Stock_List
} from '@/api/storehouse'
import {ElMessage} from 'element-plus'
import {GlobalStore} from '@/stores'
import Drawer from '@/components/Drawer/index.vue'
import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import {default as vElTableInfiniteScroll} from 'el-table-infinite-scroll'
import ImageCom from '@/components/Image/index.vue'
import {ReceiveFormType} from "@/hooks/useDepot";

let total = 0
const autoSelect = ref('')
const selectTable = ref()
const loading = ref(false)
const globalStore = GlobalStore()
const NameOptions = ref<any[]>([])
const classOptions = ref<any[]>([])
const modelOptions = ref<any[]>([])
const tableProductData = ref<any[]>([])
const productList = ref<any[]>([])
const tableStockData:any = ref([])
const drawerProductRef = ref<InstanceType<typeof Drawer> | null>(null)
const tableData = ref<any[]>([])

// props
const props = defineProps<{ selectProductData?: any[], depotId: any }>()
const selectProductData = ref(props.selectProductData)
const emit = defineEmits<{ (event: 'ontableData', value: any): void; (event: 'ontableDataAll', value: any[]): void }>()

const form = reactive<ReceiveFormType>({
	T_type: 1,
	T_uuid: '',
	T_receive: '',
	T_project: '',
	T_number: '',
	T_depot_id: undefined,
	T_product: '',
	T_date: '',
	T_remark: '',
	T_contract_number: ''
})

const initParam = reactive({
	User_tokey: globalStore.GET_User_tokey,
	T_name: '',
	T_model: '',
	T_class: '',
	page: 1,
	page_z: 20
})
const callbackProductDrawer = (done: () => void) => done()
const querySearchAsync = async (queryString: string) => {
	if (queryString) {
		loading.value = true
		globalStore.SET_isloading(true)
		const results = await getNameAsync(queryString)
		NameOptions.value = results
		globalStore.SET_isloading(false)
		loading.value = false
	}
}

const getProductModelList = async () => {
	globalStore.SET_isloading(true)
	const res: any = await Storehouse_Product_Model_List({T_name: autoSelect.value})
	modelOptions.value = res.Data.map((item: any, index: number) => {
		return {
			value: item,
			index: index
		}
	})
	globalStore.SET_isloading(false)
}
const handleSelect = (item: any) => {
	initParam.T_name = item
	getProductModelList()
}
// 搜索模型
const searchModelHandle = () => {
	total = 0
	initParam.page = 1
	tableProductData.value = []
	getProductList()
}

// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
  return row.Id
}

// 加载第二个抽屉数据
const load = () => {
	// if (initParam.page && total === tableProductData.value.length) {
	// 	ElMessage.warning('没有更多数据了！！')
	// 	return
	// }
	// initParam.page++
	// getProductList()
}
// 勾选产品
const ProductselectionChange = (selection: any[], row: any) => emit('ontableData', row)
const ProductSelectionAllChange = (selection: any[]) => emit('ontableDataAll', selection)

const getNameAsync = async (str: string): Promise<any> => {
	const res: any = await Storehouse_Product_Name_List({T_name: str, T_class: initParam.T_class})
	if (!res.Data) return
	return res.Data.map((item: any, index: number) => {
		return {
			value: item,
			index: index
		}
	})
}

/**
 * 获取产品列表
 */
const getStockTotalList =  async(depotId: number) => {

	 return new Promise( (reslove:any)=>{
		 Storehouse_Stock_List({...initParam, page_z: 9999, T_depot_id: depotId}).then((res:any)=>{
			 reslove(res.Data.Data)
		 })
	})

}

// 获取产品的列表
const getProductList = async () => {
	const res: any = await Storehouse_Product_List({...initParam, page_z: 9999, T_name: autoSelect.value})
	tableProductData.value=[...res.Data.Data || []]
	tableStockData.value = await getStockTotalList(props.depotId)

	// 创建 Map 存储 arr2 中对象，键为 Id
	const idMap = new Map(tableProductData.value.map(item => [item.Id, item]));
	// 生成合并后的新数组
	productList.value = tableStockData.value
		.filter((item: any) => idMap.has(item.T_product_id))  // 筛选存在对应关系的数据
		.map((item: any) => ({
			...item,
			...idMap.get(item.T_product_id)  // 合并两个数据源
		}));

	// tableProductData.value.push(...arr2)

	total = res.Data.Num
	if (selectProductData.value?.length) {
		// 设置产品的选中
		productList.value.forEach((row: any) => {
			setTimeout(() => {
				const matchedIndex = selectProductData.value?.findIndex((item: any) => item.T_product_id == row.Id)
				selectTable.value?.toggleRowSelection(row, matchedIndex != -1)
			});
		})
	}
}

// 获取产品分类
const getProductClassList = async () => {
	const res: any = await Storehouse_ProductClass_List({page: 1, page_z: 999})
	classOptions.value = res.Data.Data
}

onMounted(() => {
	// getProductList()
	!classOptions.value.length && getProductClassList()
})

const productColumns = [
	{type: 'selection', width: 80},
	{prop: 'T_img', label: '产品图片', name: 'T_img'},
	{prop: 'T_name', label: '产品名称'},
	{prop: 'T_class_name', label: '产品分类'},
	{prop: 'T_model', label: '产品型号', ellipsis: true},
	{prop: 'T_spec', label: '产品规格'},
	{prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn'},
	{prop: 'T_total', label: '库存数量'},
	{prop: 'T_occupy', label: '占用库存', name: 'T_occupy'},
	{prop: 'T_remark', label: '备注', ellipsis: true}
]
const countBlurHandle = () => {
	form.T_product = tableData.value.map(item => {
		if (!item.count && item.T_product_relation_sn !== 1) return undefined
		if (item.count > item.T_total) return undefined
		return `${item.T_product_id},${item.count}|`
	})
}

const openDrawer = () => drawerProductRef.value?.openDrawer()
const clearSelection = () => {
	initParam.page = 1
	tableProductData.value = []
	selectTable.value?.clearSelection()
}
const selectTableChange = (row: any) => {
	nextTick(() => {
		selectTable.value?.toggleRowSelection(row, false)
	})
}


defineExpose({
	openDrawer,
	clearSelection,
	selectTableChange,
	getProductList,
	getStockTotalList
})
</script>

<template>
	<Drawer ref="drawerProductRef" :handleClose="callbackProductDrawer" size="70%">
		<template #header="{ params }">
			<h4 :id="params.titleId" :class="params.titleClass">选择产品</h4>
		</template>
		<el-card class="box-card" shadow="never">
			<template #header>
				<div class="input-suffix">
					<el-row :gutter="20" style="margin-bottom: 0">
						<el-col :xl="5" :lg="8" :md="10" class="d-flex">
							<span class="inline-flex items-center">产品分类：</span>
							<el-select v-model="initParam.T_class" clearable placeholder="请选择分类~">
								<el-option v-for="item in classOptions" :key="item.Id" :label="item.T_name"
										   :value="item.Id"/>
							</el-select>
						</el-col>
						<el-col :xl="7" :lg="8" :md="10" class="d-flex">
							<span class="inline-flex items-center">产品名称：</span>
							<el-select
								v-model="autoSelect"
								filterable
								clearable
								remote
								reserve-keyword
								placeholder="按产品名称搜索"
								remote-show-suffix
								:remote-method="querySearchAsync"
								:loading="loading"
								@change="handleSelect"
							>
								<el-option v-for="item in NameOptions" :key="item.value" :label="item.value"
										   :value="item.value"/>
							</el-select>
						</el-col>
						<el-col :xl="7" :lg="8" :md="12" class="d-flex">
							<span class="inline-flex items-center">产品型号：</span>
							<el-select v-model="initParam.T_model" clearable placeholder="请选择型号~">
								<el-option v-for="item in modelOptions" :key="item.index" :label="item.value"
										   :value="item.value"/>
							</el-select>
							<el-button type="primary" @click="searchModelHandle">搜索</el-button>
						</el-col>
					</el-row>
				</div>
			</template>
			<el-table
				ref="selectTable"
				:row-key="getRowKey"
				:data="productList"
				style="width: 100%; height: 99%"
				:header-cell-style="{
          background: '#dedfe0',
          height: '50px'
        }"
				v-el-table-infinite-scroll="load"
				:infinite-scroll-immediate="false"
				infinite-scroll-distance="'50px'"
				@select="ProductselectionChange"
				@select-all="ProductSelectionAllChange"
			>
				<template v-for="item in productColumns" :key="item">
					<el-table-column v-if="item.type === 'index' || item.type === 'selection'" align="center"
									 v-bind="item"/>
					<el-table-column show-overflow-tooltip v-if="!item.ellipsis && item.prop" v-bind="item">
						<template #default="{ row }">
							<el-input
								v-if="item.prop === 'count' && row.T_product_relation_sn !== 1"
								v-model.number="row.count"
								type="text"
								autocomplete="off"
								@blur="countBlurHandle"
							/>
							  <span v-if="item.prop === 'T_relation_sn'">
								<el-tag v-if="row.T_relation_sn === 1" effect="dark">是</el-tag>
								<el-tag v-else type="success" effect="dark">否</el-tag>
							  </span>

							<span v-if="item.prop === 'T_occupy'">
								<el-text v-if="row.T_occupy > 0" type="danger">{{row.T_occupy}}</el-text>
								<el-text v-else type="info">{{row.T_occupy}}</el-text>
							  </span>
							<ImageCom v-if="item.prop === 'T_img'" :src="row.T_img"/>
						</template>
					</el-table-column>
					<el-table-column show-overflow-tooltip v-if="item.ellipsis && item.prop === 'T_model'"
									 align="center" v-bind="item">
						<template #default="{ row }">
							<el-tooltip effect="dark" :content="row.T_model" placement="bottom">
								{{ row.T_model }}
							</el-tooltip>
						</template>
					</el-table-column>
					<el-table-column show-overflow-tooltip v-if="item.ellipsis && item.prop === 'T_remark'"
									 align="center" v-bind="item">
						<template #default="{ row }">
							<el-tooltip effect="customized" placement="left">
								<template #content>
									<div class="tooltip-content">{{ row.T_remark }}</div>
								</template>
								{{ row.T_remark }}
							</el-tooltip>
						</template>
					</el-table-column>
				</template>
			</el-table>
		</el-card>
	</Drawer>
</template>

<style scoped lang="scss">
.tooltip-content {
	max-width: 500px;
	overflow-y: auto;
}

.box-card {
	height: 100%;

	:deep(.el-card__body) {
		height: calc(100% - 70px);
	}

	.sn-header {
		display: flex;
		justify-content: end;
	}

	.input-suffix {
		width: 100%;

		.inline-flex {
			white-space: nowrap;
		}

		.d-flex {
			display: flex;
		}
	}
}
</style>
