<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="480px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="账号名称" prop="account">
                    <el-input v-model="formData.account" placeholder="请输入账号名称" clearable :maxlength="20" show-word-limit />
                </el-form-item>
                <el-form-item v-if="formData.id == ''" label="账号密码" prop="password">
                    <el-input
                        v-model="formData.password"
                        placeholder="请输入账号密码"
                        clearable
                        :maxlength="20"
                        show-word-limit
                        type="password"
                        show-password
                    />
                </el-form-item>
                <el-form-item label="客户名称" prop="clientName">
                    <el-input v-model="formData.clientName" placeholder="请输入客户名称" clearable :maxlength="20" show-word-limit />
                </el-form-item>
                <el-form-item label="账号名额" prop="quota">
                    <el-input-number v-model="formData.quota" :min="1" :max="99999" style="width: 100%" />
                </el-form-item>
                <el-form-item label="有效期" prop="range" class="range">
                    <daterange-picker
                        type="datetimerange"
                        format="YYYY-MM-DD HH:mm:ss"
                        isDisabledDate
                        isDisabledHours
                        :shortcuts="shortcuts"
                        v-model:startTime="formData.range.startTime"
                        v-model:endTime="formData.range.endTime"
                    />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { accountAdd, accountDetail, accountEdit } from '@/api/account_center'
import feedback from '@/utils/feedback'
import { omit } from 'lodash-es'

const emit = defineEmits(['success', 'close'])

const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑账号' : '新增账号'
})
const formData = reactive({
    id: '',
    account: '',
    password: '',
    clientName: '',
    quota: 1,
    range: {
        startTime: '',
        endTime: ''
    }
})
const validaeRange = (rule: any, value: any, callback: any) => {
    if (value.startTime == '' || value.endTime == '') {
        callback(new Error('请选择有效期'))
    } else {
        callback()
    }
}
const formRules = {
    account: [
        {
            required: true,
            message: '请输入账号名称',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入账号密码',
            trigger: ['blur']
        }
    ],
    clientName: [
        {
            required: true,
            message: '请输入客户名称',
            trigger: ['blur']
        }
    ],
    quota: [
        {
            required: true,
            message: '请输入账号名额',
            trigger: ['blur']
        }
    ],
    range: [{ validator: validaeRange, trigger: 'change' }]
}
const shortcuts = [
    {
        text: '今天',
        value: () => {
            const start = new Date()
            const end = new Date()
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
        }
    },
    {
        text: '一周后',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setDate(end.getDate() + 7)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
        }
    },
    {
        text: '一个月后',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setMonth(end.getMonth() + 1)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
        }
    },
    {
        text: '三个月后',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setMonth(end.getMonth() + 3)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
        }
    },
    {
        text: '半年后',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setMonth(end.getMonth() + 6)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
        }
    },
    {
        text: '一年后',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setFullYear(end.getFullYear() + 1)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
        }
    }
]
const handleSubmit = async () => {
    await formRef.value?.validate()
    const { startTime, endTime } = formData.range
    Object.assign(formData, {
        startTime: startTime,
        expirationTime: endTime
    })
    const newFormData = omit(formData, ['range'])
    mode.value == 'edit' ? await accountEdit(newFormData) : await accountAdd(newFormData)
    feedback.msgSuccess('操作成功')
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
        formData.range.startTime = data['startTime']
        formData.range.endTime = data['expirationTime']
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await accountDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style lang="scss" scoped>
:deep(.range) {
    .el-form-item__label {
        &::before {
            content: '* ';
            margin-right: 2px;
            color: #f5222d;
        }
    }
}
</style>
