<template>
    <div class="teamaster-gallery">
        <el-card class="!border-none" v-loading="loading" shadow="never">
            <el-form ref="formRef" class="ls-form" :model="formData" :rules="formRules" label-width="100px">
                <el-form-item label="当前图片">
                    <div class="w-[220px]">
                        <el-image v-if="formData.url" style="width:220px;height:110px;" :src="formData.url"
                            :preview-src-list="[formData.url]" preview-teleported fit="cover" />
                        <div v-else class="text-tx-secondary">暂无图片</div>
                    </div>
                </el-form-item>
                <el-form-item label="上传图片" prop="url">
                    <material-picker v-model="formData.url" :limit="1" />
                </el-form-item>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="teamasterGallery">
import type { FormInstance } from 'element-plus'
import { apiCarouselTeamaster, apiCarouselTeamasterEdit } from '@/api/carousel'
import { removeImageUrlPrefix } from '@/utils/util'

const formRef = shallowRef<FormInstance>()
const loading = ref(false)
const submitLoading = ref(false)

const formData = reactive<Record<string, any>>({
    url: ''
})

const formRules = reactive({
    url: [
        {
            required: true,
            message: '请上传图片',
            trigger: ['change']
        }
    ]
})

const setFormData = (data: any) => {
    formData.url = ''

    if (!data) {
        return
    }

    const currentData = Array.isArray(data) ? data.find((item) => item) : data

    if (!currentData) {
        return
    }

    if (typeof currentData === 'string') {
        formData.url = currentData
        return
    }

    Object.assign(formData, currentData)
    formData.url = currentData.url ?? currentData.address ?? currentData.image ?? currentData.img ?? ''
}

const getTeamasterImage = async () => {
    loading.value = true
    try {
        const data = await apiCarouselTeamaster({})
        setFormData(data)
    }
    finally {
        loading.value = false
    }
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    submitLoading.value = true

    const url = removeImageUrlPrefix(formData.url)
    try {
        await apiCarouselTeamasterEdit({ url })
        getTeamasterImage()
    }
    finally {
        submitLoading.value = false
    }
}

getTeamasterImage()
</script>
