<template>
    <div class="article-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header content="菜品编辑" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form
                ref="formRef"
                class="ls-form"
                :model="formData"
                label-width="85px"
                :rules="rules"
            >
                <div class="xl:flex">
                    <div>
                        <el-form-item label="菜品名称" prop="title">
                            <div class="w-80">
                                <el-input
                                    v-model="formData.title"
                                    placeholder="请输入菜品名称"
                                    type="textarea"
                                    :autosize="{ minRows: 3, maxRows: 3 }"
                                    maxlength="10"
                                    show-word-limit
                                    clearable
                                />
                            </div>
                        </el-form-item>
                        <el-form-item label="价格(元)" prop="summary">
                            <div class="w-80">
                                <el-input-number
                                    v-model="formData.summary"
                                    :precision="2"
                                    :min="0.01"
                                    controls-position="right"
                                />
                            </div>
                        </el-form-item>
                        <el-form-item label="菜品分类" prop="cid">
                            <el-select
                                class="w-80"
                                v-model="formData.cid"
                                placeholder="请选择菜品分类"
                                clearable
                            >
                                <el-option
                                    v-for="item in optionsData.articleCate"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="菜品简介" prop="intro">
                            <div class="w-80">
                                <el-input
                                    v-model="formData.intro"
                                    placeholder="请输入菜品简介"
                                    type="textarea"
                                    :autosize="{ minRows: 3, maxRows: 6 }"
                                    :maxlength="150"
                                    show-word-limit
                                    clearable
                                />
                            </div>
                        </el-form-item>
                        <el-form-item label="菜品图片" prop="image">
                            <div>
                                <div>
                                    <material-picker v-model="formData.image" :limit="1" />
                                </div>
                            </div>
                        </el-form-item>
                      <el-form-item label="菜品规格" prop="specs">
                          <div class="w-full block mb-4">
                            <el-button type="primary" @click="handleSpecs">+</el-button>
                          </div>
                          <div class="flex flex-col gap-4">
                            <div v-for="(spec, index) in formData.specs" :key="index" class="w-full">
                                <div class="flex items-center">
                                    <el-input
                                        v-model="spec.name"
                                        placeholder="请输入规格名称"
                                        class="w-60 mr-2"
                                    />
<!--                                    <el-button type="primary" @click="handleSpecs()">添加规格项</el-button>-->
                                    <el-button type="danger" @click="removeSpec(index)">删除</el-button>
                                </div>

                                <div class="mt-2 ml-4">
                                    <el-tag
                                        v-for="(tag, idx) in spec.items"
                                        :key="idx"
                                        class="mx-1 mb-2"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(index, idx)"
                                    >
                                        {{ tag.tag }}
                                    </el-tag>
                                    <el-input
                                        v-if="spec.inputVisible"
                                        ref="InputRef"
                                        v-model="spec.inputValue"
                                        class="w-20 ml-1"
                                        size="small"
                                        @keyup.enter="handleInputConfirm(index)"
                                        @blur="handleInputConfirm(index)"
                                    />
                                    <el-button
                                        v-else
                                        class="button-new-tag ml-1"
                                        size="small"
                                        @click="showInput(index)"
                                    >
                                        + 添加
                                    </el-button>
                                </div>
                            </div>
                        </div>
                      </el-form-item>
                        <el-form-item label="排序" prop="sort">
                            <div>
                                <el-input-number v-model="formData.sort" :min="0" :max="9999" />
                                <div class="form-tips">默认为0， 数值越大越排前</div>
                            </div>
                        </el-form-item>
                        <el-form-item label="状态" required prop="isShow">
                            <el-radio-group v-model="formData.isShow">
                                <el-radio :label="1">显示</el-radio>
                                <el-radio :label="0">隐藏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="articleListsEdit">
import type { FormInstance } from 'element-plus'
import feedback from '@/utils/feedback'
import { useDictOptions } from '@/hooks/useDictOptions'
import { articleCateAll, articleDetail, articleEdit, articleAdd } from '@/api/article'
import useMultipleTabs from '@/hooks/useMultipleTabs'

const route = useRoute()
const router = useRouter()
const formData = reactive<any>({
    id: '',
    title: '',
    image: '',
    cid: '',
    intro: '',
    author: '',
    content: '',
    visit: 0,
    sort: 0,
    isShow: 1,
    summary: 0,
    specs: [] // 规格
})

const { removeTab } = useMultipleTabs()
const formRef = shallowRef<FormInstance>()
const rules = reactive({
    title: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
    cid: [{ required: true, message: '请选择菜品分类', trigger: 'blur' }],
    summary: [{ required: true, message: '请输入价格', trigger: 'blur' }],
    image: [{ required: true, message: '添加菜品图片', trigger: 'change' }]
})

// getDetails 函数修改
const getDetails = async () => {
    const data = await articleDetail({
        id: route.query.id
    })
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key];
        if(key=='summary'){
            formData[key] = Number(formData[key])
        }
    })

    // 转换规格数据
    if (data.specsList && data.specsList.length > 0) {
        const specsMap = new Map()
        data.specsList.forEach((spec: { name: string; value: string; id: number }) => {
            if (!specsMap.has(spec.name)) {
                specsMap.set(spec.name, {
                    name: spec.name,
                    items: [],
                    inputVisible: false,
                    inputValue: ''
                })
            }
            specsMap.get(spec.name).items.push({
                id: spec.id,
                tag: spec.value
            })
        })
        formData.specs = Array.from(specsMap.values())
    }
}

const { optionsData } = useDictOptions<{
    articleCate: any[]
}>({
    articleCate: {
        api: articleCateAll
    }
})

const handleSave = async () => {
    await formRef.value?.validate()
    if (formData.specs && formData.specs.length > 5) {
        feedback.msgWarning('最多添加5个规格')
        return
    }
    const specsList: Array<{
        name: string;
        value: string;
        status: number;
        articleId: number | null;
        id: number | null;
        img: string | null;
    }> = [];
    formData.specs?.forEach((spec: { name: string; items: Array<{id: number|null, tag: string}> }) => {
        spec.items.forEach(item => {
            specsList.push({
                name: spec.name,
                value: item.tag,
                status: 1,
                articleId: formData.id || null,
                id: item.id || null,
                img: null
            })
        })
    })

    const submitData = {
        ...formData,
        specsList
    }

    if (route.query.id) {
        await articleEdit(submitData)
    } else {
        await articleAdd(submitData)
    }
    feedback.msgSuccess('操作成功')
    removeTab()
    router.back()
}

route.query.id && getDetails()

// 添加规格
const handleSpecs = () => {
    if (!formData.specs) {
        formData.specs = []
    }
    formData.specs.push({
        name: '',
        items: [],
        inputVisible: false,
        inputValue: ''
    })
}

// 删除规格
const removeSpec = (index: number) => {
    formData.specs.splice(index, 1)
}

// 显示输入框
const showInput = (specIndex: number) => {
    formData.specs[specIndex].inputVisible = true
    nextTick(() => {
        InputRef.value?.input?.focus()
    })
}

// 确认输入
const handleInputConfirm = (specIndex: number) => {
    const spec = formData.specs[specIndex]
    if (spec.inputValue) {
        spec.items.push({
            id: null,
            tag: spec.inputValue
        })
    }
    spec.inputVisible = false
    spec.inputValue = ''
}

// 删除标签
const handleClose = (specIndex: number, tagIndex: number) => {
    formData.specs[specIndex].items.splice(tagIndex, 1)
}

// 添加规格项
const handleAddSpecItem = (index: number) => {
    showInput(index)
}

const InputRef = ref()
</script>
