<template>
    <DialogPro v-model="open" :title="$t('ssl.selfSigned')" @close="handleClose">
        <el-row v-loading="loading">
            <el-col :span="22" :offset="1">
                <el-form @submit.prevent ref="obtainForm" label-position="top" :model="obtain" :rules="rules">
                    <el-form-item :label="$t('website.domain')" prop="domains">
                        <el-input
                            type="textarea"
                            :rows="4"
                            v-model="obtain.domains"
                            :placeholder="$t('ssl.domainHelper')"
                        ></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('website.remark')" prop="description">
                        <el-input v-model="obtain.description"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('website.keyType')" prop="keyType">
                        <el-select v-model="obtain.keyType">
                            <el-option
                                v-for="(keyType, index) in KeyTypes"
                                :key="index"
                                :label="keyType.label"
                                :value="keyType.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('ssl.days')" prop="time">
                        <el-input type="number" v-model.number="obtain.time">
                            <template #append>
                                <el-select v-model="obtain.unit" style="width: 100px">
                                    <el-option :label="$t('commons.units.day')" value="day"></el-option>
                                    <el-option :label="$t('commons.units.year')" value="year"></el-option>
                                </el-select>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item :label="''" prop="autoRenew">
                        <el-checkbox v-model="obtain.autoRenew" :label="$t('ssl.autoRenew')" />
                    </el-form-item>
                    <el-form-item :label="''" prop="pushDir">
                        <el-checkbox v-model="obtain.pushDir" :label="$t('ssl.pushDir')" />
                    </el-form-item>
                    <el-form-item :label="$t('ssl.dir')" prop="dir" v-if="obtain.pushDir">
                        <el-input v-model.trim="obtain.dir">
                            <template #prepend>
                                <el-button
                                    icon="Folder"
                                    @click="fileRef.acceptParams({ path: obtain.dir, dir: true })"
                                />
                            </template>
                        </el-input>
                        <span class="input-help">
                            {{ $t('ssl.pushDirHelper') }}
                        </span>
                    </el-form-item>
                    <el-form-item :label="''" prop="execShell">
                        <el-checkbox v-model="obtain.execShell" :label="$t('ssl.execShell')" />
                    </el-form-item>
                    <el-form-item :label="$t('ssl.shell')" prop="shell" v-if="obtain.execShell">
                        <el-input type="textarea" :rows="4" v-model="obtain.shell" />
                        <span class="input-help">
                            {{ $t('ssl.shellHelper') }}
                        </span>
                    </el-form-item>
                    <PushToNode
                        v-if="isMaster && isXpackOrEE"
                        :push-node="obtain.pushNode"
                        :nodes="obtain.pushNodes"
                        type="ssl"
                        @update:push-node="obtain.pushNode = $event"
                        @update:nodes="obtain.pushNodes = $event"
                    />
                </el-form>
            </el-col>
        </el-row>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose" :disabled="loading">{{ $t('commons.button.cancel') }}</el-button>
                <el-button v-permission type="primary" @click="submit(obtainForm)" :disabled="loading">
                    {{ $t('commons.button.confirm') }}
                </el-button>
            </span>
        </template>
    </DialogPro>
    <FileList ref="fileRef" @choose="getPath" />
</template>

<script lang="ts" setup>
import { obtainSSLByCA } from '@/api/modules/website';
import { Rules, checkNumberRange, checkMaxLength } from '@/global/form-rules';
import i18n from '@/lang';
import FileList from '@/components/file-list/index.vue';
import { MsgSuccess } from '@/utils/message';
import { FormInstance } from 'element-plus';
import { defineAsyncComponent, ref } from 'vue';
import { KeyTypes } from '@/global/mimetype';
import { useGlobalStore } from '@/composables/useGlobalStore';

const { isMaster, isXpackOrEE } = useGlobalStore();

const PushToNode = defineAsyncComponent(async () => {
    const modules = import.meta.glob('@/xpack/views/ssl/index.vue');
    const loader = modules['/src/xpack/views/ssl/index.vue'];
    if (loader) {
        return ((await loader()) as any).default;
    }
    return { template: '<div></div>' };
});

const open = ref(false);
const fileRef = ref();
const loading = ref(false);
const obtainForm = ref<FormInstance>();
const em = defineEmits(['close']);

const rules = ref({
    keyType: [Rules.requiredSelect],
    domains: [Rules.requiredInput],
    dir: [Rules.requiredInput],
    time: [Rules.integerNumber, checkNumberRange(1, 10000)],
    shell: [Rules.requiredInput],
    description: [checkMaxLength(128)],
    pushNodes: [Rules.requiredSelect],
});

const initData = () => ({
    keyType: 'EC256',
    domains: '',
    id: 0,
    time: 10,
    unit: 'year',
    pushDir: false,
    dir: '',
    autoRenew: true,
    description: '',
    execShell: false,
    shell: '',
    pushNode: false,
    pushNodes: [] as string[],
    nodes: '',
});
const obtain = ref(initData());

const acceptParams = (id: number) => {
    open.value = true;
    obtain.value.id = id;
};

const handleClose = () => {
    open.value = false;
    em('close', false);
    resetForm();
};

const resetForm = () => {
    obtainForm.value?.resetFields();
    obtain.value = initData();
};

const getPath = (dir: string) => {
    obtain.value.dir = dir;
};

const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (!valid) {
            return;
        }
        loading.value = true;
        obtain.value.nodes = obtain.value.pushNode ? obtain.value.pushNodes.join(',') : '';

        obtainSSLByCA(obtain.value)
            .then(() => {
                MsgSuccess(i18n.global.t('commons.msg.createSuccess'));
                handleClose();
            })
            .finally(() => {
                loading.value = false;
            });
    });
};

defineExpose({
    acceptParams,
});
</script>
