<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-spin :spinning="spining">
            <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="name">
                                <a-input :placeholder="'请输入名称'" v-model:value="formData.name"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'描述'" name="description">
                                <a-input :placeholder="'请输入描述'" v-model:value="formData.description"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'服务地址'" name="serviceUrl">
                                <a-input :placeholder="'请输入服务地址'" v-model:value="formData.serviceUrl"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'apiKey'" name="apiKey">
                                <a-input :placeholder="'请输入apiKey'" v-model:value="formData.apiKey"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'顺序'" name="sequence">
                                <a-input-number :placeholder="'请输入顺序'" v-model:value="formData.sequence"
                                    style="width: 100%;"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'状态'" name="status">
                                <a-radio-group v-model:value="formData.status" :options="aiStatus.getAll()"
                                    disabled></a-radio-group>
                            </a-form-item>

                        </a-col>
                        <a-col :span="8">
                            <a-form-item :label="'封面'" name="imagePath">
                                <gx-upload v-model="formData.imagePath" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item :label="'头像'" name="icon">
                                <gx-upload v-model="formData.icon" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item :label="'背景图'" name="background">
                                <gx-upload v-model="formData.background" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-card>
            </a-form>
        </a-spin>
    </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, useSpining } from '@/hooks'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import dayjs from 'dayjs'
import { createMenu, getMenu, updateMenu } from '@/apis/modules/aiRequest'
import { spliceUrl } from '@/utils/util'
import { aiStatus } from '@/enums/index.js'
const emit = defineEmits(['ok'])
const { t } = useI18n() // 解构出t方法
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const { spining, showSpining, hideSpining } = useSpining()
const cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))
const rolesValue = ref([])
const roles = ref([])
const img = ref('')

formRules.value = {
    name: { required: true, message: '请输入名称' },
    description:{required: true, message: '请输入描述'},
    serviceUrl:{required: true, message: '请输入服务地址'},
    apiKey:{required: true, message: '请输入描述'},
    description:{required: true, message: '请输入描述'},
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    sequence: [{ required: true, message: '请选择顺序', trigger: 'change' }],
    imagePath: [{ required: true, message: '请上传图片', trigger: 'change' }],
    icon: [{ required: true, message: '请上传图片', trigger: 'change' }],
    background: [{ required: true, message: '请上传图片', trigger: 'change' }],
}

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        // 80对应about
        title: '添加',
    })
    formData.value.status = 1
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: t('pages.system.user.edit'),
    })
    showSpining()
    const { data, success } = await apis.aiRequest.getMenu(record.id).catch()
    if (!success) {
        hideModal()
        return
    }
    hideSpining()
    formData.value = { ...data }
    formData.value.imagePath = [config('http.apiBasic') + data.imagePath]
    formData.value.icon = [config('http.apiBasic') + data.icon]
    formData.value.background = [config('http.apiBasic') + data.background]
}

/**
 * 确定
 */
function handleOk() {
    formRef.value.validateFields().then(async (values) => {
        console.log(values)
        try {
            showLoading()
            const params = {
                ...values,
                imagePath: spliceUrl(formData.value?.imagePath[0]),
                icon: spliceUrl(formData.value?.icon[0]),
                background: spliceUrl(formData.value?.background[0]),
                scene: 1,
                status: 1
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.aiRequest.createMenu(params).catch(() => {
                        throw new Error()
                    })
                    break
                case 'edit':
                    // result = await apis.aiRequest.updateMenu(formData.value.id, params).catch(() => {
                    result = await apis.aiRequest.updateMenu(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() {
    img.value = ''
    hideModal()
}

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

defineExpose({
    handleCreate,
    handleEdit,
})
</script>

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