<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-tabs v-model:activeKey="activeKey">
                        <a-tab-pane key="1" tab="基本信息">
                            <a-row :gutter="12">
                                <a-col :span="24">
                                    <a-form-item :label="'产品名称'" name="code">
                                        <a-input :placeholder="'请输入产品名称'" v-model:value="formData.code"></a-input>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item :label="'产品类别'" name="categoryIDs">
                                        <a-tree-select v-model:value="formData.categoryIDs" :tree-data="categoryList"
                                            @change="handleTreeSelectChange" placeholder="请选择（只能选最后一级）"
                                            style="width: 100%" tree-default-expand-all/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item :label="'原料组成'">
                                        <a-textarea :placeholder="'请输入原料组成'"
                                            v-model:value="formData.compose"></a-textarea>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item :label="'适用对象'" name="target">
                                        <a-input :placeholder="'请输入适用对象'" v-model:value="formData.target"></a-input>
                                    </a-form-item>

                                </a-col>

                                <a-col :span="12">
                                    <a-form-item :label="'产品排序'" name="sequence">
                                        <a-input-number v-model:value="formData.sequence" :placeholder="'请输入排序'"
                                            style="width: 100%;" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <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-form-item :label="'产品图片'">
                                    <gx-upload v-model="formData.mainImage" :fileNumber="2" />
                                </a-form-item>

                            </a-row>
                        </a-tab-pane>
                        <a-tab-pane key="2" tab="产品功能">
                            <a-col :span="24">
                                <a-form-item v-for="(item, index) in formData.feature" :key="index"
                                    :label="`产品功能特点 ${index + 1}`">
                                    <a-input v-model:value="item.label" placeholder="请输入功能特点标题" class="inputPhone" />
                                    <a-select v-model:value="item.data" mode="tags" :placeholder="'请输入功能特点，按回车区分不同特点'"
                                        :token-separators="[',']" style="width: 100%;" />
                                    <a-button danger @click="removeFeature(index)" size="small" style="margin-top: 8px">
                                        删除
                                    </a-button>
                                </a-form-item>

                                <a-form-item>
                                    <a-button type="dashed" block @click="addFeature">
                                        新增产品功能特点
                                    </a-button>
                                </a-form-item>

                            </a-col>
                        </a-tab-pane>
                        <a-tab-pane key="3" tab="产品标准">
                            <a-col :span="24">
                                <a-form-item v-for="(item, index) in formData.standard" :key="index"
                                    :label="`产品标准 ${index + 1}`">
                                    <a-input v-model:value="item.label" placeholder="请输入标准名称" class="inputPhone" />
                                    <a-input v-model:value="item.fu_hoao" placeholder="请输入符号" class="inputPhone"
                                        style="margin-top: 8px" />
                                    <a-input v-model:value="item.val" placeholder="请输入标准值" class="inputPhone"
                                        style="margin-top: 8px" />
                                    <a-input v-model:value="item.prx" placeholder="请输入标准值单位" class="inputPhone"
                                        style="margin-top: 8px" />
                                    <a-button danger @click="removeStandard(index)" size="small"
                                        style="margin-top: 8px">
                                        删除
                                    </a-button>
                                </a-form-item>

                                <a-form-item>
                                    <a-button type="dashed" block @click="addStandard">
                                        新增产品标准
                                    </a-button>
                                </a-form-item>

                            </a-col>
                        </a-tab-pane>
                    </a-tabs>

                </a-card>
            </a-form>
        </a-spin>

    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, onBeforeMount } 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 {
    createProductCategory,
    createProductObj, createProductsItem,
    getProductCategory,
    getProductObj,
    getProductsItem, updateProductsItem,
} from '@/apis/modules/products'
import { spliceUrl } from '@/utils/util'
const areaFormRef = ref()
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 imgUrl = ref('')
const categoryList = ref([])
const targetList = ref([])
const images = ref([])
const contentImage = ref([])
const childOpen = ref(false)

const activeKey = ref('1')
formRules.value = {
    title: { required: true, message: '请输入产品类别名称' },
    code: { required: true, message: '请输入产品名称' },
    categoryIDs: { required: true, message: '请选择产品类别', trigger: 'change' },
    compose: { required: true, message: '请选择产品适用对象', trigger: 'change' },
    feature: [{ required: true, message: '请输入产品功能特点', trigger: 'change' }],
    // feature: [{ required: true, message: '请输入产品功能特点' }],
    standard: [{ required: true, message: '请输入产品标准' }],
    images: [{ required: true, message: '请上传产品图片' }],
    mainImage: { required: true, message: '请上传产品图片' },
    contentImage: { required: false, message: '请上传产品内容图片' },
    sequence: [{ required: true, message: '请输入产品排序' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],

}

const initData = async () => {
    try {
        showSpining();
        const { success: prodSuccess, data: prodData } = await apis.categorys.getDataList({ pageSize: 999, page: 1 });
        if (config('http.code.success') === prodSuccess) {
            categoryList.value = prodData
        }

    } catch (error) {
        message.error({ content: error.message });
    } finally {
        hideSpining();
    }
}

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '产品中心',
    })
    // 初始化所有字段
    formData.value = {
        title: '',
        categoryIDs:'',
        compose: '',
        target: '',
        feature: [{
            label: '功能特点',
            data: []
        }],
        standard: [{
            label: '',
            val: '',
            fu_hoao: '',
            prx: '',
        }],
        images: [''],
        sequence: null,
        status: 'enabled',
    }
    initData()
}

//新建产品适用对象
const childHandleObjOk = async () => {
    areaFormRef.value.validateFields().then(async (values) => {
        try {
            const params = { ...targetForm.value }
            const { success } = await apis.products.createProductObj(params)
            if (success) message.success('新增成功')
            childOpen.value = false
            targetForm.value = { targetName: '', status: 'enabled' }
            initData()
        } catch (error) {
            message.error(error.message)
        }
    })
}
const handleCombinedOk = () => {
    childHandleOk();
    childHandleObjOk();
};
/**
 * 编辑
 */
async function handleEdit(record = {}) {
     initData()
    showModal({
        type: 'edit',
        title: t('pages.system.user.edit'),
    })
    const { data, success } = await apis.products.getProductsItem(record.id).catch()
    if (!success) {
        hideModal()
        return
    }
    formData.value = {
        ...data,
        categoryIDs:data.categoryID,
        categoryID:data.categoryID,
        categoryRootID:data.categoryRootID,
        standard: data.standard || [{
            label: '',
            val: '',
            fu_hoao: '',
            prx: '',
        }],
        feature: data.feature || [{
            label: '功能特点',
            data: []
        }],
        // images:data.images || [''],
        mainImage: data.images ? data.images.map(item=>config('http.apiBasic')+item):[''],
    }
}

/**
 * 确定
 */
function handleOk() {
    console.log('编辑产品列表', formData.value)
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
                ...values,
                categoryID:formData.value.categoryID,
                categoryRootID:formData.value.categoryRootID,
                standard: formData.value.standard ||
                    [{
                        label: '',
                        val: '',
                        fu_hoao: '',
                        prx: '',
                    }],
                feature: formData.value.feature,
                images: formData.value.mainImage?formData.value.mainImage.map(item=>spliceUrl(item)):[''],
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.products.createProductsItem(params).catch((error) => {
                        throw new Error(error)
                    })
                    break
                case 'edit':
                    result = await apis.products.updateProductsItem(formData.value.id, params).catch(() => {
                        throw new Error(error)
                    })
                    break
            }
            hideLoading()
            if (config('http.code.success') === result?.success) {
                hideModal()
                emit('ok')
            }
        } catch (error) {
            message.error({ content: error.message })
            hideLoading()
        }
    })
        .catch((e) => {
            console.log(e)
            hideLoading()
        })
}


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

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

defineExpose({
    handleCreate,
    handleEdit,
})

// 添加标准
function addStandard() {
    formData.value.standard.push({ label: '', value: '' })
}

// 删除标准
function removeStandard(index) {
    if (formData.value.standard.length > 1) {
        formData.value.standard.splice(index, 1)
    }
}
// 添加标准
function addFeature() {
    formData.value.feature.push({ label: '', value: '' })
}

// 删除标准
function removeFeature(index) {
    if (formData.value.feature.length > 1) {
        formData.value.feature.splice(index, 1)
    }
}
// 递归查找节点路径
const findNodePath = (tree, value, path = []) => {
    for (const node of tree) {
        const currentPath = [...path, node.value];
        if (node.value === value) return currentPath;
        if (node.children) {
            const found = findNodePath(node.children, value, currentPath);
            if (found) return found;
        }
    }
    return null;
};
// 获取节点是否是叶子节点
const isLeafNode = (id) => {
    const node = findNodeById(categoryList.value, id);
    if(node.children.length>0) return false;
    else return true
};
// 根据ID查找节点
const findNodeById = (tree, value) => {
    for (const node of tree) {
        if (node.value === value) return node;
        if(node.children){
            const found=findNodeById(node.children,value)
            if(found) return found;
        }
    }
    return null;
};
// 处理选择事件
const handleTreeSelectChange = (value) => {
    // 验证是否叶子节点
    if (!isLeafNode(value)) {
        message.warning('只能选择最后一级节点');
        formData.value.categoryID = null; // 清除非叶子选择
        return;
    }
    if (!value) return;
    const pathIds = findNodePath(categoryList.value, value);
    if (pathIds) {
        console.log('选中的路径ID数组:', pathIds);
        // 实际使用中，此处可提交 pathIds 到后端或进行其他操作
        formData.value.categoryID=pathIds[1]
        formData.value.categoryRootID=pathIds[0]
    }
};
</script>

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