<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="520px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="110px" :rules="formRules">
                <el-form-item label="日期" prop="cost_date">
                    <el-date-picker
                        v-model="formData.cost_date"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期"
                        :disabled="mode === 'edit'"
                        class="w-full"
                    />
                </el-form-item>
                <el-form-item label="自媒体来源" prop="media_source">
                    <media-source-select
                        v-model="formData.media_source"
                        :options="mediaSourceOptions"
                        :loading="mediaSourceLoading"
                        placeholder="请选择自媒体来源"
                        :allow-create="false"
                        :disabled="mode === 'edit'"
                        select-class="w-full"
                    />
                </el-form-item>
                <el-form-item label="账户消耗" prop="amount">
                    <el-input-number
                        v-model="formData.amount"
                        :min="0"
                        :step="0.01"
                        :precision="2"
                        class="w-full"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input
                        v-model="formData.remark"
                        type="textarea"
                        :autosize="{ minRows: 3, maxRows: 5 }"
                        maxlength="255"
                        show-word-limit
                        placeholder="选填"
                    />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'

import {
    personalAccountCostAdd,
    personalAccountCostEdit,
} from '@/api/self_input_stats'
import Popup from '@/components/popup/index.vue'

import MediaSourceSelect from './MediaSourceSelect.vue'
import type { MediaSourceOption } from './useMediaSourceOptions'

withDefaults(
    defineProps<{
        mediaSourceOptions?: MediaSourceOption[]
        mediaSourceLoading?: boolean
    }>(),
    {
        mediaSourceOptions: () => [],
        mediaSourceLoading: false,
    }
)

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref<'add' | 'edit'>('add')

const popupTitle = computed(() => (mode.value === 'edit' ? '编辑账户消耗' : '新增账户消耗'))

const formData = reactive({
    id: '',
    cost_date: '',
    media_source: '',
    amount: 0,
    remark: '',
})

const formRules = {
    cost_date: [{ required: true, message: '请选择日期', trigger: ['change'] }],
    media_source: [{ required: true, message: '请填写自媒体来源', trigger: ['blur'] }],
    amount: [{ required: true, message: '请输入账户消耗金额', trigger: ['blur', 'change'] }],
}

const resetForm = () => {
    formData.id = ''
    formData.cost_date = ''
    formData.media_source = ''
    formData.amount = 0
    formData.remark = ''
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    if (mode.value === 'edit') {
        await personalAccountCostEdit(formData)
    } else {
        await personalAccountCostAdd(formData)
    }
    popupRef.value?.close()
    emit('success')
}

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

const setFormData = (data: Record<string, any>) => {
    formData.id = data.id ?? ''
    formData.cost_date = data.cost_date ?? ''
    formData.media_source = data.media_source ?? ''
    formData.amount = Number(data.amount ?? 0)
    formData.remark = data.remark ?? ''
}

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

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