<template>
    <Table
        ref="settingsTable"
        :tableParams="tableParams"
        :btnRole="[]"
        :right-btn="[]"
        isEmail
        :isCheckbox="false"
    >
        <template #left>
            <el-button @click="addSettings('add')">增加</el-button>
        </template>
    </Table>

    <el-dialog :title="title" v-model="visible" width="850px" append-to-body>
        <el-form ref="settingsFormRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="邮件地址：" prop="emailAddress">
                <el-input :disabled="isEdit" autocomplete="off" v-model="form.emailAddress" @blur="getPort" />
            </el-form-item>
            <el-form-item label="密码：" prop="emailPassword">
                <el-input type="password" autocomplete="off" show-password :readonly="isReadonly" v-model="form.emailPassword" />
            </el-form-item>
            <el-form-item label="邮箱类型：" prop="protocolType">
                <el-radio-group v-model="form.protocolType" @change="changeType">
                    <el-radio value="IMAP" label="IMAP" />
                    <el-radio value="POP3" label="POP3" />
                </el-radio-group>
            </el-form-item>
            <el-form-item class="senior-item" :label="emailTypeName + '：'" prop="receiveServer">
                <el-input v-model="form.receiveServer" />
                <el-checkbox v-model="form.receiveSsl" value="IMAP" label="SSL" @change="changePort"></el-checkbox>
                <label class="el-form-item__label">端口：</label>
                <el-input v-model="form.receivePort" />
            </el-form-item>
            <el-form-item class="senior-item" label="SMTP服务器：" prop="smtpServer">
                <el-input v-model="form.smtpServer" />
                <el-checkbox v-model="form.smtpSsl" value="IMAP" label="SSL" @change="changePort('smtp')"></el-checkbox>
                <label class="el-form-item__label">端口：</label>
                <el-input v-model="form.smtpPort" />
            </el-form-item>
            <!-- <el-form-item class="senior-item" label="SMTP服务端口（S）：" prop="orderFormId">
                <el-input v-model="form.smtpPort" />
                <el-checkbox v-model="form.smtpSsl" value="IMAP" label="SMTP安全连接（SSL）"></el-checkbox>
            </el-form-item> -->
            <!-- <el-form-item class="senior-item" label="IMAP服务端口（P）：" prop="orderFormId">
                <el-input v-model="form.imapPort" />
                <el-checkbox v-model="form.imapSsl" value="IMAP" label="IMAP安全连接（SSL）"></el-checkbox>
            </el-form-item> -->
            <el-form-item class="senior-item" label="只收取：" prop="pullDay">
                <el-input v-model="form.pullDay" />
                <span>天内的邮件</span>
            </el-form-item>
            <el-form-item label="邮件发件人：" prop="senderNickName">
                <el-input v-model="form.senderNickName" />
            </el-form-item>
            <el-form-item label="" prop="useDefault">
                <el-checkbox v-model="form.useDefault" :value="1" label="设为默认发件箱"></el-checkbox>
            </el-form-item>
        </el-form>
        <template #footer>
			<div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm('test')">检 测</el-button>
				<el-button :disabled="submitDisabled" :loading="buttonLoading" type="primary" @click="submitForm('save')">提交</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</template>
    </el-dialog>
</template>

<script setup lang="ts">
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import { listEmailsSetting, addEmailsSetting, delEmailsSetting, emailsTest, getMailsPort } from '@/api/emails';
    import { EmailsVO, EmailsQuery, EmailsForm } from '@/api/emails/types';

    const emits = defineEmits(['refresh', 'emailContent', 'delChange'])

    const tableParams = reactive<tableTypes<EmailsQuery, EmailsVO>>({
        tableColumn: [
            { show: true, label: '邮件地址', prop: 'emailAddress' },
            { show: true, label: 'IMAP/POP3服务器', prop: 'receiveServer' },
            { show: true, label: 'SMTP服务器', prop: 'smtpServer' },
            { show: true, label: '状态', prop: 'status', render: ({ column }: { column: EmailsVO }) => {
                return column.enabled ? '启用' : '禁用'
            } },
            {
                show: true, label: '操作', width: 150, prop: 'operation', disabledMove: true, render: ({ column }: { column: EmailsVO }) => {
                    return [
                        h(ElButton, { link: true, type: 'primary', onClick: () => { addSettings('edit', column) } }, '编辑'),
                        h(ElButton, { link: true, type: 'danger', onClick: () => { delSettings(column.id) } }, '删除'),
                    ]
                }
            },
        ],
        queryParams: {
            blurry: ''
        },
        listFn: listEmailsSetting
    })

    const { queryParams } = toRefs(tableParams)

    const visible = ref(false)
    const title = ref('')
    const isEdit = ref(false)
    const isReadonly = ref(true)
    const addSettings = (type: string, data?: EmailsVO) => {
        isEdit.value = false
        reset()
        title.value = type == 'add' ? '增加' : '编辑'
        visible.value = true
        nextTick(() => {
            setTimeout(() => {
                isReadonly.value = false
            }, 500)
            if(type == 'edit') {
                data.useDefault = data.useDefault == 1
                data.receiveSsl = data.receiveSsl == 1
                data.smtpSsl = data.smtpSsl == 1
                Object.assign(form.value, data)
                isEdit.value = true
                getPort()
            }
        })
    }

    const delSettings = (id: string | number) => {
        ElMessageBox.confirm(
            '是否确认删除当前数据？',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            delEmailsSetting(id).then(res => {
                if(res.success) {
                    ElMessage.success('删除成功')
                    settingsTable.value.getData()
                    emits('delChange', id)
                }else{
                    ElMessage.error('删除失败')
                }
            })
        }).catch(() => { })
    }

    const form = ref<EmailsForm>({
        id: undefined,
        emailAddress: '',
        emailPassword: '',
        smtpServer: '',
        useDefault: true,
        receiveSsl: false,
        receiveServer: '',
        smtpSsl: false,
        protocolType: '',
        receivePort: '',
        pullDay: '365',
    })
    const emailTypeName = ref('IMAP/POP3')
    const changeType = (val: string) => {
        emailTypeName.value = val
        submitDisabled.value = true
        if(portData.value) {
            form.value.receiveServer = portData.value[val == 'IMAP' ? 'imapServer' : 'popServer']
            if(form.value.receiveSsl) {
                form.value.receivePort = portData.value[val == 'IMAP' ? 'imapPortSsl' : 'popPortSsl']
            }else {
                form.value.receivePort = portData.value[val == 'IMAP' ? 'imapPort' : 'popPort']
            }
        }
    }

    const rules = ref({
        emailAddress: [
            { required: true, message: "邮件地址不能为空", trigger: "change" }
        ],
        emailPassword: [
            { required: true, message: "密码不能为空", trigger: "change" }
        ],
        smtpServer: [
            { required: true, message: "SMTP服务器不能为空", trigger: "change" }
        ],
        receiveServer: [
            { required: true, message: "IMAP/POP3不能为空", trigger: "change" }
        ],
        senderNickName: [
            { required: true, message: "邮件发件人不能为空", trigger: "change" }
        ],
        protocolType: [
            { required: true, message: "邮件类型不能为空", trigger: "change" }
        ]
    })

    const portData = ref(null)
    const getPort = () => {
        if(form.value.emailAddress) {
            getMailsPort(form.value.emailAddress).then(res => {
                if(res.success && res.result) {
                    portData.value = res.result
                    if(!isEdit.value) {
                        form.value.smtpServer = res.result.smtpServer
                        form.value.smtpPort = res.result.smtpPortSsl
                        form.value.smtpSsl = true
                        form.value.receiveSsl = true
                        form.value.protocolType = 'IMAP'
                        changeType('IMAP')
                        form.value.receiveServer = res.result.imapServer
                        form.value.receivePort = res.result.imapPortSsl
                    }
                }
            })
        }
    }

    const changePort = (type?: string) => {
        if(portData.value) {
            if(type == 'smtp') {
                form.value.smtpPort = portData.value[form.value.smtpSsl ? 'smtpPortSsl' : 'smtpPort']
            }else {
                if(form.value.receiveSsl) {
                    form.value.receivePort = portData.value[form.value.protocolType == 'IMAP' ? 'imapPortSsl' : 'popPortSsl']
                }else{
                    form.value.receivePort = portData.value[form.value.protocolType == 'IMAP' ? 'imapPort' : 'popPort']
                }
            }
        }
    }

    const submitDisabled = ref(true)
    const buttonLoading = ref(false)
    const settingsTable = ref()
    const settingsFormRef = ref()
    const submitForm = (type: string) => {
        settingsFormRef.value?.validate(async (valid: boolean) => {
            if(valid) {
                let params = JSON.parse(JSON.stringify(form.value))
                params.useDefault = params.useDefault ? 1 : 0
                params.receiveSsl = params.receiveSsl ? 1 : 0
                params.smtpSsl = params.smtpSsl ? 1 :0
                params.enabled = 1 // 前端无状态按钮，默认给开启
                buttonLoading.value = true;
                let requset = type == 'test' ? emailsTest : addEmailsSetting
                await requset(params).finally(() => buttonLoading.value = false);
                ElMessage.success((type == 'test' ? '检测' : '新增') + "成功")
                if(type == 'test') {
                    submitDisabled.value = false
                }else {
                    settingsTable.value.getData()
                    emits('refresh')
                    reset()
                    visible.value = false
                }
            }
        })
    }

    const reset = () => {
        settingsFormRef.value?.resetFields();
        form.value.receivePort = ''
        form.value.smtpPort = ''
        form.value.smtpSsl = false
        form.value.receiveSsl = false
        form.value.id = undefined
    }

    const cancel = () => {
        reset();
        visible.value = false
    }

    const handleQuery = () => {
        settingsTable.value.getData()
    }

    defineExpose({
        handleQuery,
        queryParams
    })
</script>

<style scoped lang="scss">
    :deep(.el-tabs){
        .el-tabs__content{
            height: 350px;
        }
        .el-tabs__header{
            margin: 0 0 25px;
        }
    }
    :deep(.senior-item){
        .el-input{
            width: 180px;
            margin-right: 20px;
        }
    }
</style>
