<template>
    <a-modal :open="modal.open" :title="modal.title" :width="640" :confirm-loading="modal.confirmLoading"
             :after-close="onAfterClose" :cancel-text="cancelText" :ok-text="okText" @ok="handleOk" @cancel="handleCancel">
        <a-form ref="formRef" :model="formData" :rules="formRules">
            <a-card class="mb-8-2">
                <a-row :gutter="12">
                    <a-col :span="24">
                        <a-form-item :label="'标题'" name="title">
                            <a-input :placeholder="'请输入标题'" v-model:value="formData.title"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'内容'" name="subheading">
<!--                            <a-textarea :placeholder="'内容'" v-model:value="formData.subheading"></a-textarea>-->
                            <a-textarea :placeholder="'请输入内容'" v-model:value="formData.subheading"></a-textarea>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'链接'" name="link">
                            <a-input v-model:value="formData.link" :placeholder="'请输入链接'" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'日期'" name="pushAt">
                            <a-date-picker v-model:value="formData.pushAt" :format="'YYYY-MM-DD'" placeholder="选择日期" style="width: 100%;">
                            </a-date-picker>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'状态'" name="status">
                            <a-radio-group v-model:value="formData.status" :options="[
                                { label: '启用', value: 'enabled' },
                                { label: '停用', value: 'disabled' },
                            ]"></a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'大图片'" name="fullImg">
                            <x-upload-image v-model="formData.fullImg" @imgChange="(val) => imgChange(val, 'fullImg')" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'小图片'" name="smallImg">
                            <x-upload-image v-model="formData.smallImg" @imgChange="(val) => imgChange(val, 'smallImg')" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="视频" name="videoUrl">
                            <a-upload
                                :action="uploadUrl"
                                :show-upload-list="false"
                                :before-upload="beforeUpload"
                                :on-success="handleUploadSuccess"
                                :accept="'video/*'"
                            >
                                <a-button type="primary">上传视频</a-button>
                            </a-upload>

                            <video
                                v-if="formData.videoUrl"
                                :src="formData.videoUrl"
                                @imgChange="(val) => imgChange(val, 'videoUrl')"
                                controls
                                style="margin-top: 10px; width: 100%; max-width: 600px;"
                            />
                        </a-form-item>

                    </a-col>
                </a-row>
            </a-card>
        </a-form>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import dayjs from 'dayjs'
const emit = defineEmits(['ok'])
const { t } = useI18n() // 解构出t方法
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))
const rolesValue = ref([])
const roles = ref([])
const fullImg = ref('')
const smallImg = ref('')
const videoUrl = ref('')
formRules.value = {
    title: { required: true, message: '请输入标题' },
    subheading: { required: false, message: '请输入内容' },
    link: { required: false, message: '请输入链接' },
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    pushAt: [{ required: true, message: '请选择发布日期', trigger: 'change' }],
    fullImg: [{ required: false, message: '请上传大图片', trigger: 'change' }],
    smallImg: [{ required: false, message: '请上传小图片', trigger: 'change' }],
    videoUrl: [{ required: false, message: '请上传视频', trigger: 'change' }],
}
/**
 * select 选择框
 */
const handleChange = (value) => {
    rolesValue.value = value
}

const imgChange = (value, type) => {
    formData.value[type] = value
}
/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '添加公司动态',
    })
    formData.value.status = 'enabled'
}


/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: t('pages.system.user.edit'),
    })
    const { data, success } = await apis.videoCenter.getItem(record.id).catch()
    if (!success) {
        hideModal()
        return
    }
    formData.value = { ...data }
    formData.value.pushAt = dayjs(data.pushAt)
    console.log(formData.value)
    formData.value.fullImg = config('http.apiBasic') + data.fullImg
    formData.value.smallImg = config('http.apiBasic') + data.smallImg
    formData.value.videoUrl = config('http.apiBasic') + data.videoUrl
}

/**
 * 确定
 */
function handleOk() {
   // if (!formData.value.img) return message.error('请上传图片');
    formRef.value.validateFields().then(async (values) => {
        console.log(values)
        try {
            showLoading()
            const params = {
                ...values,
                //img: formData.value.img,
                fullImg: formData.value.fullImg,
                smallImg: formData.value.smallImg,
                videoUrl: formData.value.videoUrl,
                pushAt:dayjs(formData.value.pushAt).format("YYYY-MM-DD"),
            }
            let result = null
            console.log(modal.value.type)
            switch (modal.value.type) {
                case 'create':
                    result = await apis.videoCenter.createDynamic(params).catch(() => {
                        throw new Error()
                    })
                    break
                case 'edit':
                    result = await apis.videoCenter.updateItem(formData.value.id, params).catch(() => {
                        throw new Error()
                    })
                    break
            }
            hideLoading()
            if (config('http.code.success') === result?.success) {
                hideModal()
                emit('ok')
            }
        } catch (error) {
            console.log(error)
            hideLoading()
        }
    })
        .catch((e) => {
            console.log(e)
            hideLoading()
        })
}

/**
 * 对权限组 过数据格式
 */
function formatArr(data, type = '') {
    const rolesArr = []
    data.forEach((item) => {
        roles.value.forEach((r) => {
            if (type === 'edit') {
                if (item.role_id === r.value) {
                    rolesArr.push({
                        value: item.role_id,
                        label: r.label,
                    })
                    return
                }
            } else if (r.value === item) {
                rolesArr.push({
                    role_id: item,
                    role_name: r.label,
                })
                return
            }
        })
    })
    return rolesArr
}

/**
 * 取消
 */
function handleCancel() {
    //imgUrl.value = ''
    fullImg.value = ''
    smallImg.value = ''
    videoUrl.value = ''
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

defineExpose({
    handleCreate,
    handleEdit,
})
/**
 * 视频上传
 */
function beforeUpload(file) {
    const isVideo = file.type.startsWith('video/')
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isVideo) {
        message.error('只能上传视频文件')
        return false
    }
    if (!isLt100M) {
        message.error('视频大小不能超过 100MB')
        return false
    }
    return true
}

function handleUploadSuccess(response) {
    formData.value.videoUrl = response.url
    message.success('视频上传成功')
}

function videoChange(url) {
    console.log('视频改变了:', url)
}
</script>

<style lang="less" scoped></style>
