<template>
    <BasicTable @register="registerTable" @row-dbClick="onRowDblClick" @selection-change="selectionChange">
        <template #toolbar>
            <BatchApprovalProcess v-if="showBatchApproval" :selectedRows="data.selectedRows" @close="BatchClearHandler">
                <a-button v-auth="'processtasks:batchApproval'">{{ t('批量审批') }}</a-button>
            </BatchApprovalProcess>
            <ApprovalProcess v-else :processId="processId" :schemaId="schemaId" :taskId="taskId" :visible="false" @close="clearHandler">
                <a-button v-auth="'processtasks:approve'">{{ t('审批') }}</a-button>
            </ApprovalProcess>
            <LookProcess :processId="processId" :taskId="taskId" @close="clearHandler">
                <a-button v-auth="'processtasks:view'">{{ t('查看') }}</a-button>
            </LookProcess>
        </template>

        <template #currentProgress="{ record }">
            <a-progress v-if="record.currentProgress" :percent="record.currentProgress" size="small" />
        </template>
    </BasicTable>
    <InfoModal @register="registerModal" @success="reload" />
</template>

<script lang="ts" setup>
    import userTaskTable from './../../hooks/userTaskTable';
    import { useModal } from '/@/components/Modal';
    import LookProcess from './../LookProcess.vue';
    import ApprovalProcess from './../ApprovalProcess.vue';
    import BatchApprovalProcess from './../BatchApprovalProcess.vue';
    import InfoModal from '../BatchApprovalInfo.vue';
    import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
    import { getSchemaTask } from '/@/api/workflow/process';
    import { TaskTypeUrl } from '/@/enums/workflowEnum';
    import { useI18n } from '/@/hooks/web/useI18n';
    import { unref, watch, onMounted, onUnmounted ,h} from 'vue';
    import { useRouter } from 'vue-router';
    import useEventBus from '/@/hooks/event/useEventBus';
    import { getAppEnvConfig } from '/@/utils/env';
    import { storeToRefs } from 'pinia';
    import { useUserStore } from '/@/store/modules/user';
    import {useMessage} from "/@/hooks/web/useMessage";
    import {useTenantManager} from "/@/utils/tenantManager";

    const router = useRouter();
    const { currentRoute } = router;
    const { t } = useI18n();
    const userStore = useUserStore();
    const { userInfo } = storeToRefs(userStore);


    const configColumns: BasicColumn[] = [
        {
            title: t('流水号'),
            dataIndex: 'serialNumber',
            width: 80,
            align: 'left'
        },
        {
            title: t('流程名称'),
            dataIndex: 'processName',
            width: '32%',
            align: 'left'
        },
        {
            title: t('任务名称'),
            dataIndex: 'taskName',
            width: '17%',
            align: 'left'
        },
        {
            title: t('当前进度'),
            dataIndex: 'currentProgress',
            width: '17%',
            align: 'left',
            slots: { customRender: 'currentProgress' }
        },
        {
            title: t('发起人'),
            dataIndex: 'startUserName',
            width: 80,
            align: 'left'
        },
        {
            title: t('发起时间'),
            width: 120,
            dataIndex: 'startTime',
            align: 'left'
        }
    ];
    const [registerModal, { openModal }] = useModal();
    const { formConfig, data, processId, taskId, schemaId, selectionChange, showBatchApproval } = userTaskTable();
    const {bus, FLOW_PROCESSED} = useEventBus();

    function BatchClearHandler(v) {
        if (v) {
            openModal(true, v);
        }
        clearSelectedRowKeys();
    }

    const clearHandler = () => {
        clearSelectedRowKeys();
        reload();
    };
    const [registerTable, { reload, clearSelectedRowKeys }] = useTable({
        title: t('待办任务列表'),
        api: getSchemaTask,
        rowKey: 'id',
        columns: configColumns,
        formConfig: formConfig(),
        beforeFetch: (params) => {
            return { data: params, taskUrl: TaskTypeUrl.PENDING_TASKS };
        },
        rowSelection: {
            type: 'checkbox'
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        pagination: {
            pageSize: 18
        },
        tableSetting: {
            size: false,
            setting: false
        }
    });

    const {toggleLocal}=useTenantManager();

    onMounted(() => {
        bus.on(FLOW_PROCESSED, onFlowProcessed);
    });

    onUnmounted(() => {
        bus.off(FLOW_PROCESSED, onFlowProcessed);
    });
    watch(
        () => unref(currentRoute),
        (val) => {
            if (val.name == 'ProcessTasks') reload();
        },
        { deep: true }
    );
    const onRowDblClick = (record, index) => {
        const {tenantId,tenantCode,tenantName} = record;
        let tenantEnabled=getAppEnvConfig().VITE_GLOB_TENANT_ENABLED;
        if(tenantEnabled =='true'&&tenantId){
            let currentTenantId=userInfo.value.tenantId;
            if(tenantId!=currentTenantId){
                const { createConfirm} = useMessage();
                createConfirm({
                    iconType: 'warning',
                    title: () => h('span', t('温馨提醒')),
                    content: () => h('div', [
                        h('span', t(`当前流程的发起租户是"${tenantName}"，需要切换到该租户才能对该流程进行审批`)),
                        h('br'),
                        h('span', t('是否确认切换租户？未保存的数据可能会丢失！'))
                    ]),
                    width:'600px',
                    onOk: async () => {
                        switchTenant(tenantCode).then(()=>{
                            openDetailPage(record,true);
                        })

                    },
                    okText: () => t('确认'),
                    cancelText: () => t('取消'),
                });

            }else{
                openDetailPage(record);
            };
        }else{
            openDetailPage(record);
        }
    };

    function openDetailPage(record,isTenantSwitch){
        const { processId, taskId, schemaId} = record;
        router.push({
            path: `/flow/${schemaId}/${processId}/approveFlow`,
            query: {
                taskId
            }
        }).then(()=> {
            if (isTenantSwitch) {
                const {notification} = useMessage();
                const {tenantName} = record;
                notification.success({
                    message: 'Tip',
                    description: t('已切换到租户“' + tenantName + '"'),
                });
            }
        });
    }

    function onFlowProcessed() {
        reload();
    }

    async function switchTenant(tenantCode: string) {
       await toggleLocal({tenantCode:tenantCode, goHome:false,tabCloseAction:"closeOther"});
    }

</script>

<style scoped></style>
