<template>
	<uni-popup class="materials-popup" ref="materialChoosePopRef" type="bottom" :is-mask-click="false"
		borderRadius="10px 10px 0 0">
		<z-paging class="z-page-popup" ref="paging" style="top: 200px;"  :default-page-size="20" v-model="dataList" @query="queryList">
			<!-- z-paging默认铺满全屏，此时页面所有view都应放在z-paging标签内，否则会被盖住 -->
			<!-- 需要固定在页面顶部的view请通过slot="top"插入，包括自定义的导航栏 -->
			<template #top>
				<view class="page-top">
					<uni-row class="head-row">
						<uni-col :span="6" class="head-cancel align-center justify-start" @click="oncancel">
							{{$t('operation.cancel')}}
						</uni-col>
						<uni-col :span="12" class="head-title justify-center">
							{{$t('workOrder.selectMaterial')}}
						</uni-col>
						<uni-col :span="6" class="head-add align-center justify-end" @click="onAdd" v-if="!noAdd">
							<uni-icons type="plusempty" color="#004098"></uni-icons>
							{{$t('operation.add')}}
						</uni-col>
					</uni-row>
					<uni-row class="search-row flex-row justify-between">
						<uni-col :span="24">
							<uni-easyinput v-model="searchValue" :styles="inputStyles"
								:placeholderStyle="placeholderStyle"
								:placeholder="`${$t('operation.PleaseInput')}${$t('workOrder.materialName')}`"
								@confirm="searchList">
							</uni-easyinput>
						</uni-col>
					</uni-row>
					<uni-row :gutter="5" class="table-header flex-row align-center justify-between">
						<uni-col :span="5" class="flex-row justify-center">
							{{ $t('workOrder.materialCode')}}
						</uni-col>
						<uni-col :span="7" class="flex-row justify-center">
							{{ $t('workOrder.materialName')}}
						</uni-col>
						<uni-col :span="3" class="flex-row justify-center">
							{{ $t('workOrder.unit')}}
						</uni-col>
						<uni-col :span="3" class="flex-row justify-center">
							{{ $t('workOrder.unitPrice')}}
						</uni-col>
						<uni-col :span="3" class="flex-row justify-center">
							{{ $t('workOrder.inventory')}}
						</uni-col>
						<uni-col :span="4" class="flex-row justify-end">
							{{ $t('workOrder.source')}}
						</uni-col>
					</uni-row>
				</view>
			</template>
			<view class="page-table">
				<uni-row :gutter="2" class="item-row align-center"
					:class="{'choosed': chooseIds.includes(item.chooseKey)}" v-for="(item,index) in dataList"
					:key="index" @click="onChoose(item)">
					<uni-col :span="5" class="item-col flex-row justify-start">
						{{item.materialCode}}
					</uni-col>
					<uni-col :span="7" class="item-col flex-row justify-start">
						{{item.materialName}}
					</uni-col>
					<uni-col :span="3" class="item-col flex-row justify-center">
						{{item.unit}}
					</uni-col>
					<uni-col :span="3" class="item-col flex-row justify-center">
						{{item.unitPrice}}
					</uni-col>
					<uni-col :span="3" class="item-col flex-row justify-center">
						{{item.totalInventoryQuantity}}
					</uni-col>
					<uni-col :span="4" class="item-col flex-row justify-end">
						{{item.materialSource}}
					</uni-col>
				</uni-row>
			</view>
		</z-paging>
	</uni-popup>
	<materials-count ref="countRef" @count-set="onCountSet"></materials-count>
	<materials-add ref="addRef" @add-set="onEmit"></materials-add>
</template>

<script setup>
	import dayjs from 'dayjs'
	import {
		computed,
		ref,
		reactive,
		watch,
		onMounted,
	} from 'vue'
	import {
		useI18n
	} from 'vue-i18n'
	import {
		getDeptId,
	} from "@/utils/auth"
	import {
		getMaterialList
	} from '@/api/material'
	import {
		devicePage,
	} from '@/api/device';
	import materialsCount from './count'
	import materialsAdd from './add'
	// 接收父组件传递的参数
	const props = defineProps({
		deviceId: {
			type: Number,
		},
		deptId: {
			type: Number,
			default:getDeptId(),
		},
		bomNodeId: {
			type: String,
			default: null,
		},
		materialItem: {
			type: Object,
			default: () => {}
		},
		noAdd: {
			type: Boolean,
			default: false,
		},
	})

	const searchValue = ref('')
	const placeholderStyle = ref('color:#ADADAD;font-weight:400;font-size:12px')
	const inputStyles = reactive({
		backgroundColor: '#F5F5F5',
		color: '#797979',
	})
	const paging = ref(null)
	// v-model绑定的这个变量不要在分页请求结束中自己赋值，直接使用即可
	const dataList = ref([])

	// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
	const queryList = (pageNo, pageSize) => {
		// 此处请求仅为演示，请替换为自己项目中的请求
		getMaterialList({
			pageNo,
			pageSize,
			deviceId: props.deviceId,
			deptId: props.deptId,
			bomNodeId: props.bomNodeId,
			materialName: searchValue.value
		}).then(res => {
			// 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
			res.data.list.forEach(item => {
				item.chooseKey =
					`${item.materialCode}_${item.costCenterId}_${item.factoryId}_${item.unitPrice}_${item.storageLocationId}`
			})
			paging.value.complete(res.data.list);
		}).catch(res => {
			// 如果请求失败写paging.value.complete(false);
			// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
			// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
			paging.value.complete(false);
		})
	}
	const searchList = () => {
		paging.value.reload()
	}
	const formatDate = (time) => {
		return dayjs(time).format('YYYY-MM-DD');
	}
	// ----------------------------------------------


	// ---------------------------------------------
	const chooseList = ref([])
	const chooseIds = computed(() => {
		// 返回chooseList的id组成新数组
		return chooseList.value.map(c => c.chooseKey)
	})
	const onChoose = (item) => {

		// 判断当前点击的设备是否存在于chooseList中，
		// 若存在，则从chooseList中删除，否则添加到chooseList中
		// 若不存在则添加
		const index = chooseList.value.findIndex((v) => v.chooseKey === item.chooseKey)
		if (index > -1) {
			// chooseList.value.splice(index, 1)
		} else {
			chooseList.value = [item]
			onCountShow(item)
		}
	}
	const onChooseDel = (item) => {
		// 判断当前点击的设备是否存在于chooseList中，
		// 若存在，则从chooseList中删除，否则添加到chooseList中
		const index = chooseList.value.findIndex((v) => v.chooseKey === item.chooseKey)
		if (index > -1) {
			chooseList.value.splice(index, 1)
		}
	}
	const oncancel = () => {
		chooseList.value = []
		close()
	}
	const addRef = ref(null)
	const onAdd = () => {
		// oncancel()
		addRef.value.open()
	}
	const onEmit = (item) => {
		// chooseList.value = [item]
		console.log('onEmit-item', item, bomItem.value)
		const subItem = Object.assign({}, item)
		// subItem.bomId = bomItem.value.id
		subItem.bomNodeId = bomItem.value.bomNodeId
		// subItem.workOrderId = bomItem.value.workOrderId
		subItem.workOrderBomOnlyKey = bomItem.value.workOrderBomOnlyKey
		console.log('onEmit-subItem', subItem)
		emit('material-submit', subItem)
		oncancel()
	}
	const countRef = ref(null)
	const onCountShow = (item) => {
		countRef.value.showCountPop(item)
	}
	const onCountSet = (item) => {
		console.log('onCountSet- item', item)
		onEmit(item)
		countRef.value.hideCountPop()
	}


	const {
		t,
		locale
	} = useI18n({
		useScope: 'global'
	})

	const bomItem = ref({})
	const materialChoosePopRef = ref(null)
	// 打开弹窗
	const open = (bom) => {
		console.log('open-bom', bom)
		bomItem.value = bom
		materialChoosePopRef.value.open()
	}
	// 关闭弹窗
	const close = () => {
		materialChoosePopRef.value.close()
	}

	const emit = defineEmits(['material-submit'])
	// 提供外部方法
	const expose = {
		open,
	}
	defineExpose(expose)
</script>

<style lang="scss" scoped>
	@import "@/style/choose-device.scss";

	.z-page-popup {
		padding: 20px 15px;
		box-sizing: border-box;
		background: #FFF;
		border-radius: 10px 10px 0 0;
	}

	.page-top {
		background: #fff;
		padding: 0;
	}

	.head-row {
		margin-bottom: 20px;
		font-size: 16px;
		line-height: 21px;
		color: #A3A3A3;
	}

	.head-title {
		color: #333333;
		font-weight: bold;
	}

	.head-add {
		color: #004098;
	}

	.table-header {
		background: #FFF;
		border-bottom: 1px solid #CACCCF;
	}

	.page-table {
		padding: 0;
	}

	.item-col {
		font-size: 11px;
	}
</style>