import { useAppStoreWithOut } from '@/store/modules/app';
import { TableColumn } from '../types';
import { queryTableColumnsApi, updateTableColumnsApi, delTableColumnsApi } from '@/api/common'
import { isEqual, find } from 'lodash-es';
import { getLoginNameByUserInfo } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import { isNotEmpty } from '@/utils/is';

const appStore = useAppStoreWithOut();

/**
 * 更新表格列操作保存
 */
export const updateTableColumns = async (tableId: number | undefined, oldColumns?: TableColumn[], newColumns: TableColumn[] = []): Promise<any> => {
    // 表格列操作保存 & tableId 允许保存
    if (appStore.getServerTableColumns && isNotEmpty(tableId)) {
        const loginId = getLoginNameByUserInfo();
        const oldColumns1 = oldColumns?.map(item => {
            return {
                field: item.field,
                hidden: !!item.hidden,
                fixed: item.fixed
            }
        });
        const newColumns1 = newColumns.map(item => {
            return {
                field: item.field,
                hidden: !!item.hidden,
                fixed: item.fixed
            }
        });
        // 比较数据是否相同
        const isChange = !isEqual(oldColumns1, newColumns1);
        // 数据存在修改, 执行更新接口
        if (isChange) {
            updateTableColumnsApi({
                userId: loginId,
                tableId: tableId?.toString(),
                tableColumns: JSON.stringify(newColumns1)
            }).then((res) => {
                if (res?.head?.code === '0') {
                    ElMessage.success('更新表格列成功！');
                }
            })
        }
        // 数据完全一致的情况下, 执行清空接口
        if (!isChange) {
            delTableColumnsApi({
                userId: loginId,
                tableId: tableId?.toString()
            }).then((res) => {
                if (res?.head?.code === '0') {
                    ElMessage.success('重置表格列成功！');
                }
            })
        }

    }
}

export const getTableColumns = async (tableId: number | undefined, initColumns: TableColumn[], isReStore = false): Promise<TableColumn[] | void> => {
    // 表格列操作保存 & tableId 允许查询
    if (appStore.getServerTableColumns && isNotEmpty(tableId)) {
        const loginId = getLoginNameByUserInfo();
        const res = await queryTableColumnsApi({
            userId: loginId,
            tableId: tableId?.toString()
        });
        if (res?.head?.code === '0') {
            const tableColumns = res?.body?.result?.tableColumns ? JSON.parse(res?.body?.result?.tableColumns) : [];
            if (isNotEmpty(tableColumns)) {
                const columnsList = tableColumns.map(item => {
                    const initCol = find(initColumns, { field: item.field });
                    return {
                        ...initCol,
                        hidden: item.hidden,
                        fixed: item.fixed
                    }
                });
                return columnsList;
            }
        }
    }
}