import { cloneDeep } from 'lodash-es'
import { hasPerm } from '@/utils/permission'
import { useRouter } from 'vue-router'
import useTabs from '@/utils/useTabs'

/**
 * 列表页面表格信息 hook 封装（数据操作）
 * @param apiModule 调用接口
 * @param tableColumns 表格头部信息
 * @returns {{searchFormRef: Ref<UnwrapRef<{}>>, toolConfig: {columnSetting: boolean, striped: boolean, refresh: boolean, height: boolean}, searchFormState: Ref<UnwrapRef<{}>>, tableRef: Ref<UnwrapRef<null>>, selectedRowKeys: Ref<UnwrapRef<*[]>>, columns: Ref<UnwrapRef<unknown>>, options: {rowSelection: {onChange: options.rowSelection.onChange}, alert: {show: boolean, clear: options.alert.clear}}, reset: reset, loadData: (function(*): *), deleteBatchRecords: deleteBatchRecords, deleteRecord: deleteRecord}}
 */
export function useTableManagement(apiModule = {}, tableColumns, hasPermData) {
	const searchFormState = ref({})
	const searchFormRef = ref(null)
	const tableRef = ref(null)
	const selectedRowKeys = ref([])
	const router = useRouter()
	let advanced = ref(false)

	// 动态列配置
	const columns = ref(tableColumns)

	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }

	// 根据权限添加操作列
	if (hasPerm(hasPermData)) {
		// 判断columns 是否有操作
		const columnsFilter = columns.value.filter((item) => item.dataIndex === 'action')
		if (columnsFilter.length === 0)
			columns.value.push({
				title: '操作',
				dataIndex: 'action',
				align: 'center',
				width: 200,
				fixed: 'right',
				max_width: 100
			})
	}

	// 加载数据
	const loadData = (parameter) => {
		const searchFormParam = cloneDeep(searchFormState.value)
		return apiModule.page(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}

	// 重置
	const reset = () => {
		if (tableRef.value) {
			searchFormRef.value.resetFields()
			tableRef.value.refresh(true)
		}
	}

	// 删除
	const deleteRecord = (record) => {
		let params = [{ id: record.id }]
		return apiModule.delete(params).then(() => {
			if (tableRef.value) {
				tableRef.value.refresh(true)
			}
		})
	}

	// 批量删除
	const deleteBatchRecords = (params) => {
		apiModule.delete(params).then(() => {
			if (tableRef.value) {
				tableRef.value.clearRefreshSelected()
			}
		})
	}

	// 选择配置
	const options = {
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = []
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	// 页面跳转
	const navigateTo = (to, params) => {
		router.push({
			path: to,
			query: params
		})
	}

	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}

	// 返回Hook的值
	return {
		searchFormState,
		searchFormRef,
		tableRef,
		selectedRowKeys,
		columns,
		loadData,
		reset,
		deleteRecord,
		deleteBatchRecords,
		options,
		toolConfig,
		navigateTo,
		toggleAdvanced,
		advanced
	}
}
