<template>
	<div>
		<el-card shadow="hover">
			<QueryForm
				v-model="searchForm"
				:fields="searchFields"
				@search="onSearch"
				@reset="onReset"
				ref="queryFormRef"
			/>

			<el-row :gutter="10" style="padding-bottom: 10px">
				<el-col :span="1.5">
					<el-button type="primary" @click="handleAdd" v-auth="'api/v1/businesses/speciesName/add'"
						><el-icon><ele-Plus /></el-icon>新增</el-button
					>
				</el-col>
				<el-col :span="1.5">
					<el-button
						type="danger"
						:disabled="multiple"
						@click="handleDelete(null)"
						v-auth="'api/v1/businesses/speciesName/delete'"
						><el-icon><ele-Delete /></el-icon>删除</el-button
					>
				</el-col>
			</el-row>

			<ProTable
				v-if="columns.length > 0"
				ref="proTableRef"
				:columns="columns"
				:data="tableData.data"
				:loading="loading"
				:show-selection="true"
				@selection-change="handleSelectionChange"
				:heightOffset="400"
				:action-width="280"
				:show-expand="true"
			>
				<template #expand="{ row }">
					<el-form-item label="核查意见">
						{{ row.auditView }}
					</el-form-item>
					<el-form-item label="备注">
						{{ row.remark }}
					</el-form-item>
				</template>
				<template #actions="{ row }">
					<el-button
						type="primary"
						@click="handleUpdate(row)"
						size="small"
						v-auth="'api/v1/businesses/speciesName/edit'"
						v-if="row.auditStatus != 1"
						><el-icon><ele-EditPen /></el-icon>修改</el-button
					>
					<el-button
						type="danger"
						size="small"
						@click="handleDelete(row)"
						v-auth="'api/v1/businesses/speciesName/delete'"
						><el-icon><ele-DeleteFilled /></el-icon>删除</el-button
					>
					<el-button
						type="warning"
						size="small"
						@click="handleAudit(row)"
						v-if="row.auditStatus == 0"
						v-auth="'api/v1/businesses/speciesName/audit'"
						><el-icon><ele-Check /></el-icon>审核</el-button
					>
				</template>
			</ProTable>

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

		<ModalForm
			v-model:visible="showDialog"
			:title="formTitle"
			:fields="formFields"
			v-model:modelValue="formData"
			:type="formType"
			:show-footer="true"
			:label-width="'120px'"
			:width="'50%'"
			@submit="handleFormSubmit"
			@cancel="handleCancel"
			ref="modalFormRef"
		>
		</ModalForm>

		<AuditForm
			ref="auditFormRef"
			v-model="showAuditDialog"
			title="审核数据"
			@submit="onAuditSubmit"
		/>
	</div>
</template>
<script setup lang="ts">
import { toRefs, reactive, onMounted, ref, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {
	listSpeciesName,
	delSpeciesName,
	addSpeciesName,
	updateSpeciesName,
	auditSpeciesName,
} from './api';
import {
	SpeciesNameTableColumns,
	SpeciesNameInfoData,
	SpeciesNameTableDataState,
} from '/@/views/businesses/speciesName/type';
import QueryForm from '/@/components/dynamicpage/queryForm/index.vue';
import ProTable from '/@/components/dynamicpage/ProTable/index.vue';
import ModalForm from '/@/components/dynamicpage/modalForm/index.vue';
import AuditForm from '/@/components/dynamicpage/auditForm/index.vue';
import { QueryFormField, TableColumn, PopupFormField } from '/@/components/dynamicpage/type';
import { getUserList } from '/@/api/system/user/index';
import { UserItem, VersionMap } from '/@/types';
import { parseTime } from '/@/utils/gfast';
import { cloneDeep } from 'lodash';
defineOptions({ name: 'apiV1DemoSpeciesNameList' });

const loading = ref(false);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
const userOptions = ref<UserItem[]>([]);

const state = reactive<SpeciesNameTableDataState>({
	ids: [],
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			pageNum: 1,
			pageSize: 10,
		},
	},
});
const versionMap = ref<VersionMap>({} as VersionMap);
const proTableRef = ref();
const { tableData } = toRefs(state);
const columns: TableColumn[] = [
	{ label: '物种编码', prop: 'speciesCode' },
	{ label: '物种名称', prop: 'name' },
	{ label: '物种名称内容', prop: 'content' },
	{ label: '数据来源', prop: 'sourcesData' },
	{
		label: '数据采集人',
		prop: 'createUser',
		isFormater: true,
		formater(row, column, cellValue, index) {
			const user = userOptions.value.find((i) => i.id === cellValue);
			return user ? user.userNickname : '';
		},
	},
	{
		label: '数据采集日期',
		prop: 'createDate',
		isFormater: true,
		formater(_: SpeciesNameTableColumns, col: any, val: string) {
			return parseTime(val, '{y}-{m}-{d}');
		},
	},
	{
		label: '数据核查人',
		prop: 'auditUser',
		isFormater: true,
		formater(row, column, cellValue, index) {
			const user = userOptions.value.find((i) => i.id === cellValue);
			return user ? user.userNickname : '';
		},
	},
	{
		label: '数据核查日期',
		prop: 'auditDate',
		isFormater: true,
		formater(_: SpeciesNameTableColumns, col: any, val: string) {
			return parseTime(val, '{y}-{m}-{d}');
		},
	},
	{
		label: '状态',
		prop: 'auditStatus',
		isFormater: true,
		formater(row, column, cellValue, index) {
			return cellValue == 0 ? '待审核' : cellValue == 1 ? '通过' : '不通过';
		},
	},
];

const onSearch = async (val: Record<string, any>) => {
	let newVal: Record<string, any> = {};
	for (const v in val) {
		if (val[v]) {
			newVal[v] = val[v];
		}
	}
	state.tableData.param = { ...state.tableData.param, ...newVal };
	speciesNameList();
};
const onReset = () => {
	state.tableData.param = {
		pageNum: 1,
		pageSize: 10,
	};
	speciesNameList();
};
const searchForm = ref<Omit<SpeciesNameInfoData, 'id' | 'remark' | 'content'>>({
	speciesCode: undefined,
	name: undefined,
	sourcesData: undefined,
	createUser: undefined,
	createDate: undefined,
	auditUser: undefined,
	auditDate: undefined,
});
const searchFields = computed<QueryFormField[]>(() => [
	{ label: '物种编码', prop: 'speciesCode', type: 'input', placeholder: '请输入物种编码' },
	{ label: '物种名称', prop: 'name', type: 'input', placeholder: '请输入物种名称' },
	{ label: '数据来源', prop: 'sourcesData', type: 'input', placeholder: '请输入数据来源' },
	{
		label: '数据采集人',
		prop: 'createUser',
		type: 'select',
		options: userOptions.value.map((i) => {
			return {
				label: i.userNickname,
				value: i.id,
			};
		}),
		placeholder: '请选择数据采集人',
	},
	{ label: '数据采集日期', prop: 'createDate', type: 'daterange', valueFormat: 'YYYY-MM-DD' },

	{
		label: '数据核查人',
		prop: 'auditUser',
		type: 'select',
		options: userOptions.value.map((i) => {
			return {
				label: i.userNickname,
				value: i.id,
			};
		}),
		placeholder: '请选择数据核查人',
	},
	{ label: '数据核查日期', prop: 'auditDate', type: 'daterange', valueFormat: 'YYYY-MM-DD' },
]);

// 页面加载时
onMounted(() => {
	initTableData();
});
// 初始化表格数据
const initTableData = () => {
	speciesNameList();
	reqGetUserList();
};
// 获取列表数据
const speciesNameList = async () => {
	loading.value = true;
	const res = await listSpeciesName(state.tableData.param);
	let list = res.data.list ?? [];
	state.tableData.data = list;
	versionMap.value = list.reduce((acc: any, cur: any) => {
		acc[cur.id] = cur.version;
		return acc;
	}, {});
	state.tableData.total = res.data.total;
	loading.value = false;
};
const reqGetUserList = async () => {
	if (userOptions.value.length > 0) return;
	const res = await getUserList({ pageSize: 9999, pageNum: 1 });
	userOptions.value = res.data.userList;
};
// 多选框选中数据
const handleSelectionChange = (selection: Array<SpeciesNameInfoData>) => {
	state.ids = selection.map((item) => item.id);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
};

const showDialog = ref(false);
const formTitle = ref('');
const formFields = computed<PopupFormField[]>(() => [
	{
		label: '物种编码',
		prop: 'speciesCode',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入物种编码', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入物种编码',
		},
	},
	{
		label: '物种名称',
		prop: 'name',
		span: 12,
		type: 'input',
		rules: [{ required: true, message: '请输入物种名称', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入物种名称',
		},
	},
	{
		label: '物种名称内容',
		prop: 'content',
		type: 'input',
		rules: [{ required: true, message: '请输入物种名称内容', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入物种名称内容',
			type: 'textarea',
		},
	},
	{
		label: '数据来源',
		prop: 'sourcesData',
		span: 24,
		type: 'input',
		rules: [{ required: true, message: '请输入数据来源', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入数据来源',
		},
	},
	{
		label: '数据采集人',
		span: 12,
		prop: 'createUser',
		type: 'select',
		rules: [{ required: true, message: '请选择数据采集人', trigger: 'change' }],
		componentProps: {
			placeholder: '请选择数据采集人',
		},
		options: userOptions.value.map((i) => {
			return {
				label: i.userNickname,
				value: i.id,
			};
		}),
	},
	{
		label: '数据采集日期',
		span: 12,
		prop: 'createDate',
		type: 'date',
		rules: [{ required: true, message: '请选择数据采集日期', trigger: 'change' }],
		componentProps: {
			placeholder: '请选择数据采集日期',
		},
	},
	// {
	// 	label: '数据核查人',
	// 	span: 12,
	// 	prop: 'auditUser',
	// 	type: 'select',
	// 	rules: [{ required: true, message: '请选择数据核查人', trigger: 'change' }],
	// 	componentProps: {
	// 		placeholder: '请选择数据核查人',
	// 	},
	// 	options: userOptions.value.map((i) => {
	// 		return {
	// 			label: i.userNickname,
	// 			value: i.id,
	// 		};
	// 	}),
	// },
	// {
	// 	label: '数据核查日期',
	// 	span: 12,
	// 	prop: 'auditDate',
	// 	type: 'date',
	// 	rules: [{ required: true, message: '请选择数据核查日期', trigger: 'change' }],
	// 	componentProps: {
	// 		placeholder: '请选择数据核查日期',
	// 	},
	// },
	{
		label: '备注',
		prop: 'remark',
		span: 24,
		type: 'input',
		componentProps: {
			placeholder: '请输入备注',
			type: 'textarea',
		},
	},
]);
const formData = ref<SpeciesNameInfoData>({
	id: undefined,
	speciesCode: undefined,
	name: undefined,
	content: undefined,
	sourcesData: undefined,
	createUser: undefined,
	createDate: undefined,
	auditUser: undefined,
	auditDate: undefined,
	remark: undefined,
});
const formType = ref<'add' | 'edit'>('add');

const handleFormSubmit = (form: SpeciesNameInfoData) => {
	if (formType.value === 'add') {
		addSpeciesName(form).then(() => {
			ElMessage.success('新增成功');
			handleCancel();
			speciesNameList();
		});
	} else {
		form.auditStatus = 0;
		updateSpeciesName(form).then(() => {
			ElMessage.success('编辑成功');
			handleCancel();
			speciesNameList();
		});
	}
};
const handleCancel = () => {
	showDialog.value = false;
	formTitle.value = '';
	formType.value = 'add';
	formData.value = {
		id: undefined,
		speciesCode: undefined,
		name: undefined,
		content: undefined,
		sourcesData: undefined,
		createUser: undefined,
		createDate: undefined,
		auditUser: undefined,
		auditDate: undefined,
		remark: undefined,
	};
};

const handleAdd = () => {
	showDialog.value = true;
	formTitle.value = '新增物种名称';
	formType.value = 'add';
};
const handleUpdate = (row: SpeciesNameTableColumns) => {
	showDialog.value = true;
	formTitle.value = '编辑物种名称';
	formType.value = 'edit';
	formData.value = cloneDeep(row);
};
const handleDelete = (row: SpeciesNameTableColumns | null) => {
	let msg = '你确定要删除所选数据？';
	let id: number[] = [];
	if (row) {
		msg = `此操作将永久删除数据，是否继续?`;
		id = [row.id];
	} else {
		id = state.ids;
	}
	if (id.length === 0) {
		ElMessage.error('请选择要删除的数据。');
		return;
	}
	ElMessageBox.confirm(msg, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			delSpeciesName(
				id,
				id.map((i) => versionMap.value[i])
			).then(() => {
				ElMessage.success('删除成功');
				speciesNameList();
			});
		})
		.catch(() => {});
};

const auditFormRef = ref();
const showAuditDialog = ref(false);
const handleAudit = (row: SpeciesNameTableColumns) => {
	auditFormRef.value.open(cloneDeep(row), userOptions.value);
};
const onAuditSubmit = (val: SpeciesNameTableColumns) => {
	auditSpeciesName(val).then(() => {
		ElMessage.success('审核成功');
		showAuditDialog.value = false;
		speciesNameList();
	});
};
</script>
