<template>
    <div class="add-and-edit-form">
        <!-- 基本信息表单 -->
        <TitleTip title="基本信息" />
        <el-form
            ref="addAndEditForm"
            label-width="120px"
            :model="addAndEditForm"
            :rules="addAndEditFormRules"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item label="名称" prop="name">
                        <el-input
                            clearable
                            maxlength="50"
                            show-word-limit
                            placeholder="请输入名称"
                            v-model="addAndEditForm.name"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="类型" prop="typeId">
                        <el-select
                            clearable
                            filterable
                            style="width: 100%"
                            placeholder="请选择类型"
                            @change="handleTypeIdChange"
                            v-model="addAndEditForm.typeId"
                        >
                            <el-option
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                v-for="item in dict.type.tb_product_type"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="链接" prop="linkUrl">
                        <el-input
                            clearable
                            maxlength="500"
                            show-word-limit
                            placeholder="请输入链接"
                            v-model="addAndEditForm.linkUrl"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="封面" prop="cover">
                        <UploadImgFormData
                            :limit="1"
                            :file-size="10"
                            :file-type="['jpg', 'png', 'jpeg']"
                            :file-list.sync="addAndEditForm.cover"
                            @onSelectDeleteFileId="handleSelectDeleteFileId"
                            :is-uploaded="addAndEditForm.cover.length >= 1"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="是否支持访问" prop="isAccess">
                        <el-radio-group v-model="addAndEditForm.isAccess">
                            <el-radio label="1">是</el-radio>
                            <el-radio label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="产品介绍" prop="introduction">
                        <el-input
                            clearable
                            type="textarea"
                            maxlength="2000"
                            show-word-limit
                            placeholder="请输入产品介绍"
                            :autosize="{ minRows: 6, maxRows: 10 }"
                            v-model="addAndEditForm.introduction"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 产品案例Tabs区域 -->
        <TitleTip title="产品案例" />
        <el-row class="add-product-case">
            <el-col :span="21" class="add-product-case-tags">
                <el-tabs
                    closable
                    type="card"
                    v-model="currentTab"
                    @tab-remove="handleRemoveTab"
                    @tab-click="handleTabClick"
                >
                    <el-tab-pane
                        :key="item.name"
                        :name="item.name"
                        :label="item.title"
                        v-for="item in editableTabs"
                    >
                    </el-tab-pane>
                </el-tabs>
            </el-col>
            <el-col :span="3">
                <el-button
                    plain
                    type="primary"
                    icon="el-icon-plus"
                    @click="handleAddProductCase"
                    style="height: 40px; width: 100%"
                >
                    新增
                </el-button>
            </el-col>
        </el-row>

        <!-- 产品案例表单：绑定当前Tab的formInfo -->

        <template v-for="item in editableTabs">
            <el-form
                :key="item.name"
                label-width="120px"
                :model="item.formInfo"
                :ref="`caseForm_${item.name}`"
                :rules="addAndEditFormCaseRules"
                v-show="currentTab === item.name"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="案例公司" prop="caseCompany">
                            <el-input
                                maxlength="50"
                                show-word-limit
                                placeholder="请输入案例公司"
                                v-model="item.formInfo.caseCompany"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="案例排序" prop="caseSort">
                            <el-input
                                clearable
                                placeholder="请输入案例排序"
                                v-model.number="item.formInfo.caseSort"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item
                            label="案例图片"
                            prop="caseImage"
                            required
                        >
                            <UploadImgFormData
                                :limit="6"
                                :file-size="10"
                                :file-type="['jpg', 'png', 'jpeg']"
                                :file-list.sync="item.formInfo.caseImage"
                                @onSelectDeleteFileId="handleSelectDeleteFileId"
                                :is-uploaded="
                                    item.formInfo.caseImage.length >= 6
                                "
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="案例介绍" prop="caseIntroduction">
                            <el-input
                                type="textarea"
                                maxlength="8000"
                                show-word-limit
                                placeholder="请输入案例介绍"
                                :autosize="{ minRows: 6, maxRows: 10 }"
                                v-model="item.formInfo.caseIntroduction"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>

        <!-- 底部按钮 -->
        <el-row class="add-and-edit-form-footer">
            <el-button size="mini" type="info" @click="handleCancel">
                取消
            </el-button>
            <el-button size="mini" type="primary" @click="handleSave">
                保存
            </el-button>
        </el-row>
    </div>
</template>

<script>
import {
    addProductCenterAPI,
    editProductCenterAPI,
    getProductCenterDetailAPI,
} from '@/api/dataManage/product-center'
import TitleTip from '@/components/TitleTip'
import UploadImgFormData from '@/components/UploadImgFormData'
export default {
    name: 'AddAndEditForm',
    dicts: ['tb_product_type'],
    components: { TitleTip, UploadImgFormData },
    props: {
        formType: {
            type: Number,
            default: 1,
        },
        detailsId: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            currentTab: '1', // 当前激活的Tab名称
            // 基本信息表单
            addAndEditForm: {
                name: '', // 名称
                typeId: '', // 类型
                typeName: '', // 类型名称
                cover: [], // 封面
                linkUrl: '', // 链接
                isAccess: '1', // 是否支持访问
                introduction: '', // 产品介绍
            },
            // 基本信息表单校验规则
            addAndEditFormRules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                typeId: [
                    { required: true, message: '请输入类型', trigger: 'blur' },
                ],
                linkUrl: [
                    { required: true, message: '请输入链接', trigger: 'blur' },
                ],
                cover: [
                    { required: true, message: '请输入封面', trigger: 'blur' },
                ],
                isAccess: [
                    {
                        required: true,
                        message: '请选择是否支持访问',
                        trigger: 'change',
                    }, // 优化：radio用change触发
                ],
                introduction: [
                    {
                        required: true,
                        message: '请输入产品介绍',
                        trigger: 'blur',
                    },
                ],
            },
            // 案例表单校验规则
            addAndEditFormCaseRules: {
                caseCompany: [
                    {
                        required: true,
                        message: '请输入案例公司',
                        trigger: 'blur',
                    },
                ],
                caseImage: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请上传案例图片',
                    },
                ],
                caseSort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                ],
                caseIntroduction: [
                    {
                        required: true,
                        message: '请输入案例介绍',
                        trigger: 'blur',
                    },
                ],
            },
            // 案例Tabs数据：每个Tab包含独立的表单信息
            editableTabs: [
                {
                    name: '1',
                    title: '案例1',
                    formInfo: {
                        id: '',
                        caseSort: 1,
                        caseImage: [],
                        caseCompany: '',
                        caseIntroduction: '',
                    },
                },
            ],

            editDeleteCaseId: [], // 编辑删除的案例ID
            editDeleteFileId: [], // 编辑删除的文件ID
        }
    },
    computed: {
        // 当前Tab的表单数据（简化引用）
        currentTabFormInfo() {
            const currentTab = this.editableTabs.find(
                (tab) => tab.name === this.currentTab,
            )
            return currentTab ? currentTab.formInfo : null
        },
        // 当前Tab的索引（简化引用）
        currentTabIndex() {
            return this.editableTabs.findIndex(
                (tab) => tab.name === this.currentTab,
            )
        },
    },

    methods: {
        // 取消操作
        handleCancel() {
            // 重置基本信息表单
            this.$refs.addAndEditForm?.resetFields()
            // 重置所有案例表单
            this.editableTabs.forEach((tab) => {
                this.$refs[`caseForm_${tab.name}`]?.resetFields()
            })
            // 回到第一个Tab
            this.currentTab = '1'

            this.$emit('closeDialog', false)
        },
        // 保存操作：校验所有表单
        async handleSave() {
            console.log(this.addAndEditForm, '基本信息表单')
            this.$message.closeAll()
            try {
                // 1. 校验基本信息表单
                await this.$refs.addAndEditForm.validate()

                // 2. 校验所有案例表单
                // const caseFormPromises = this.editableTabs.map((tab) => {
                //     return this.$refs[`caseForm_${tab.name}`].validate()
                // })
                // await Promise.all(caseFormPromises)

                // await this.$refs[`caseForm_${this.currentTab}`].validate()

                // 2. 手动校验所有案例表单的必填项
                const requiredFields = [
                    { key: 'caseCompany', name: '案例公司' },
                    { key: 'caseSort', name: '案例排序' },
                    { key: 'caseIntroduction', name: '案例介绍' },
                ]

                let isValid = true
                let errorMessage = ''
                let errorCaseIndex = ''

                // 遍历所有案例表单
                this.editableTabs.forEach((tab, tabIndex) => {
                    if (!isValid) return // 如果已经发现错误，停止检查

                    // 检查当前案例的每个必填字段
                    requiredFields.forEach((field) => {
                        if (!isValid) return

                        const value = tab.formInfo[field.key]
                        // 检查值是否为空（考虑空字符串、undefined、null）
                        if (
                            value === '' ||
                            value === undefined ||
                            value === null
                        ) {
                            isValid = false
                            errorCaseIndex = tabIndex
                            errorMessage = `案例${tabIndex + 1}的${
                                field.name
                            }为必填项`
                        }
                        // 对数字类型进行额外检查（避免0被误判）
                        else if (
                            field.key === 'caseSort' &&
                            (isNaN(value) || value === '')
                        ) {
                            isValid = false
                            errorCaseIndex = tabIndex
                            errorMessage = `案例${tabIndex + 1}的${
                                field.name
                            }必须为有效数字`
                        }
                    })

                    // 检查案例图片（如果需要必填的话）
                    if (isValid && tab.formInfo.caseImage.length === 0) {
                        isValid = false
                        errorMessage = `案例${
                            tabIndex + 1
                        }请至少上传一张案例图片`
                        errorCaseIndex = tabIndex
                    }
                })

                // 如果校验失败，抛出错误
                if (!isValid) {
                    this.currentTab = this.editableTabs[errorCaseIndex].name
                    this.$nextTick(async () => {
                        await this.$refs[
                            `caseForm_${this.editableTabs[errorCaseIndex].name}`
                        ][0].validate()
                    })
                    throw new Error(errorMessage)
                }

                // 3. 所有校验通过，提交数据
                const submitData = {
                    ...this.addAndEditForm,
                    cases: this.editableTabs.map((tab) => tab.formInfo),
                }
                console.log('提交数据：', submitData)

                // 组装参数
                const formData = new FormData()
                const filesTypes = []
                const { cover } = this.addAndEditForm
                cover.forEach((item) => {
                    if (!item.id) {
                        formData.append('files', item.raw)
                        filesTypes.push('s')
                    }
                })

                const addAndEditFormParams = this.addAndEditForm
                delete addAndEditFormParams.cover
                for (const key in addAndEditFormParams) {
                    formData.append(key, addAndEditFormParams[key])
                }

                const caseCompanyList = this.editableTabs.map((item, index) => {
                    item.formInfo.caseImage.forEach((file) => {
                        if (!file.id) {
                            formData.append('files', file.raw)
                            filesTypes.push(index)
                        }
                    })
                    return {
                        caseCompany: item.formInfo.caseCompany,
                        caseIntroduction: item.formInfo.caseIntroduction,
                        caseSort: item.formInfo.caseSort,
                        id: item.formInfo.id,
                    }
                })

                formData.append('json', JSON.stringify(caseCompanyList))
                formData.append('fileType', filesTypes.join(','))

                if (this.formType === 2) {
                    formData.append('delCase', this.editDeleteCaseId.join(','))
                    formData.append('delFile', this.editDeleteFileId.join(','))
                    formData.append('id', this.detailsId)
                }

                const API =
                    this.formType === 2
                        ? editProductCenterAPI
                        : addProductCenterAPI

                const res = await API(formData)

                if (res.code === 200) {
                    this.$modal.msgSuccess(
                        this.formType === 2 ? '编辑成功' : '新增成功',
                    )
                    this.$emit('closeDialog', true)
                }
            } catch (error) {
                console.log(error, 'error')
                // 校验失败，提示用户
                this.$message.error('请完善所有必填项后再保存')
            }
        },
        // 新增产品案例Tab
        handleAddProductCase() {
            const newTabIndex = this.editableTabs.length + 1
            const newTab = {
                title: `案例${newTabIndex}`,
                name: newTabIndex.toString(),
                formInfo: {
                    id: '',
                    caseCompany: '',
                    caseImage: [],
                    caseIntroduction: '',
                    caseSort: newTabIndex,
                },
            }
            this.editableTabs.push(newTab)
            // 自动切换到新Tab
            this.currentTab = newTab.name
        },
        // 移除产品案例Tab
        handleRemoveTab(removeTabName) {
            // 禁止删除最后一个Tab
            if (this.editableTabs.length <= 1) {
                this.$message.warning('至少保留一个案例')
                return
            }

            // 找到要删除的Tab索引
            const removeIndex = this.editableTabs.findIndex(
                (tab) => tab.name === removeTabName,
            )

            if (this.formType === 2) {
                this.editDeleteCaseId.push(
                    this.editableTabs[removeIndex].formInfo?.id,
                )
            }

            this.editableTabs.splice(removeIndex, 1)

            // 如果删除的是当前激活的Tab，切换到第一个Tab
            if (removeTabName === this.currentTab) {
                this.currentTab = this.editableTabs[0].name
            }

            // 当前激活的Tab索引 如果大于删除的Tab索引，则减1
            if (this.currentTabIndex >= removeIndex) {
                this.currentTab =
                    this.editableTabs[this.currentTabIndex - 1].name
            }

            // 重新计算排序（可选：保持排序连续）
            this.editableTabs.forEach((tab, index) => {
                tab.title = `案例${index + 1}`
                tab.name = (index + 1).toString()
                tab.formInfo.caseSort = index + 1
            })
        },
        // Tab切换事件：触发当前Tab的表单校验
        handleTabClick() {
            // this.$nextTick(() => {
            //     this.$refs[`caseForm_${this.currentTab}`]?.validate(
            //         (isValid) => {},
            //     )
            // })
        },

        // 类型ID改变事件
        handleTypeIdChange(value) {
            this.addAndEditForm.typeName = this.dict.type.tb_product_type.find(
                (item) => item.value === value,
            ).label
        },

        // 获取产品中心详情
        async getProductCenterDetail() {
            const res = await getProductCenterDetailAPI({
                id: this.detailsId,
            })

            console.log(res, '产品中心详情')

            const {
                name,
                typeId,
                typeName,
                image,
                linkUrl,
                introduction,
                isAccess,
                list,
            } = res?.data

            this.addAndEditForm = {
                name,
                typeId,
                typeName,
                linkUrl,
                introduction,
                isAccess,
                cover: [
                    { url: image.url, id: image.id, name: image.originalName },
                ],
            }

            this.editableTabs = list.map((item, index) => {
                return {
                    title: `案例${index + 1}`,
                    name: (index + 1).toString(),
                    formInfo: {
                        id: item.id,
                        caseCompany: item.caseCompany,
                        caseIntroduction: item.caseIntroduction,
                        caseSort: item.caseSort,
                        caseImage: item.imageList.map((e) => {
                            return {
                                id: e.id,
                                url: e.url,
                                name: e.originalName,
                            }
                        }),
                    },
                }
            })
        },

        // 选择删除的文件ID
        handleSelectDeleteFileId(id) {
            this.editDeleteFileId.push(id)
        },
    },
    watch: {
        detailsId: {
            handler(newVal) {
                if (newVal) {
                    this.getProductCenterDetail()
                }
            },
            immediate: true,
        },
    },
}
</script>

<style lang="scss" scoped>
.add-and-edit-form {
    width: 100%;
    height: 100%;
    padding-bottom: 70px;

    .add-and-edit-form-footer {
        position: fixed;
        bottom: 0;
        right: 0;
        width: 100%;
        height: 60px;
        padding: 10px;
        border-top: 1px solid #e5e6e7;
        background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

.add-product-case {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    // .add-product-case-tags {
    //     border: 1px solid #e5e6e7;
    // }
}

::v-deep .el-tabs__header {
    margin: 0;
}

::v-deep .el-tabs--card > .el-tabs__header {
    border: none;
}

::v-deep .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: none;
}

::v-deep .el-tabs__nav-scroll {
    border: 1px solid #e5e6e7;
}

::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item {
    border: none;
}

::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    background-color: #1abc9c;
    color: #fff;
}
</style>
