<template>
	<div class="businesses-foreignDistribution-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/foreignDistribution/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/foreignDistribution/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/foreignDistribution/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/foreignDistribution/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/foreignDistribution/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 {
	listForeignDistribution,
	delForeignDistribution,
	addForeignDistribution,
	updateForeignDistribution,
	auditForeignDistribution,
} from './api';
import {
	ForeignDistributionTableColumns,
	ForeignDistributionInfoData,
	ForeignDistributionTableDataState,
} from './type';

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

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';
import { SpeciesNameInfoData } from '../speciesName/type';
defineOptions({ name: 'BusinessesForeignDistributionList' });

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

const state = reactive<ForeignDistributionTableDataState>({
	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: 'continent', minWidth: 150 },
	{ label: '所属国家/地区', prop: 'region', minWidth: 150 },
	{ label: '所属州', prop: 'belongState', minWidth: 150 },
	{ label: '发现/报道年份', prop: 'year', minWidth: 150 },
	{ label: '参考文献', prop: 'references', minWidth: 150 },
	{
		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(_, 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(_, 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: 'auditView' },
	{ label: '备注', prop: 'remark' },
];

const onSearch = async (val: Record<string, any>) => {
	let newVal: Record<string, any> = {};
	for (const v in val) {
		if (val[v] || val[v] === 0) {
			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<ForeignDistributionInfoData>>({
	speciesCode: undefined,
	continent: undefined,
	region: undefined,
	belongState: undefined,
	year: undefined,
	references: undefined,
	createUser: undefined,
	auditStatus: undefined,
});
const searchFields = computed<QueryFormField[]>(() => [
	{ label: '物种编码', prop: 'speciesCode', type: 'input', placeholder: '请输入物种编码' },
	{ label: '所属大洲', prop: 'continent', type: 'input', placeholder: '请输入所属大洲' },
	{ label: '所属国家/地区', prop: 'region', type: 'input', placeholder: '请输入所属国家/地区' },
	{ label: '所属州', prop: 'belongState', type: 'input', placeholder: '请输入所属州' },
	{ label: '发现/报道年份', prop: 'year', type: 'input', placeholder: '请输入发现/报道年份' },
	{ label: '参考文献', prop: 'references', type: 'input', placeholder: '请输入参考文献' },

	{
		label: '核查状态',
		prop: 'auditStatus',
		type: 'select',
		options: [
			{ label: '待审核', value: 0 },
			{ label: '通过', value: 1 },
			{ label: '不通过', value: 2 },
		],
		placeholder: '请输入物种编码',
	},
	{
		label: '数据采集人',
		prop: 'createUser',
		type: 'select',
		options: userOptions.value.map((i) => {
			return {
				label: i.userNickname,
				value: i.id,
			};
		}),
		placeholder: '请选择数据采集人',
	},
]);

// 页面加载时
onMounted(() => {
	initTableData();
});
// 初始化表格数据
const initTableData = () => {
	getList();
	reqGetUserList();
	reqListSpeciesName();
};
// 获取列表数据
const getList = async () => {
	loading.value = true;
	const res = await listForeignDistribution(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 specieslist = ref<SpeciesNameInfoData[]>([]);
/**获取物种列表 */
const reqListSpeciesName = async () => {
	if (userOptions.value.length > 0) return;
	const res = await listSpeciesName({ pageSize: 9999, pageNum: 1 });
	specieslist.value = res.data.list;
};

/**获取用户列表 */

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<ForeignDistributionInfoData>) => {
	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: 'select',
		options: specieslist.value.map((i) => {
			return {
				value: i.speciesCode,
				label: i.speciesCode,
			};
		}),
		span: 24,
		rules: [{ required: true, message: '请输入物种编码', trigger: 'blur' }],
		componentProps: {
			placeholder: '请选择物种编码',
		},
	},
	{
		label: '所属大洲',
		prop: 'continent',
		rules: [{ required: true, message: '请输入所属大洲', trigger: 'blur' }],
		type: 'input',
		span: 24,
		componentProps: {
			placeholder: '请输入所属大洲',
		},
	},
	{
		label: '所属国家/地区',
		prop: 'region',
		type: 'input',
		span: 24,
		rules: [{ required: true, message: '请输入所属国家/地区', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入所属国家/地区',
		},
	},
	{
		label: '所属州',
		prop: 'belongState',
		type: 'input',
		span: 24,
		rules: [{ required: true, message: '请输入所属州', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入所属州',
		},
	},
	{
		label: '发现/报道年份',
		prop: 'year',
		type: 'input',
		span: 24,
		rules: [{ required: true, message: '请输入发现/报道年份', trigger: 'blur' }],
		componentProps: {
			placeholder: '请输入发现/报道年份',
		},
	},
	{
		label: '参考文献',
		prop: 'references',
		type: 'input',
		span: 24,
		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: '备注',
		prop: 'remark',
		span: 24,
		type: 'input',
		componentProps: {
			placeholder: '请输入备注',
			type: 'textarea',
		},
	},
]);
const formData = ref<Partial<ForeignDistributionInfoData>>({
	speciesCode: undefined,
	continent: undefined,
	region: undefined,
	belongState: undefined,
	year: undefined,
	references: undefined,
	createUser: undefined,
	createDate: undefined,
	remark: undefined,
});
const formType = ref<'add' | 'edit'>('add');

const handleFormSubmit = (form: ForeignDistributionInfoData) => {
	if (formType.value === 'add') {
		addForeignDistribution(form).then(() => {
			ElMessage.success('新增成功');
			handleCancel();
			getList();
		});
	} else {
		form.auditStatus = 0;
		updateForeignDistribution(form).then(() => {
			ElMessage.success('编辑成功');
			handleCancel();
			getList();
		});
	}
};
const handleCancel = () => {
	showDialog.value = false;
	formTitle.value = '';
	formType.value = 'add';
	formData.value = {
		speciesCode: undefined,
	};
};

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

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