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

			<el-row :gutter="10" class="mb8">
				<el-col :span="1.5">
					<el-button
						type="primary"
						@click="handleAdd"
						v-auth="'api/v1/businesses/classifyStatuse/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/classifyStatuse/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"
			>
				<template #actions="{ row }">
					<el-button
						type="primary"
						@click="handleUpdate(row)"
						size="small"
						v-auth="'api/v1/businesses/classifyStatuse/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/classifyStatuse/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/classifyStatuse/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="getList"
			/>
		</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 {
	listClassifyStatuse,
	delClassifyStatuse,
	addClassifyStatuse,
	updateClassifyStatuse,
	auditSpeciesName,
} from './api';
import {
	ClassifyStatuseTableColumns,
	ClassifyStatuseInfoData,
	ClassifyStatuseTableDataState,
} from './type';

import { getUserList } from '/@/api/system/user/index';
import { UserItem, VersionMap } from '/@/types';
import { parseTime } from '/@/utils/gfast';
import { cloneDeep } from 'lodash';

import { QueryFormField, TableColumn, PopupFormField } from '/@/components/dynamicpage/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';

defineOptions({ name: 'ClassifyStatuse' });
const loading = ref(false);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
const userOptions = ref<UserItem[]>([]);

const state = reactive<ClassifyStatuseTableDataState>({
	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: 'jie' },
	{ label: 'Kingdom', prop: 'kingdom' },
	{ label: '门', prop: 'men' },
	{ label: 'Phylum', prop: 'phylum' },
	{ label: '纲', prop: 'gang' },
	{ label: 'Class', prop: 'classTitle' },
	{ label: '目', prop: 'mu' },
	{ label: 'Order', prop: 'orderTitle' },
	{ label: '科', prop: 'ke' },
	{ label: 'Family', prop: 'family' },
	{ label: '属', prop: 'shu' },
	{ label: 'Genus', prop: 'genus' },
	{ label: '种', prop: 'zhong' },
	{ label: 'Species', prop: 'species' },
	{ label: '其他分类信息', prop: 'otherInfo', minWidth: 120 },
	{ label: '数据来源', prop: 'sourcesData' },
	{
		label: '数据采集人',
		prop: 'createUser',
		isFormater: true,
		minWidth: 120,
		formater(row, column, cellValue, index) {
			const user = userOptions.value.find((i) => i.id === cellValue);
			return user ? user.userNickname : '';
		},
	},
	{
		label: '数据采集日期',
		prop: 'createDate',
		isFormater: true,
		minWidth: 120,
		formater(_: ClassifyStatuseTableColumns, col: any, val: string) {
			return parseTime(val, '{y}-{m}-{d}');
		},
	},
	{
		label: '数据核查人',
		prop: 'auditUser',
		isFormater: true,
		minWidth: 120,
		formater(row, column, cellValue, index) {
			const user = userOptions.value.find((i) => i.id === cellValue);
			return user ? user.userNickname : '';
		},
	},
	{
		label: '数据核查日期',
		prop: 'auditDate',
		minWidth: 120,
		isFormater: true,
		formater(_: ClassifyStatuseTableColumns, 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 ? '通过' : '不通过';
		},
	},
	{ label: '备注', prop: 'remark' },
];

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 };
	getList();
};
const onReset = () => {
	state.tableData.param = {
		pageNum: 1,
		pageSize: 10,
	};
	getList();
};
const searchForm = ref<Partial<ClassifyStatuseInfoData>>({
	speciesCode: undefined,
	jie: undefined,
	kingdom: undefined,
	men: undefined,
	phylum: undefined,
	gang: undefined,
	classTitle: undefined,
	mu: undefined,
	orderTitle: undefined,
	ke: undefined,
	family: undefined,
	shu: undefined,
	genus: undefined,
	zhong: undefined,
	species: undefined,
	otherInfo: undefined,
	sourcesData: undefined,
});
const searchFields = computed<QueryFormField[]>(() => [
	{ label: '物种编码', prop: 'speciesCode', type: 'input', placeholder: '请输入物种编码' },
	{ label: '界', prop: 'jie', type: 'input', placeholder: '请输入界' },
	{ label: 'kingdom', prop: 'kingdom', type: 'input', placeholder: '请输入kingdom' },
	{ label: '门', prop: 'men', type: 'input', placeholder: '请输入门' },
	{ label: 'Phylum', prop: 'phylum', type: 'input', placeholder: '请输入Phylum' },
	{ label: '纲', prop: 'gang', type: 'input', placeholder: '请输入纲' },
	{ label: 'Class', prop: 'classTitle', type: 'input', placeholder: '请输入Class' },
	{ label: '目', prop: 'mu', type: 'input', placeholder: '请输入目' },
	{ label: 'Order', prop: 'orderTitle', type: 'input', placeholder: '请输入Order' },
	{ label: '科', prop: 'ke', type: 'input', placeholder: '请输入科' },
	{ label: 'Family', prop: 'family', type: 'input', placeholder: '请输入Family' },
	{ label: '属', prop: 'shu', type: 'input', placeholder: '请输入属' },
	{ label: 'Genus', prop: 'genus', type: 'input', placeholder: '请输入Genus' },
	{ label: '种', prop: 'zhong', type: 'input', placeholder: '请输入种' },
	{ label: 'Species', prop: 'species', type: 'input', placeholder: '请输入Species' },
]);

// 页面加载时
onMounted(() => {
	initTableData();
});
// 初始化表格数据
const initTableData = () => {
	getList();
	reqGetUserList();
};
// 获取列表数据
const getList = async () => {
	loading.value = true;
	const res = await listClassifyStatuse(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<ClassifyStatuseInfoData>) => {
	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: 'jie',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入界', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入界',
		},
	},
	{
		label: 'kingdom',
		prop: 'kingdom',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入kingdom', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入界',
		  
		}
	},
	{
		label: '门',
		prop: 'men',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入门', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入门',
		},
	},
	{
		label: 'Phylum',
		prop: 'phylum',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入Phylum', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入Phylum',
		},
	},
	{
		label: '纲',
		prop: 'gang',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入纲', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入纲',
		},
	},
	{
		label: 'Class',
		prop: 'classTitle',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入Class', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入Class',
		},
	},
	{
		label: '目',
		prop: 'mu',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入目', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入目',
	}
	},
	{
		label: 'Order',
		prop: 'orderTitle',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入Order', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入Order',
		},
	},
	{
		label: '科',
		prop: 'ke',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入科', trigger: 'blur' }],
		componentProps: {
		  placeholder: '请输入科',
		}
	},
	{
		label: 'Family',
		prop: 'family',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入Family', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入Family',
		},
	},
	{
		label: '属',
		prop: 'shu',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入属', trigger: 'blur' }],
		componentProps: {
	  placeholder: '请输入属',
	}
},
	{
		label: 'Genus',
		prop: 'genus',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入Genus', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入Genus',
		},
	},
	{
		label: '种',
		prop: 'zhong',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入种', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入种',
		},
	},
	{
		label: 'Species',
		prop: 'species',
		type: 'input',
		span: 12,
		rules: [{ required: true, message: '请输入Species', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入Species',
		},
	},
	{
		label: '数据来源',
		prop: 'sourcesData',
		span: 12,
		type: 'input',
		rules: [{ required: true, message: '请输入数据来源', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入数据来源',
		},
	},
	{
		label: '其他分类信息',
		prop: 'otherInfo',
		span: 24,
		type: 'input',
		rules: [{ required: true, message: '请输入其他分类信息', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入其他信息',
			type: 'textarea',
		},
	},
	
	{
		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: '备注',
		prop: 'remark',
		span: 24,
		type: 'input',
		componentProps: {
			placeholder: '请输入备注',
			type: 'textarea',
		},
	},
]);
const formData = ref<ClassifyStatuseInfoData>({
	speciesCode: undefined,
	jie: undefined,
	kingdom: undefined,
	men: undefined,
	phylum: undefined,
	gang: undefined,
	classTitle: undefined,
	mu: undefined,
	orderTitle: undefined,
	ke: undefined,
	family: undefined,
	shu: undefined,
	genus: undefined,
	id: undefined,
	zhong: undefined,
	species: undefined,
	otherInfo: undefined,
	sourcesData: undefined,
	createUser: undefined,
	createDate: undefined,
	remark: undefined,
	auditStatus: undefined,
	auditUser: undefined,
	auditDate: undefined,
	version: undefined,
	auditView: undefined,
});
const formType = ref<'add' | 'edit'>('add');

const handleFormSubmit = (form: ClassifyStatuseInfoData) => {
	if (formType.value === 'add') {
		addClassifyStatuse(form)
			.then(() => {
				ElMessage.success('新增成功');
				handleCancel();
				getList();
			})
			.catch(() => {
				ElMessage.error('新增失败');
				handleCancel();
				getList();
			});
	} else {
		form.auditStatus = 0;
		updateClassifyStatuse(form)
			.then(() => {
				ElMessage.success('编辑成功');
				handleCancel();
				getList();
			})
			.catch(() => {
				ElMessage.error('编辑失败');
				handleCancel();
				getList();
			});
	}
};
const handleCancel = () => {
	showDialog.value = false;
	formTitle.value = '';
	formType.value = 'add';
	formData.value = {
		speciesCode: undefined,
		jie: undefined,
		kingdom: undefined,
		men: undefined,
		phylum: undefined,
		gang: undefined,
		classTitle: undefined,
		mu: undefined,
		orderTitle: undefined,
		ke: undefined,
		family: undefined,
		shu: undefined,
		genus: undefined,
		zhong: undefined,
		species: undefined,
		otherInfo: undefined,
		sourcesData: undefined,
		id: undefined,
		createUser: undefined,
		createDate: undefined,
		remark: undefined,
		auditStatus: undefined,
		auditUser: undefined,
		auditDate: undefined,
		version: undefined,
		auditView: undefined,
	};
};

const handleAdd = () => {
	showDialog.value = true;
	formTitle.value = '新增分类地位';
	formType.value = 'add';
};
const handleUpdate = (row: ClassifyStatuseInfoData) => {
	showDialog.value = true;
	formTitle.value = '编辑分类地位';
	formType.value = 'edit';
	formData.value = cloneDeep(row);
};
const handleDelete = (row: ClassifyStatuseTableColumns | 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(() => {
			delClassifyStatuse(
				id,
				id.map((i) => versionMap.value[i])
			).then(() => {
				ElMessage.success('删除成功');
				getList();
			});
		})
		.catch(() => {});
};

const auditFormRef = ref();
const showAuditDialog = ref(false);
const handleAudit = (row: ClassifyStatuseTableColumns) => {
	auditFormRef.value.open(cloneDeep(row), userOptions.value);
};
const onAuditSubmit = (val: ClassifyStatuseTableColumns) => {
	auditSpeciesName(val)
		.then(() => {
			ElMessage.success('审核成功');
			showAuditDialog.value = false;
			getList();
		})
		.catch(() => {
			ElMessage.error('审核失败');
			showAuditDialog.value = false;
			getList();
		});
};
</script>
<style lang="scss" scoped>
.colBlock {
	display: block;
}
.colNone {
	display: none;
}
.ml-2 {
	margin: 3px;
}
</style>
