<template>
    <div>
        <RouterMenu />
        <LayoutContent :title="'Go'" v-loading="loading">
            <template #leftToolBar>
                <el-button type="primary" @click="openCreate">
                    {{ $t('runtime.create') }}
                </el-button>
            </template>
            <template #rightToolBar>
                <TableRefresh @search="search()" />
                <TableSetting title="go-runtime-refresh" @search="search()" />
            </template>
            <template #main>
                <ComplexTable :pagination-config="paginationConfig" :data="items" @search="search()" :heightDiff="260">
                    <el-table-column
                        :label="$t('commons.table.name')"
                        fix
                        prop="name"
                        min-width="120px"
                        show-overflow-tooltip
                    >
                        <template #default="{ row }">
                            <el-text type="primary" class="cursor-pointer" @click="openDetail(row)">
                                {{ row.name }}
                            </el-text>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('runtime.codeDir')" prop="codeDir" min-width="120px">
                        <template #default="{ row }">
                            <el-button type="primary" link @click="toFolder(row.codeDir)">
                                <el-icon>
                                    <FolderOpened />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('app.version')" prop="version"></el-table-column>
                    <el-table-column :label="$t('runtime.externalPort')" prop="port" min-width="110px">
                        <template #default="{ row }">
                            <PortJump :row="row" :jump="goDashboard" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('commons.table.status')" prop="status">
                        <template #default="{ row }">
                            <RuntimeStatus :row="row" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('commons.button.log')" prop="path" min-width="90px">
                        <template #default="{ row }">
                            <el-button @click="openLog(row)" link type="primary" v-if="row.status != 'Stopped'">
                                {{ $t('website.check') }}
                            </el-button>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="createdAt"
                        :label="$t('commons.table.date')"
                        :formatter="dateFormat"
                        show-overflow-tooltip
                        min-width="120"
                        fix
                    />
                    <fu-table-operations
                        :ellipsis="mobile ? 0 : 5"
                        :min-width="mobile ? 'auto' : 300"
                        :buttons="buttons"
                        fixed="right"
                        :label="$t('commons.table.operate')"
                        fix
                    />
                </ComplexTable>
            </template>
        </LayoutContent>
        <Operate ref="operateRef" @close="search" />
        <Delete ref="deleteRef" @close="search" />
        <ComposeLogs ref="composeLogRef" />
        <PortJumpDialog ref="dialogPortJumpRef" />
        <AppResources ref="checkRef" @close="search" />
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { Runtime } from '@/api/interface/runtime';
import { OperateRuntime, RuntimeDeleteCheck, SearchRuntimes, SyncRuntime } from '@/api/modules/runtime';
import { dateFormat } from '@/utils/util';
import Operate from '@/views/website/runtime/go/operate/index.vue';
import Delete from '@/views/website/runtime/delete/index.vue';
import i18n from '@/lang';
import RouterMenu from '../index.vue';
import router from '@/routers/router';
import ComposeLogs from '@/components/log/compose/index.vue';
import PortJumpDialog from '@/components/port-jump/index.vue';
import AppResources from '@/views/website/runtime/php/check/index.vue';
import { ElMessageBox } from 'element-plus';
import RuntimeStatus from '@/views/website/runtime/components/runtime-status.vue';
import PortJump from '@/views/website/runtime/components/port-jump.vue';
import { disabledButton } from '@/utils/runtime';
import { GlobalStore } from '@/store';
const globalStore = GlobalStore();
const mobile = computed(() => {
    return globalStore.isMobile();
});

const loading = ref(false);
const items = ref<Runtime.RuntimeDTO[]>([]);
const operateRef = ref();
const deleteRef = ref();
const dialogPortJumpRef = ref();
const composeLogRef = ref();
const checkRef = ref();

const paginationConfig = reactive({
    cacheSizeKey: 'runtime-page-size',
    currentPage: 1,
    pageSize: 10,
    total: 0,
});
const req = reactive<Runtime.RuntimeReq>({
    name: '',
    page: 1,
    pageSize: 40,
    type: 'go',
});
const buttons = [
    {
        label: i18n.global.t('commons.operate.stop'),
        click: function (row: Runtime.Runtime) {
            operateRuntime('down', row.id);
        },
        disabled: function (row: Runtime.Runtime) {
            return disabledButton(row, 'stop');
        },
    },
    {
        label: i18n.global.t('commons.operate.start'),
        click: function (row: Runtime.Runtime) {
            operateRuntime('up', row.id);
        },
        disabled: function (row: Runtime.Runtime) {
            return disabledButton(row, 'start');
        },
    },
    {
        label: i18n.global.t('commons.button.restart'),
        click: function (row: Runtime.Runtime) {
            operateRuntime('restart', row.id);
        },
        disabled: function (row: Runtime.Runtime) {
            return disabledButton(row, 'restart');
        },
    },
    {
        label: i18n.global.t('commons.button.edit'),
        click: function (row: Runtime.Runtime) {
            openDetail(row);
        },
        disabled: function (row: Runtime.Runtime) {
            return disabledButton(row, 'edit');
        },
    },
    {
        label: i18n.global.t('commons.button.delete'),
        click: function (row: Runtime.Runtime) {
            openDelete(row);
        },
    },
];

const search = async () => {
    req.page = paginationConfig.currentPage;
    req.pageSize = paginationConfig.pageSize;
    loading.value = true;
    try {
        const res = await SearchRuntimes(req);
        items.value = res.data.items;
        paginationConfig.total = res.data.total;
    } catch (error) {
    } finally {
        loading.value = false;
    }
};

const sync = () => {
    SyncRuntime();
};

const openCreate = () => {
    operateRef.value.acceptParams({ type: 'go', mode: 'create' });
};

const openDetail = (row: Runtime.Runtime) => {
    operateRef.value.acceptParams({ type: row.type, mode: 'edit', id: row.id });
};

const openDelete = async (row: Runtime.Runtime) => {
    RuntimeDeleteCheck(row.id).then(async (res) => {
        const items = res.data;
        if (res.data && res.data.length > 0) {
            checkRef.value.acceptParams({ items: items, key: 'website', installID: row.id });
        } else {
            deleteRef.value.acceptParams(row.id, row.name);
        }
    });
};

const openLog = (row: any) => {
    composeLogRef.value.acceptParams({ compose: row.path + '/docker-compose.yml', resource: row.name });
};

const goDashboard = async (port: any, protocol: string) => {
    dialogPortJumpRef.value.acceptParams({ port: port, protocol: protocol });
};

const operateRuntime = async (operate: string, ID: number) => {
    try {
        const action = await ElMessageBox.confirm(
            i18n.global.t('runtime.operatorHelper', [i18n.global.t('commons.operate.' + operate)]),
            i18n.global.t('commons.operate.' + operate),
            {
                confirmButtonText: i18n.global.t('commons.button.confirm'),
                cancelButtonText: i18n.global.t('commons.button.cancel'),
                type: 'info',
            },
        );
        if (action === 'confirm') {
            loading.value = true;
            await OperateRuntime({ operate: operate, ID: ID });
            search();
        }
    } catch (error) {
    } finally {
        loading.value = false;
    }
};

const toFolder = (folder: string) => {
    router.push({ path: '/hosts/files', query: { path: folder } });
};

onMounted(() => {
    sync();
    search();
});
</script>

<style lang="scss" scoped></style>
