<script setup name="Demo" lang="ts">
import { listDemo, pageDemo, getDemo, delDemo, addDemo, updateDemo } from "@/api/demo/demo";
import { getToken } from "@/utils/auth";
import { ComponentInternalInstance } from "vue";
import { ElUpload, UploadFile, UploadFiles, DateModelType } from 'element-plus';
import { DemoForm, DemoQuery, DemoVO } from "@/api/demo/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const demoList = ref<DemoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([])
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const daterangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const demoFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);
const uploadRef = ref(ElUpload);

const dialog = reactive<DialogOption>({
	visible: false,
	title: ''
});

/** 用户导入参数 */
const upload = reactive<ImportOption>({
	// 是否显示弹出层（用户导入）
	open: false,
	// 弹出层标题（用户导入）
	title: "",
	// 是否禁用上传
	isUploading: false,
	// 设置上传的请求头部
	headers: { Authorization: "Bearer " + getToken() },
	// 上传的地址
	url: import.meta.env.VITE_APP_BASE_API + "demo/demo/importData"
})

// 列显隐信息
const columns = ref<FieldOption[]>([
	{ key: 0, label: `主键`, visible: false },
	{ key: 1, label: `部门id`, visible: true },
	{ key: 2, label: `用户id`, visible: true },
	{ key: 3, label: `排序号`, visible: true },
	{ key: 4, label: `key键`, visible: true },
	{ key: 5, label: `值`, visible: true },
	{ key: 6, label: `创建时间`, visible: true },
	{ key: 7, label: `创建人`, visible: true },
	{ key: 8, label: `更新时间`, visible: true },
	{ key: 9, label: `更新人`, visible: true }
]);

const initDataForm: DemoForm = {
	id: undefined,
	deptId: undefined,
	userId: undefined,
	orderNum: 0,
	testKey: '',
	value: '',
	version: '',
	ossConfigId: undefined,
}
const data = reactive<PageData<DemoForm, DemoQuery>>({
	form: { ...initDataForm },
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		testKey: '',
		value: '',
		createTime: '',
	},
	rules: {
		testKey: [{ required: true, message: "key键不能为空", trigger: "blur" }],
		value: [{ required: true, message: "值不能为空", trigger: "blur" }],
	}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询OSS对象存储列表 */
const getList = async () => {
	loading.value = true;
	const res = await listDemo(proxy?.addDateRange(queryParams.value, daterangeCreateTime.value, "CreateTime"));
	demoList.value = res.rows;
	total.value = res.total;
	loading.value = false;
}
/** 自定义分页查询 */
const getPage = async () => {
	loading.value = true;
	const res = await pageDemo(proxy?.addDateRange(queryParams.value, daterangeCreateTime.value, "CreateTime"));
	demoList.value = res.rows;
	total.value = res.total;
	loading.value = false;
}
/** 取消按钮 */
const cancel = () => {
	reset();
	dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
	form.value = { ...initDataForm };
	demoFormRef.value.resetFields();
}
/** 搜索按钮操作 */
const handleQuery = () => {
	queryParams.value.pageNum = 1;
	getList();
}
/** 搜索按钮操作 */
const handlePage = () => {
	queryParams.value.pageNum = 1;
	getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
	daterangeCreateTime.value = ['', ''];
	queryFormRef.value.resetFields();
	handleQuery();
}
/** 选择条数  */
const handleSelectionChange = (selection: DemoVO[]) => {
	ids.value = selection.map(item => item.id);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
}
/** 新增按钮操作 */
const handleAdd = () => {
	dialog.visible = true;
	dialog.title = "添加测试单表";
	nextTick(() => {
		reset();
	})
}
/** 修改按钮操作 */
const handleUpdate = async (row?: DemoVO) => {
	loading.value = true;
	dialog.visible = true;
	dialog.title = "修改测试单表";
	const _ids = row?.id || ids.value[0];
	const res = await getDemo(_ids);
	nextTick(() => {
		reset();
		Object.assign(form.value, res.data)
		loading.value = false;
	})
}
/** 提交按钮 */
const submitForm = () => {
	demoFormRef.value.validate(async (valid: boolean) => {
		if (valid) {
			buttonLoading.value = true;
			if (form.value.ossConfigId) {
				await updateDemo(form.value).finally(() => buttonLoading.value = false);
			} else {
				await addDemo(form.value).finally(() => buttonLoading.value = false);
			}
			proxy?.$modal.msgSuccess("操作成功");
			dialog.visible = false;
			getList();
		}
	});
}
/** 删除按钮操作 */
const handleDelete = async (row?: DemoVO) => {
	const _ids = row?.id || ids.value;
	await proxy?.$modal.confirm('是否确认删除测试单表编号为"' + _ids + '"的数据项?');
	await delDemo(_ids).finally(() => loading.value = false);
	loading.value = false;
	getList();
	proxy?.$modal.msgSuccess("删除成功");
}
/** 导入按钮操作 */
const handleImport = () => {
	upload.title = "测试导入";
	upload.open = true;
}
/** 导出按钮操作 */
const handleExport = () => {
	proxy?.download("demo/demo/export", {
		...queryParams.value,
	}, `demo_${new Date().getTime()}.xlsx`);
}
/**文件上传中处理 */
const handleFileUploadProgress = () => {
	upload.isUploading = true;
}
/** 文件上传成功处理 */
const handleFileSuccess = (res: any, file: UploadFile, fileList: UploadFiles) => {
	upload.open = false;
	upload.isUploading = false;
	uploadRef.value.clearFiles();
	ElMessageBox.alert(res.msg, "导入结果", { dangerouslyUseHTMLString: true });
	getList();
}
/** 提交上传文件 */
function submitFileForm() {
	uploadRef.value.submit();
}

onMounted(() => {
	getList()
	getPage()
})
</script>

<template>
	<div class="p-2">
		<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
			<div class="search" v-show="showSearch">
				<el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
					<el-form-item label="key键" prop="testKey">
						<el-input v-model="queryParams.testKey" placeholder="请输入key键" clearable style="width: 200px" @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item label="值" prop="value">
						<el-input v-model="queryParams.value" placeholder="请输入值" clearable style="width: 200px" @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item label="创建时间">
						<el-date-picker
							v-model="daterangeCreateTime"
							value-format="YYYY-MM-DD HH:mm:ss"
							type="daterange"
							range-separator="-"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							:default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
						></el-date-picker>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
						<el-button type="primary" icon="search" @click="handlePage">搜索(自定义分页接口)</el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
		</transition>

		<el-card shadow="never">
			<template #header>
				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['demo:demo:add']">新增</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['demo:demo:edit']">修改</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['demo:demo:remove']">
							删除
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['demo:demo:import']">导入(校验)</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:demo:export']">导出</el-button>
					</el-col>
					<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
				</el-row>
			</template>

			<el-table v-loading="loading" :data="demoList" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="主键" align="center" prop="id" v-if="columns[0].visible" />
				<el-table-column label="部门id" align="center" prop="deptId" v-if="columns[1].visible" />
				<el-table-column label="用户id" align="center" prop="userId" v-if="columns[2].visible" />
				<el-table-column label="排序号" align="center" prop="orderNum" v-if="columns[3].visible" />
				<el-table-column label="key键" align="center" prop="testKey" v-if="columns[4].visible" />
				<el-table-column label="值" align="center" prop="value" v-if="columns[5].visible" />
				<el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="180">
					<template #default="scope">
						<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="创建人" align="center" prop="createByName" v-if="columns[7].visible" />
				<el-table-column label="更新时间" align="center" prop="updateTime" v-if="columns[8].visible" width="180">
					<template #default="scope">
						<span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="更新人" align="center" prop="updateByName" v-if="columns[9].visible" />
				<el-table-column label="操作" fixed="right" align="center" width="150" class-name="small-padding fixed-width">
					<template #default="scope">
						<el-tooltip content="修改" placement="top">
							<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:demo:edit']"></el-button>
						</el-tooltip>
						<el-tooltip content="修改" placement="top">
							<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['demo:demo:remove']"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>

			<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
		</el-card>

		<!-- 添加或修改测试单表对话框 -->
		<el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
			<el-form ref="demoFormRef" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="部门id" prop="deptId">
					<el-input v-model="form.deptId" placeholder="请输入部门id" />
				</el-form-item>
				<el-form-item label="用户id" prop="userId">
					<el-input v-model="form.userId" placeholder="请输入用户id" />
				</el-form-item>
				<el-form-item label="排序号" prop="orderNum">
					<el-input v-model="form.orderNum" placeholder="请输入排序号" />
				</el-form-item>
				<el-form-item label="key键" prop="testKey">
					<el-input v-model="form.testKey" placeholder="请输入key键" />
				</el-form-item>
				<el-form-item label="值" prop="value">
					<el-input v-model="form.value" placeholder="请输入值" />
				</el-form-item>
				<el-form-item label="创建时间" prop="createTime">
					<el-date-picker clearable v-model="form.createTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择创建时间">
					</el-date-picker>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 用户导入对话框 -->
		<el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
			<el-upload
				ref="uploadRef"
				:limit="1"
				accept=".xlsx, .xls"
				:headers="upload.headers"
				:action="upload.url + '?updateSupport=' + upload.updateSupport"
				:disabled="upload.isUploading"
				:on-progress="handleFileUploadProgress"
				:on-success="handleFileSuccess"
				:auto-upload="false"
				drag
			>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			</el-upload>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitFileForm">确 定</el-button>
					<el-button @click="upload.open = false">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
