<template>
	<div class="p20">
		<!-- 功能区 -->
		<el-card class="box-card">
			<el-row>
				<el-col :span="12">
					<el-text class="mx-1">关键词：</el-text>

					<el-input class="width200" placeholder="请输入物品名称" v-model="data.params.keyword"
						@keyup.enter.native="getList"> </el-input>

					<el-button type="primary" class="ml10" @click="getList">
						<el-icon>
							<ele-Search />
						</el-icon>
						查询
					</el-button>
				</el-col>
				<el-col :span="12" class="tr">
					<el-button type="primary" @click="addPage">添加</el-button>
					<el-button type="danger" @click="deleteMult">批量删除</el-button>
					<el-button type="default" @click="checkAll">查看全部</el-button>
					<el-button type="default" @click="importExcel()">导入</el-button>
					<el-button type="default" @click="exportExcel()">导出</el-button>
					<el-button type="default" @click="enable">启用</el-button>
					<el-button type="default" @click="forbidden">禁用</el-button>
				</el-col>
			</el-row>
		</el-card>
		<!-- 主体区 -->
		<el-row :gutter="20">
			<el-col :span="16">
				<el-card class="box-card mt20" v-loading="data.loading">
					<!-- 列表 -->
					<el-table :data="data.tableData" @selection-change="handleTableDataSelectionChange">
						<!-- props绑定数据表的字段，lable填写中文 -->
						<el-table-column type="selection" width="55" />
						<el-table-column fixed prop="no" label="物品编码" width="150"
							:default-sort="{ prop: 'date', order: 'descending' }" />
						<el-table-column prop="name" label="物品名称" width="150" />
						<el-table-column prop="desc" label="物品介绍" width="" />
						<el-table-column prop="goodClass.name" label="物品类别" width="" />
						<el-table-column prop="unit" label="单位" width="" />
						<el-table-column prop="spec" label="规格" width="" />
						<el-table-column prop="valid" label="是否有效" width="">
							<template #default="scope">
								<el-tag v-if="scope.row.valid == 1">启用</el-tag>
								<el-tag type="danger" v-if="scope.row.valid == 0">禁用</el-tag>
							</template>
						</el-table-column>
						<el-table-column fixed="right" label="操作" width="200">
							<template #default="scope">
								<el-button link type="primary" @click="openDetail(scope.row)">详情</el-button>
								<el-button link type="primary" @click="print(scope.row)">打印</el-button>
								<el-button link type="primary" @click="edit(scope.$index, scope.row)">编辑</el-button>
								<el-button link type="danger" @click="deleteOne(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<!-- 分页 -->
					<div class="yc_pagebox">
						<el-pagination v-model:current-page="data.pagination.currentPage"
							v-model:page-size="data.pagination.pageSize" :page-sizes="getThemeConfig.pageSizeArray"
							layout="total, sizes, prev, pager, next, jumper" :total="data.pagination.total"
							@size-change="handleSizeChange" @current-change="handleCurrentChange" />
					</div>
				</el-card>
			</el-col>
			<el-col :span="8">
				<el-card class="box-card mt20" v-loading="data.classLoading">
					<div class="class">
						<div class="classFont">物品分类</div>
						<el-button type="primary" @click="addClassPage">新增类别</el-button>
					</div>
					<div class="mt20">
						<el-input class="" placeholder="请输入物品分类名称" v-model="data.classParams.keyword"
							@keyup.enter.native="getClass"> </el-input>
					</div>
					<!-- 列表 -->
					<el-table :data="data.tableClassData" style="width: 100%" @row-click="checkproduct">
						<!-- props绑定数据表的字段，lable填写中文 -->
						<el-table-column prop="name" label="分类名称" width="" />
						<el-table-column prop="desc" label="分类说明" width="" />
						<el-table-column fixed="right" label="操作" width="200">
							<template #default="scope">
								<el-button link type="primary"
									@click.stop="classEdit(scope.$index, scope.row)">编辑</el-button>
								<el-button link type="danger" @click.stop="deleteClassOne(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</el-col>
		</el-row>
		<!-- 物品弹出容器 ，新增和修改的-->
		<vuecmf-dialog width="1000px" :model_value="data.dialog.show" :title="data.dialog.title" @close="closePage">
			<template #content>
				<el-form :model="newForm" label-width="120px" ref="formRef" v-loading="data.dialog.isLoading">
					<!-- 每个form-item就是一个表单的标签，label是名称，prop和v-model绑定字段名 -->
					<!-- <el-form-item label="物品图片" prop="img">
						<el-avatar shape="square" :size="100" fit="fill" :src="newForm.img" />
						<el-text class="mx-1" type="info"
							style="margin-top: -80px; margin-left: 20px;">尺寸316*316，小于100k</el-text>
					</el-form-item> -->
					<el-row>
						<el-col :span="12">
							<el-form-item label="物品编码" prop="no"
								:rules="[{ required: true, message: '请选择状态', trigger: 'blur' }]">
								<el-input v-model="newForm.no" placeholder="填写物品代码" />
							</el-form-item></el-col>
						<el-col :span="12">
							<el-form-item label="物品名称" prop="name"
								:rules="[{ required: true, message: '请选择状态', trigger: 'blur' }]">
								<el-input v-model="newForm.name" placeholder="填写物品名称" />
							</el-form-item></el-col>
					</el-row>
					<el-row class="mt20">
						<el-col :span="12">
							<el-form-item label="物品单位" prop="unit">
								<el-input v-model="newForm.unit" placeholder="填写物品单位" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物品介绍" prop="desc">
								<el-input v-model="newForm.desc" placeholder="填写物品介绍" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row class="mt20">
						<el-col :span="12">
							<el-form-item label="物品规格" prop="spec">
								<el-input v-model="newForm.spec" placeholder="填写物品规格" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物品分类" prop="good_class_id">
								<el-select v-model="newForm.good_class_id" value-key="id" placeholder="选择物品分类">
									<el-option v-for="item in data.region" :key="item.id" :label="item.name"
										:value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item class="mt20" label="状态" prop="valid"
						:rules="[{ required: true, message: '请选择状态', trigger: 'blur' }]">
						<el-radio-group v-model="newForm.valid">
							<el-radio :label="1">启用</el-radio>
							<el-radio :label="0">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
				<div class="height20"></div>
			</template>
			<template #footer>
				<el-button type="default" @click="closePage">取消</el-button>
				<el-button type="primary" @click="submitForm(formRef)">确定</el-button>
			</template>
		</vuecmf-dialog>

		<!-- 详情弹出容器-->
		<vuecmf-dialog width="1000px" :model_value="data.dialogDetail.showDetail" :title="data.dialogDetail.titleDetail"
			@close="closePage">
			<template #content>
				<el-form :model="newForm" label-width="120px" ref="formRef" v-loading="data.dialogDetail.isLoadingDetail">
					<!-- 每个form-item就是一个表单的标签，label是名称，prop和v-model绑定字段名 -->
					<!-- <el-form-item label="物品图片" prop="img">
						<el-avatar shape="square" :size="100" fit="fill" :src="newForm.img" />
						<el-text class="mx-1" type="info"
							style="margin-top: -80px; margin-left: 20px;">尺寸316*316，小于100k</el-text>
					</el-form-item> -->
					<el-row>
						<el-col :span="12">
							<el-form-item label="物品编码：" prop="no">
								<el-text class="mx-1">{{ newForm.no }}</el-text>
							</el-form-item></el-col>
						<el-col :span="12">
							<el-form-item label="物品名称：" prop="name">
								<el-text class="mx-1">{{ newForm.name }}</el-text>
							</el-form-item></el-col>
					</el-row>
					<el-row class="mt20">
						<el-col :span="12">
							<el-form-item label="物品单位：" prop="unit">
								<el-text class="mx-1">{{ newForm.unit }}</el-text>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物品介绍：" prop="desc">
								<el-text class="mx-1">{{ newForm.desc }}</el-text>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row class="mt20">
						<el-col :span="12">
							<el-form-item label="物品规格：" prop="spec">
								<el-text class="mx-1">{{ newForm.spec }}</el-text>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物品分类：" prop="good_class_id">
								<el-text class="mx-1">{{ newForm.good_class_id }}</el-text>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item class="mt20" label="状态：" prop="valid">
						<el-text class="mx-1">{{ newForm.valid == 1 ? "启用" : "禁用" }}</el-text>
					</el-form-item>
				</el-form>
				<div class="height20"></div>
			</template>
		</vuecmf-dialog>

		<!-- 物品分类弹出容器 ，新增和修改的-->
		<vuecmf-dialog width="1000px" :model_value="data.classDialog.classShow" :title="data.classDialog.classTitle"
			@close="closePage">
			<template #content>
				<el-form :model="data.form" label-width="120px" ref="formRef" v-loading="data.classDialog.classIsLoading">
					<!-- 每个form-item就是一个表单的标签，label是名称，prop和v-model绑定字段名 -->
					<el-form-item label="分类名称" prop="name"> <el-input v-model="data.form.name" placeholder="填写分类名称" />
					</el-form-item>
					<el-form-item label="分类说明" prop="desc"> <el-input v-model="data.form.desc" placeholder="填写分类说明" />
					</el-form-item>
				</el-form>
				<div class="height20"></div>
			</template>
			<template #footer>
				<el-button type="default" @click="closePage">取消</el-button>
				<el-button type="primary" @click="submitClassForm(formRef)">确定</el-button>
			</template>
		</vuecmf-dialog>
		<ImportExcelDialog ref="importExcelDialogRef" @refresh="getTableData()" />
		<ExportExcelDialog ref="exportExcelDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, computed, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import Good from '/@/api/model/Good'; //gzs:引入模型
import GoodClass from '/@/api/model/GoodClass';//gzs:引入模型
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import router from '/@/router';
// 定义变量内容
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 获取布局配置信息
const getThemeConfig = computed(() => {
	return themeConfig.value;
});
const formRef = ref<FormInstance>();
const multipleSelection = ref([]);
//双向绑定的变量，推荐只定义1个
//注意：所有变量初始化后再使用
const data = reactive({
	//请求查询的参数
	params: {
		pageSize: getThemeConfig.value.pageSize, //分页大小
		page: 1, //当前页面
		keyword: '', //关键字
		good_class_id: null,
	},
	classParams: {
		pageSize: getThemeConfig.value.pageSize, //分页大小
		page: 1, //当前页面
		keyword: '', //关键字
	},
	//分页组件的变量
	pagination: {
		currentPage: 1,
		pageSize: getThemeConfig.value.pageSize,
		total: 100,
	},
	loading: false, //是否加载中
	classPagination: {
		currentPage: 1,
		pageSize: getThemeConfig.value.pageSize,
		total: 100,
	},
	classLoading: false, //是否加载中
	tableData: [], // 表格数据
	tableClassData: [], //分类表格数据
	//物品弹出框
	dialog: {
		show: false, // 是否显示弹出框，用于最大化、最小化及还原
		title: '添加', // 弹出框标题
		isLoading: false, //是否加载中
		type: "edit" as "submit" | "edit"	// 表单类型 edit|submit
	},
	//详情弹出框
	dialogDetail: {
		showDetail: false, // 是否显示弹出框，用于最大化、最小化及还原
		titleDetail: '添加', // 弹出框标题
		isLoadingDetail: false, //是否加载中
	},
	//分类弹出框
	classDialog: {
		classShow: false, // 是否显示弹出框，用于最大化、最小化及还原
		classTitle: '添加', // 弹出框标题
		classIsLoading: false, //是否加载中
	},
	form: {} as any, //分类新增和修改表单数据
	//扫码枪
	value: '',
	//物品分类选择
	region: [] as any,
	//导出
	impparam: {
		date: "",
		keyword: "",
		product_id: "",
		classes_id: "",
		page: 1,
		list_rows: 10,
		is_sort: 0
	},
});
/**
 * 监听页数
 */
watch(() => [data.params.good_class_id, data.params.keyword], (count, prevCount) => {
	data.params.page = 1
	getList();
}
)

// 初始化表格数据
const getTableData = () => {
	getList();
	getClass();
};
/**
 * 导入、导出
 */
const ImportExcelDialog = defineAsyncComponent(() => import("/@/views/payrollModule/import.vue"));
const importExcelDialogRef = ref();
const importExcel = () => {
	importExcelDialogRef.value.openDialog();
};

const ExportExcelDialog = defineAsyncComponent(() => import("/@/views/payrollModule/export.vue"));
const exportExcelDialogRef = ref();
const exportExcel = () => {
	// return ElMessage.warning("功能正在完善中");
	exportExcelDialogRef.value.openDialog(data.impparam);
};
/**
 * 实例化1个表单对象
 */
const newForm = reactive({
	no: '',
	name: '',
	desc: '',
	unit: '',
	img: '',
	spec: '',
	index: 0,
	good_class_id: '' as number | string,
	valid: 1,
});
/**
 * 实例化1个分类表单对象
 */
const newClassForm = () => {
	let form = {
		id: 0,
		name: '',
		desc: '',
		valid: 1,
	};
	return form;
};
/**
 * 启用、禁用
 */
const enable = async () => {
	const items = multipleSelection.value.map((item: any) => { item.valid = 1; return item });
	let res = await Good.edit(items);
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	ElMessage.success(res.msg);
	getList()
};
const forbidden = async () => {
	const items = multipleSelection.value.map((item: any) => { item.valid = 0; return item });
	let res = await Good.edit(items);
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	ElMessage.success(res.msg);
	getList()
};
/**
 * 切换页面大小
 * @param val
 */
const handleSizeChange = (val: number) => {
	data.params.pageSize = val;
	data.classParams.pageSize = val;
	getList();
	getClass()
};
/**
 * 翻页
 */
const handleCurrentChange = (val: number) => {
	data.params.page = val;
	getList();
};

const search = async () => {
	data.params.page = 1;
	await getList();
};
/**
 * 页面初始化方法，有就写逻辑，没有可以留空
 */
const init = async () => { };
/**
 * 获取所有分类数据
 */
const getAll = async () => {
	data.loading = true;
	const res = await GoodClass.all();
	data.loading = false;
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	console.log("getAllres", res);
	data.region = res.data
	console.log("data.region", data.region);
};
/**
 * 获取分类列表数据
 */
const getClass = async () => {
	data.classLoading = true;
	const res = await GoodClass.list({
		pageParams: {
			page: data.classParams.page,
			size: data.classParams.pageSize,
		},
		keyword: data.classParams.keyword
	});
	data.classLoading = false;
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	console.log("getClass", res);
	data.tableClassData = res.data.data;
	//分页数据赋值
	// data.classPagination.total = res.data.total;
	// data.classPagination.currentPage = res.data.current_page;
	// data.classPagination.pageSize = res.data.per_page;
};
/**
 * 点击查看全部
 */
const checkAll = async () => {
	data.params.good_class_id = null
	getList();
};
/**
 * 点击分类选项查看物品分类
 */
const checkproduct = async (row: any) => {
	console.log("check", row.id);
	data.params.good_class_id = row.id;
};
/**
 * 获取分页数据
 */
const getList = async () => {
	data.loading = true;
	const res = await Good.list({
		pageParams: {
			page: data.params.page,
			size: data.params.pageSize,
		},
		keyword: data.params.keyword,
		good_class_id: data.params.good_class_id
	}); //异步请求获取 分页数据，接口返回，0为成功，非0失败
	data.loading = false;
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	data.tableData = res.data.data;
	//分页数据赋值
	data.pagination.total = res.data.total;
	data.pagination.currentPage = res.data.current_page;
	data.pagination.pageSize = res.data.per_page;
};
// 翻页
const handleTableDataSelectionChange = (val: any) => {
	multipleSelection.value = val;
	console.log('lzj500🚀 ~ file: index.vue:203 ~ handleTableDataSelectionChange ~ val:', val);
};
//=========添加 和 编辑 删除
/**
 * 关闭弹出框
 */
const closePage = () => {
	data.dialog.show = false;
	data.dialogDetail.showDetail = false;
	data.classDialog.classShow = false;
};

/**
 * 弹出新增分类页面
 */
const addClassPage = () => {
	data.classDialog.classShow = true;
	data.classDialog.classTitle = '添加分类'; //gzs:标题
	data.form = newClassForm();
	console.log('lzj500🚀 ~ file: index.vue:160 ~ addPage ~ dialog:', data.classDialog);
};
/**
 * 弹出新增页面
 */
const addPage = async () => {
	await getAll();
	data.dialog.show = true;
	data.dialog.title = '添加物品'; //gzs:标题
	data.dialog.type = "submit";
	newForm.no = '';
	newForm.desc = '';
	newForm.good_class_id = '';
	newForm.img = '';
	newForm.unit = '';
	newForm.valid = 1;
	newForm.spec = '';
	newForm.name = '';
	console.log('lzj500🚀 ~ file: index.vue:160 ~ addPage ~ dialog:', data.dialog);
};
/**
 * 弹出 分类编辑页面
 */
const classEdit = async (index: number, item: any) => {
	data.classDialog.classShow = true;
	data.classDialog.classTitle = '编辑分类';
	data.form = item;
};
/**
 * 弹出 编辑页面
 */
const edit = async (index: number, item: any) => {
	data.dialog.show = true;
	data.dialog.title = '编辑物品';
	data.dialog.type = "edit";
	newForm.no = item.no;
	newForm.desc = item.desc;
	newForm.good_class_id = item.good_class_id;
	newForm.img = item.img;
	newForm.unit = item.unit;
	newForm.valid = item.valid;
	newForm.spec = item.spec;
	newForm.name = item.name;
	newForm.index = item.id;
	// await detail(item.id);
};
/**
 * 弹出详情页面
 */
const openDetail = async (item: any) => {
	console.log("itemitem", item);

	data.dialogDetail.showDetail = true;
	data.dialogDetail.titleDetail = '仓库详情';
	newForm.no = item.no;
	newForm.desc = item.desc;
	newForm.good_class_id = item.goodClass.name;
	newForm.img = item.img;
	newForm.unit = item.unit;
	newForm.valid = item.valid;
	newForm.spec = item.spec;
	newForm.name = item.name;
	newForm.index = item.id;
};
/**
 * 打印机打印
 */
const print = (item: any) => {
	// let url = window.location.href.split('/data/good')[0];
	// setTimeout(() => {
	// 	window.open(url + `/data/print?no=${item.no}&name=${item.name}`);
	// }, 500)
	router.push({ name: 'printGood', query: { no: item.no, name: item.name } });
};
/**
 * 分类的提交 表单，新增和修改都在这里
 */
const submitClassForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async (valid) => {
		if (!valid) {
			console.log('error submit!');
			return false;
		}

		// console.log('submit!');
		let res = null;
		data.classDialog.classIsLoading = true;
		if (data.form?.id) {
			//如果是编辑
			res = await GoodClass.edit(data.form);
		} else {
			res = await GoodClass.add(data.form);
		}
		data.classDialog.classIsLoading = false;
		if (res.code != 0) {
			ElMessage.error(res.msg);
			return;
		}
		ElMessage.success(res.msg);
		await getClass();
		search();
		closePage();
	});
};
/**
 * 提交 表单，新增和修改都在这里
 */
const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async (valid) => {
		if (!valid) {
			console.log('error submit!');
			return false;
		}
		let res = null;
		data.dialog.isLoading = true;
		console.log("🚀 ~ file: good.vue:638 ~ formEl.validate ~ newForm:", newForm)
		if (data.dialog.type == "edit") {
			//如果是编辑
			res = await Good.edit([{
				id: newForm.index,
				no: newForm.no,
				name: newForm.name,
				img: newForm.img,
				spec: newForm.spec,
				valid: newForm.valid,
				unit: newForm.unit,
				desc: newForm.desc,
				good_class_id: newForm.good_class_id,
			}])
		} else {
			res = await Good.add(newForm);
		}
		data.dialog.isLoading = false;
		if (res.code != 0) {
			ElMessage.error(res.msg);
			return;
		}
		ElMessage.success(res.msg);
		search();
		closePage();
	});
};
//删除分类1条数据
const deleteClassOne = (item: any) => {
	ElMessageBox.confirm('删除后不可恢复，确定要删除该记录吗？', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			doClassDelete(item.id);
		})
		.catch(() => { });
};
//删除1条数据
const deleteOne = (item: any) => {
	ElMessageBox.confirm('删除后不可恢复，确定要删除该记录吗？', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			doDelete([item.id]);
		})
		.catch(() => { });
};
//删除多条数据
const deleteMult = (item: any) => {
	if (multipleSelection.value.length == 0) {
		ElMessage.error('请选择要删除的记录');
		return;
	}
	let ids = multipleSelection.value.map((item: any) => item.id);
	ElMessageBox.confirm('删除后不可恢复，确定要删除选中记录吗？', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			doDelete(ids);
		})
		.catch(() => { });
};

//执行分类删除请求
const doClassDelete = async (id: any) => {
	data.loading = true;
	let res = await GoodClass.delete({ id });
	data.loading = false;
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	await getClass();
};
//执行删除请求
const doDelete = async (id: any) => {
	data.loading = true;
	let res = await Good.delete({ id });
	data.loading = false;
	if (res.code != 0) {
		ElMessage.error(res.msg);
		return;
	}
	await getList();
};
//=========页面事件
/**
 * 页面加载时事件
 */
onMounted(async () => {
	getList();
	getClass();
	getAll();
	init();
});


</script>
<style>
.class {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.classFont {
	color: #31373D;
	font-size: 14px;
	font-weight: bold;
}

.active {
	color: blue;
}
</style>
