<template>
	<!-- <el-form-item class="inventory_dictionary_select_container">
		<span class="label_span">物品类型：</span>
		<el-select v-model="formData.typeCode" filterable placeholder="物品类型" clearable :size="size" @change="onChangeByType" class="comp">
			<el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label" :value="item.value"></el-option>
		</el-select>
		<span class="label_span">物品名称：</span>
		<el-select
			v-model="formData.itemCode"
			filterable
			placeholder="物品名称"
			:disabled="!formData.typeCode"
			clearable
			:size="size"
			:loading="itemDatas['loading']"
			class="comp"
			@change="onChangeByItem"
		>
			<el-option v-for="item in itemDatas['list']" :key="item.value" :label="item.label" :value="item.value"></el-option>
		</el-select>
	</el-form-item> -->
	<div class="inventory_dictionary_select_container">
		<el-form-item label="物品类型">
        <el-select v-model="formData.typeCode" filterable placeholder="物品类型" clearable :size="size" @change="onChangeByType" class="comp">
			<el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label" :value="item.value"></el-option>
		</el-select>
    </el-form-item>
    <el-form-item label="物品名称">
        <el-select
			v-model="formData.itemCode"
			filterable
			placeholder="物品名称"
			:disabled="!formData.typeCode"
			clearable
			:size="size"
			:loading="itemDatas['loading']"
			class="comp"
			@change="onChangeByItem"
		>
			<el-option v-for="item in itemDatas['list']" :key="item.value" :label="item.label" :value="item.value"></el-option>
		</el-select>
    </el-form-item>
	<el-form-item></el-form-item>
	</div>

</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, nextTick, computed } from 'vue';
import { useStore } from '/@/store';
import { list as getInevntorysApi } from '/@/api/inventory/typeDict';
import { list as getItemsApi } from '/@/api/inventory/itemDict';

interface ITypeAndItemCompare {
	typeCode: string; // 所属类型code
	loading: boolean;
	isRequest: boolean; // 是否请求过
	list: any[];
}

interface IState {
	formData: {
		typeCode: string;
		itemCode: string;
	};
	typeOptions: any[];
	typeAndItemCompareOptions: ITypeAndItemCompare[];
	typeLoading: boolean;
}

export default defineComponent({
	name: 'InventoryDictionarySelectByFormItem',
	props: {
		size: {
			type: String,
			default: 'small',
		},
		// -1全部 0耗材 1药品
		typeCategory: {
			type: Number,
			default: -1
		}
	},
	emits: ['change'],
	setup(props, context) {
		const store: any = useStore();

		const state = reactive<IState>({
			formData: {
				typeCode: '', // 物品类型code
				itemCode: '', // 物品code
			},
			typeOptions: [], // 物品类型选项数据
			typeAndItemCompareOptions: [], // 类型/物品关联选项数据
			typeLoading: false, // 物品类型的loading
		});

		const itemDatas = computed(() => {
			const defaultData = {
				typeCode: '',
				loading: false,
				isRequest: true,
				list: [],
			};
			if (!state.formData.typeCode) return defaultData;
			const item = state.typeAndItemCompareOptions.find((e) => e.typeCode === state.formData.typeCode);
			if (item) {
				return item;
			} else {
				return defaultData;
			}
		});

		const getTypeDatas = async () => {
			state.typeLoading = true;
			try {
				const params = {
					page: 0,
					size: 0,
					wherecondition: `client_code='${store.state.userInfos.userInfos.client.code}' or (client_code is null or client_code = '')`,
					ordercondition: 'sort_order asc',
					isFilterShowState: 1,
				};

				const { data } = await getInevntorysApi(params);

				let listCopy = data.list;
				if (props.typeCategory !== -1) {
					listCopy = data.list.filter((e: any) => e.typeCategory === props.typeCategory)
				}

				state.typeOptions = listCopy.map((v: any) => {
					return {
						label: v.typeName,
						value: v.code,
					};
				});

				// 初始化类型/物品关联选项数据
				state.typeAndItemCompareOptions = listCopy.map((v: any) => {
					return {
						typeCode: v.code,
						loading: false,
						isRequest: false,
						list: [],
					};
				});
			} finally {
				state.typeLoading = false;
			}
		};

		/**
		 * 获取物品数据
		 */
		const getItemDatas = async (code: string, i: number) => {
			state.typeAndItemCompareOptions[i].loading = true;
			state.typeAndItemCompareOptions[i].isRequest = true;
			try {
				const params = {
					page: 0,
					size: 0,
					wherecondition: `inventory_type_code='${code}' and is_show = 1 and client_code='${store.state.userInfos.userInfos.client.code}'`,
					ordercondition: 'item_is_use desc, item_sort_order asc',
					isPure: 0,
				};
				const { data } = await getItemsApi(params);
				state.typeAndItemCompareOptions[i].list = data.list.map((v: any) => {
					return {
						label: v.itemName,
						value: v.code,
					};
				});
			} finally {
				state.typeAndItemCompareOptions[i].loading = false;
			}
		};

		/** 物品类型的改变 */
		const onChangeByType = (val: string) => {
			// 物品类型改变时清除选中的物品
			state.formData.itemCode = '';
			context.emit('change', JSON.parse(JSON.stringify(state.formData)));

			if (val) {
				// 判断当前类型是否存在物品数据，如果没有则进行请求
				const itemIndex = state.typeAndItemCompareOptions.findIndex((e) => e.typeCode === val);
				if (itemIndex === -1) return false;
				const typeItem = JSON.parse(JSON.stringify(state.typeAndItemCompareOptions[itemIndex]));
				// 如果已经请求过了，那么直接返回
				if (typeItem.isRequest) return false;
				getItemDatas(val, itemIndex);
			}
		};

		/** 物品名称的改变 */
		const onChangeByItem = () => {
			context.emit('change', JSON.parse(JSON.stringify(state.formData)));
		};

		onMounted(() => {
			getTypeDatas();
		});

		return {
			...toRefs(state),
			itemDatas,
			onChangeByType,
			onChangeByItem,
		};
	},
});
</script>

<style lang="scss" scoped>
.inventory_dictionary_select_container {
	display: inline-block;
	.label_span {
	}
	.comp {
		margin-right: 15px;
	}
}
</style>