<template>
	<div class="page page-full border bg padding">
		<el-form inline ref="queryRef" @keyup.enter="getList(1)">
			<el-form-item :label="$t('message.property.dossier.form.keyword') + '：'" prop="keyWord">
				<el-input v-model="params.keyWord" :placeholder="$t('message.property.dossier.form.keywordPlaceholder')" clearable style="width: 240px" />
			</el-form-item>

			<el-form-item>
				<el-button type="primary" class="ml10" @click="getList(1)">
					<el-icon>
						<ele-Search />
					</el-icon>
					{{ $t('message.tableI18nAction.query') }}
				</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="info" @click="batchdel()" v-auth="'batchdel'">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					{{ $t('message.tableI18nAction.delete') }}
				</el-button>
			</el-form-item>
		</el-form>
		<div class="page page-full-part flex-row gap-4">
			<el-card style="width: 250px;" shadow="never">
				<el-tree :data="mergedData" :props="defaultProps" accordion default-expand-all @node-click="handleNodeClick" :node-key="'id'" highlight-current>
					<template #default="{ node, data }">
						<div class="custom-tree-node">
							<span class="tree-label">
								<el-icon v-if="data.is_type != '2'">
									<Folder />
								</el-icon>
								<SvgIcon name="iconfont icon-siweidaotu" v-else></SvgIcon>
								{{ node.label }}
							</span>
						</div>
					</template>
				</el-tree>
			</el-card>
			<el-card class="flex1" shadow="never">
				<div class="page page-full">
					<el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" row-key="id" v-loading="loading">
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column prop="deviceName" v-col="'deviceName'" :label="$t('message.property.dossier.columns.deviceName')" min-width="100" show-overflow-tooltip />
						<el-table-column prop="deviceKey" v-col="'deviceKey'" :label="$t('message.property.dossier.columns.deviceKey')" show-overflow-tooltip />
						<el-table-column prop="deviceNumber" v-col="'deviceNumber'" :label="$t('message.property.dossier.columns.deviceNumber')" show-overflow-tooltip />
						<el-table-column prop="deviceCategory" v-col="'deviceCategory'" :label="$t('message.property.dossier.columns.deviceCategory')" show-overflow-tooltip />
						<el-table-column prop="installTime" v-col="'installTime'" :label="$t('message.property.dossier.columns.installTime')" width="160" align="center" />
						<el-table-column :label="$t('message.tableI18nColumn.operation')" width="160" align="center">
							<template #default="scope">
								<el-button size="small" text type="warning" v-auth="'edit'" @click="addOrEdit(scope.row)">{{ $t('message.tableI18nAction.edit') }}</el-button>
								<el-button size="small" text type="info" v-auth="'del'" @click="del(scope.row)">{{ $t('message.tableI18nAction.delete') }}</el-button>
							</template>
						</el-table-column>
					</el-table>
					<pagination v-if="params.total" :total="params.total" v-model:page="params.pageNum" v-model:limit="params.pageSize" @pagination="getList()" />
				</div>
			</el-card>
		</div>
		<EditForm ref="editFormRef" @getList="getList(1)"></EditForm>
	</div>
</template>

<script lang="ts" setup>
import device from '/@/api/device'
import { useSearch } from '/@/hooks/useCommon'
import { Folder } from '@element-plus/icons-vue'

import { ElMessageBox, ElMessage } from 'element-plus'
import EditForm from './edit.vue'
import { useI18n } from 'vue-i18n'
interface Tree {
	label: string
	children?: Tree[]
}
import { ref, onMounted } from 'vue'
const defaultProps = {
	children: 'children',
	label: 'label',
}

const queryRef = ref()
const { t } = useI18n()
const productData = ref([])
const mergedData = ref()
const cateData = ref()
const editFormRef = ref()
const productIno = ref()
const deviceKeys = ref<number[]>([])

const { params, tableData, getList, loading } = useSearch<any[]>(device.dev_asset.getList, 'Data', { keyWord: '' })
getList()
const handleSelectionChange = (selection: any[]) => {
	deviceKeys.value = selection.map((item) => item.deviceKey);
};
onMounted(() => {
	getCateList()
})
const addOrEdit = async (row?: any) => {
	if (row) {
		editFormRef.value.open(row, productIno.value)
		return
	} else {
		editFormRef.value.open({}, productIno.value)
	}
}

const getCateList = () => {
	device.category.getList({}).then((res: any) => {
		cateData.value = res.category

		device.product.getLists({}).then((res: any) => {
			productData.value = res.product
			mergedData.value = matchProductsToCategories(productData.value, cateData.value)
		})
	})
}

const handleNodeClick = (data: any) => {
	if (data.is_type === '2') {
		productIno.value = data
		params.productKey = data.key
		getList()
	} else {
		productIno.value = ''
	}
}

const matchProductsToCategories = (productData: any, cateData: any) => {
	const treeData = []
	for (let category of cateData) {
		const treeNode = buildTree(category, productData)
		treeData.push(treeNode)
	}
	return treeData
}

const buildTree = (category: any, productData: any) => {
	const treeNode = {
		id: category.id,
		label: category.name,
		key: category.key,
		is_type: '1', // 1是分类
		children: [] as any[],
	}

	if (category.children && category.children.length > 0) {
		const products = productData.filter((product: any) => product.categoryId === category.id)
		for (let product of products) {
			const productNode = {
				id: product.id,
				label: product.name,
				key: product.key,
				is_type: '2', // 2是产品
			}
			treeNode.children.push(productNode)
		}
		
		for (let child of category.children) {
			const childNode = buildTree(child, productData)
			treeNode.children.push(childNode)
		}

	} else {
		const products = productData.filter((product: any) => product.categoryId === category.id)
		for (let product of products) {
			const productNode = {
				id: product.id,
				label: product.name,
				key: product.key,
				is_type: '2', // 2是产品
			}
			treeNode.children.push(productNode)
		}
	}

	return treeNode
}

const batchdel = () => {
	ElMessageBox.confirm(t('message.property.dossier.messages.batchDeleteConfirm'), t('message.property.dossier.messages.tips'), {
		confirmButtonText: t('message.property.dossier.messages.confirm'),
		cancelButtonText: t('message.property.dossier.messages.cancel'),
		type: 'warning',
	}).then(async () => {
		await device.dev_asset.delete({ deviceKeys: deviceKeys.value })
		ElMessage.success(t('message.property.dossier.messages.deleteSuccess'))
		getList()
	})
}

const del = (row: any) => {
	ElMessageBox.confirm(t('message.property.dossier.messages.deleteItemConfirm', { name: row.deviceName }), t('message.property.dossier.messages.tips'), {
		confirmButtonText: t('message.property.dossier.messages.confirm'),
		cancelButtonText: t('message.property.dossier.messages.cancel'),
		type: 'warning',
	}).then(async () => {
		await device.dev_asset.delete({ deviceKeys: [row.deviceKey] })
		ElMessage.success(t('message.property.dossier.messages.deleteSuccess'))
		getList()
	})
}


// getCateList()
</script>
<style scoped lang="scss">
.custom-tree-node {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
	overflow: hidden;

	.tree-label {
		width: 100%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-right: 10px;
	}

	&:hover {
		.tree-options {
			display: block;
		}
	}
}
</style>