<template>
    <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
        <BasicTable @register="registerTable" ref="tableRef" @row-dbClick="dbClickRow">
            <template #toolbar>
                <template v-for="button in tableButtonConfig" :key="button.code">
                    <a-button v-if="button.isDefault" :type="button.type" @click="buttonClick(button.code)">
                        <template #icon>
                            <Icon :icon="button.icon" />
                        </template>
                        {{ button.name }}
                    </a-button>
                    <a-button v-else :type="button.type">
                        <template #icon>
                            <Icon :icon="button.icon" />
                        </template>
                        {{ button.name }}
                    </a-button>
                </template>
            </template>
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                    <TableAction :actions="getActions(record)" />
                </template>
            </template>
        </BasicTable>
        <FormChangeLogModal @register="registerModal" @success="handleSuccess" />
    </PageWrapper>
    <a-modal v-model:visible="visibleFlowRecordModal" style="width: 1200px;height: 500px;" :maskClosable="false"
        @cancel="handleClose" @ok="handleClose" :title="t('变更明细')">
        <div style=" height: 500px;overflow: auto; padding: 0px 15px">
            <ChangeRowDetailModal :rowId="currentRowId" :currentUserName="currentUserName"
                :currentCreateTime="currentCreateTime" :formInfos="props.formInfos[0]['formConfig']['children']"
                :isShow="visibleFlowRecordModal">
            </ChangeRowDetailModal>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
import {
    ref, computed, onMounted, onUnmounted, createVNode,
    inject,

} from 'vue';

import { Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
import { getFormChangeRecordPage, deleteFormChangeRecord, getRecordList } from '/@/api/formChange/formChangeLog';
import { PageWrapper } from '/@/components/Page';
import { useMessage } from '/@/hooks/web/useMessage';
import { useI18n } from '/@/hooks/web/useI18n';
import { usePermission } from '/@/hooks/web/usePermission';
import { useRouter } from 'vue-router';
import { getFormChangeRecord } from '/@/api/formChange/formChangeLog';
import { useModal } from '/@/components/Modal';
import FormChangeLogModal from './components/FormChangeLogModal.vue';
import { BasicModal } from '/@/components/Modal';
import { searchFormSchema, columns } from './components/config';
import Icon from '/@/components/Icon/index';
import useEventBus from '/@/hooks/event/useEventBus';
import ChangeRowDetailModal from '../changeLogDetail/components/ChangeRowDetailModal.vue';

const { bus, CREATE_FLOW, FLOW_PROCESSED, FORM_LIST_MODIFIED } = useEventBus();

const { notification } = useMessage();
const { t } = useI18n();
defineEmits(['register']);
const { filterColumnAuth, filterButtonAuth } = usePermission();

// const filterColumns = filterColumnAuth(columns);
const filterColumns = columns;
const tableRef = ref();
const visibleFlowRecordModal = ref(false);
const currentRowId = ref(0);
const currentUserName = ref('');
const currentCreateTime = ref('');
const props = withDefaults(
    defineProps<{
        formDataId: number
        formInfos: any
    }>(),
    {
        formDataId: 0
    },
);

//展示在列表内的按钮
const actionButtons = ref<string[]>(['view', 'edit', 'copyData', 'delete', 'startwork', 'flowRecord']);
const buttonConfigs = computed(() => {
    // const list = [{ "isUse": true, "name": "新增", "code": "add", "icon": "ant-design:plus-outlined", "isDefault": true, "type": "primary" }, {
    //     "isUse": true,
    //     "name": "编辑",
    //     "code": "edit",
    //     "icon": "ant-design:form-outlined",
    //     "isDefault": true
    // }, { "isUse": true, "name": "刷新", "code": "refresh", "icon": "ant-design:reload-outlined", "isDefault": true }, { "isUse": true, "name": "查看", "code": "view", "icon": "ant-design:eye-outlined", "isDefault": true }, {
    //     "isUse": true,
    //     "name": "删除",
    //     "code": "delete",
    //     "icon": "ant-design:delete-outlined",
    //     "isDefault": true
    // }]
    const list = []
    return filterButtonAuth(list);
})

const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
});

const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
});

const btnEvent = { add: handleAdd, edit: handleEdit, refresh: handleRefresh, view: handleView, delete: handleDelete, }

const { currentRoute } = useRouter();
const router = useRouter();


const formIdComputedRef = ref();
formIdComputedRef.value = currentRoute.value.meta.formId
const schemaIdComputedRef = ref();
schemaIdComputedRef.value = currentRoute.value.meta.schemaId


const [registerModal, { openModal }] = useModal();


const formName = '表单更新记录';
const [registerTable, { reload, }] = useTable({
    title: '' || (formName + '列表'),
    api: getFormChangeRecordPage,
    // api: getRecordList,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
        rowProps: {
            gutter: 16,
        },
        schemas: searchFormSchema,
        fieldMapToTime: [],
        showResetButton: false,
    },
    beforeFetch: (params) => {
        return { ...params, FormId: formIdComputedRef.value, formDataId: props.formDataId };
    },
    afterFetch: (res) => {
        tableRef.value.setToolBarWidth();

    },
    useSearchForm: true,
    showTableSetting: true,

    striped: false,
    tableSetting: {
        size: false,
        setting: false,
    },

});

function handleClose() {
    visibleFlowRecordModal.value = false;
}

function dbClickRow(record) {
    // console.log(1111111111, record);
    // const { processId, taskIds, schemaId } = record.workflowData || {};
    // if (taskIds && taskIds.length) {
    //     router.push({
    //         path: '/flow/' + schemaId + '/' + (processId || '') + '/approveFlow',
    //         query: {
    //             taskId: taskIds[0],
    //             formName: formName
    //         }
    //     });
    // } else if (schemaId && !taskIds && processId) {
    //     router.push({
    //         path: '/flow/' + schemaId + '/' + processId + '/approveFlow',
    //         query: {
    //             readonly: 1,
    //             taskId: '',
    //             formName: formName
    //         }
    //     });
    // } else {
    //     router.push({
    //         path: '/form/formChangeLog/' + record.id + '/viewForm',
    //         query: {
    //             formPath: 'formChange/formChangeLog',
    //             formName: formName
    //         }
    //     });
    // }
    currentRowId.value = record.id;
    currentUserName.value = record.createUserName;
    currentCreateTime.value = record.createDate;
    visibleFlowRecordModal.value = true;

}

function buttonClick(code) {

    btnEvent[code]();
}

function handleAdd() {
    if (schemaIdComputedRef.value) {
        router.push({
            path: '/flow/' + schemaIdComputedRef.value + '/0/createFlow'
        });
    } else {
        router.push({
            path: '/form/formChangeLog/0/createForm',
            query: {
                formPath: 'formChange/formChangeLog',
                formName: formName
            }
        });
    }
}

function handleEdit(record: Recordable) {

    router.push({
        path: '/form/formChangeLog/' + record.id + '/updateForm',
        query: {
            formPath: 'formChange/formChangeLog',
            formName: formName
        }
    });
}


function handleDelete(record: Recordable) {
    deleteList([record.id]);
}

function deleteList(ids) {
    Modal.confirm({
        title: '提示信息',
        icon: createVNode(ExclamationCircleOutlined),
        content: '是否确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
            deleteFormChangeRecord(ids).then((_) => {
                handleSuccess();
                notification.success({
                    message: 'Tip',
                    description: t('删除成功！'),
                });
            });
        },
        onCancel() {
        },
    });
}


function handleRefresh() {
    reload();
}

function handleSuccess() {

    reload();
}

function handleView(record: Recordable) {

    dbClickRow(record);

}


onMounted(() => {

    if (schemaIdComputedRef.value) {
        bus.on(FLOW_PROCESSED, handleRefresh);
        bus.on(CREATE_FLOW, handleRefresh);
    } else {
        bus.on(FORM_LIST_MODIFIED, handleRefresh);
    }
});
onUnmounted(() => {
    if (schemaIdComputedRef.value) {
        bus.off(FLOW_PROCESSED, handleRefresh);
        bus.off(CREATE_FLOW, handleRefresh);
    } else {
        bus.off(FORM_LIST_MODIFIED, handleRefresh);
    }
});

function getActions(record: Recordable): ActionItem[] {

    const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
        if (!record.workflowData?.processId) {
            return {
                icon: button?.icon,
                tooltip: button?.name,
                color: button.code === 'delete' ? 'error' : undefined,
                onClick: btnEvent[button.code].bind(null, record),
            };
        } else {
            if (button.code === 'view') {
                return {
                    icon: button?.icon,
                    tooltip: button?.name,
                    onClick: btnEvent[button.code].bind(null, record),
                };
            } else {
                return {};
            }
        }
    });
    return actionsList;
}

</script>
<style lang="less" scoped>
:deep(.ant-table-selection-col) {
    width: 50px;
}

.show {
    display: flex;
}

.hide {
    display: none !important;
}
</style>
