<script setup lang="ts">
import {Storehouse_Product_List, Storehouse_Product_Name_List} from '@/api/storehouse/index'
import {GlobalStore} from '@/stores/index'
import Drawer from '@/components/Drawer/index.vue'
import {nextTick, onMounted, reactive, ref} from 'vue'
import ImageCom from '@/components/Image/index.vue'

const autoSelect = ref('')
const loading = ref(false)
const NameOptions = ref<any[]>([])
const selectTable = ref()
const globalStore = GlobalStore()
const tableProductData = ref<any[]>([])
const drawerProductRef = ref<InstanceType<typeof Drawer> | null>(null)

const initParam = reactive({
	User_tokey: globalStore.GET_User_tokey,
	page: 1,
	page_z: 9999,
	T_VerifyContract: 1
})

// 获取产品的列表
const getProductList = async () => {
	const res: any = await Storehouse_Product_List({...initParam, T_name: autoSelect.value})
	tableProductData.value.push(...res.Data.Data)
	if (selectProductData.value?.length) {
		// 设置产品的选中
		tableProductData.value.forEach((row: any) => {
			const matchedIndex = selectProductData.value?.findIndex((item: any) => item.Id == row.Id)
			selectTable.value?.toggleRowSelection(row, matchedIndex != -1)
		})
	}
}

onMounted(() => {
	getProductList()
})

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_remark', label: '备注', ellipsis: true}
]

// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => row.Id
const openDrawer = () => drawerProductRef.value?.openDrawer()
const callbackProductDrawer = (done: () => void) => done()
// 勾选产品
const ProductselectionChange = (selection: any[], row: any) => emit('ontableData', row)
const ProductSelectionAllChange = (selection: any[]) => emit('ontableDataAll', selection)
const clearSelection = () => {
	initParam.page = 1
	tableProductData.value = []
	selectTable.value?.clearSelection()
}
const selectTableChange = (row: any) => {
	nextTick(() => {
		selectTable.value?.toggleRowSelection(row, false)
	})
}

// props
const props = defineProps<{ selectProductData?: any[] }>()
const selectProductData = ref(props.selectProductData)
const emit = defineEmits<{ (event: 'ontableData', value: any): void; (event: 'ontableDataAll', value: any[]): void }>()
const getNameAsync = async (str: string): Promise<any> => {
	const res: any = await Storehouse_Product_Name_List({T_name: str, T_VerifyContract: 1})
	if (!res.Data) return
	return res.Data.map((item: any, index: number) => {
		return {
			value: item,
			index: index
		}
	})
}
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 searchModelHandle = () => {
	initParam.page = 1
	tableProductData.value = []
	getProductList()
}
defineExpose({
	openDrawer,
	clearSelection,
	selectTableChange
})
</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 class="d-flex">
							<span class="inline-flex items-center">产品名称：</span>
							<el-input v-model="autoSelect" type="text" class="w-50 m-2"
									  placeholder="按产品名称搜索" clearable/>
							<el-button type="primary" @click="searchModelHandle">搜索</el-button>
						</el-col>
					</el-row>
				</div>
			</template>
			<el-table
				ref="selectTable"
				:row-key="getRowKey"
				:data="tableProductData"
				style="width: 100%; height: 99%"
				:header-cell-style="{
        background: '#dedfe0',
        height: '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 }">
            <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>
							<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);
	}

	.input-suffix {
		width: 100%;

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

		.w-50 {
			width: 12.5rem;
		}
	}
}


</style>
