<template>
    <div class="edit-price">
        <custom-header name="飞鸟管家"></custom-header>
        <div class="edit-form">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="药肥名称" prop="id" required>
                    <el-select v-model="form.id" placeholder="请选择" filterable clearable style="width: 100%">
                        <el-option v-for="opt in pesticideOptions" :key="opt.id" :label="opt.name" :value="opt.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="药肥品牌" prop="brand" required>
                    <el-input class="has-border" v-model="form.brand" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="药肥类型" required prop="typeId">
                    <div class="row-3-selects">
                        <field
                            v-model="fieldValue"
                            is-link
                            readonly
                            label=""
                            placeholder="请选择药肥类型"
                            @click="showCascader = true"
                        />
                        <popup v-model:show="showCascader" round position="bottom">
                            <cascader
                                v-model="cascaderValue"
                                aria-hidden="false"
                                title="请选择药肥类型"
                                :options="typeOptions"
                                :field-names="cascaderProps"
                                @close="showCascader = false"
                                @finish="onFinish"
                            />
                        </popup>
                    </div>
                </el-form-item>

                <el-form-item label="计量单位" prop="unit" required>
                    <el-radio-group v-model="form.unit">
                        <el-radio value="克">克</el-radio>
                        <el-radio value="千克">千克</el-radio>
                        <el-radio value="毫升">毫升</el-radio>
                        <el-radio value="升">升</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="施用方式" prop="method" required>
                    <el-radio-group v-model="form.method">
                        <el-radio value="1">叶面施</el-radio>
                        <el-radio value="2">根部施</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="药肥成本" prop="cost" required class="input-unit">
                    <el-input v-model="form.cost" type="number" step="0.01" placeholder="请输入">
                        <template #append>元/{{ form.unit }}</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="药肥报价" prop="price" required class="input-unit">
                    <el-input v-model="form.price" type="number" step="0.01" placeholder="请输入">
                        <template #append>元/{{ form.unit }}</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="药肥库存" prop="stock" required class="input-unit">
                    <el-input v-model="form.stock" type="number" step="0.01" placeholder="请输入">
                        <template #append>{{ form.unit }}</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="单位兑水" class="input-unit">
                    <div class="water-row">
                        <el-input v-model="form.waterMin" type="number" step="0.01" placeholder="请输入兑水量">
                            <template #append>{{ form.unit }}</template>
                        </el-input>
                        <span>-</span>
                        <el-input v-model="form.waterMax" type="number" step="0.01" placeholder="请输入兑水量">
                            <template #append>{{ form.unit }}</template>
                        </el-input>
                    </div>
                </el-form-item>

                <el-form-item label="适用品类">
                    <el-select
                        v-model="form.speciesIds"
                        multiple
                        placeholder="请选择"
                        filterable
                        clearable
                        style="width: 100%"
                    >
                        <el-option v-for="(opt, optI) in specieList" :key="optI" :label="opt.name" :value="opt.id" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>

        <div class="page-action">
            <div class="btn-item del" v-if="!isAdd" @click="openDelete">删除</div>
            <div class="btn-item cancel" v-if="isAdd" @click="goBack">取消</div>
            <div class="btn-right">
                <div class="btn-item cancel" v-if="!isAdd" @click="goBack">取消编辑</div>
                <div class="btn-item primary" @click="handleSave">{{ isAdd ? "新增报价" : "保存报价" }}</div>
            </div>
        </div>
    </div>
</template>

<script setup>
import customHeader from "@/components/customHeader.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, onMounted, onActivated, onUnmounted, onDeactivated, watch } from "vue";
import { Cascader, Popup, Field } from "vant";

const router = useRouter();
const route = useRoute();
const isAdd = ref(false);
const goBack = () => {
    router.back();
};

const showCascader = ref(false);
const fieldValue = ref("");
const cascaderValue = ref("");
// 全部选项选择完毕后，会触发 finish 事件
const onFinish = ({ selectedOptions }) => {
    showCascader.value = false;
    fieldValue.value = selectedOptions.map((option) => option.name).join(" / ");
    form.typeId = selectedOptions[selectedOptions.length - 1].id;
};

const openDelete = () => {
    ElMessageBox.confirm("确认要删除该报价吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            VE_API.z_farm_work_pesticide_fertilizer.deleteFertilizer({ agriculturalStoreId: detailData.value.agriculturalStoreId, pesticideFertilizerId: detailData.value.id }).then((res) => {
                if (res.code === 0) {
                    ElMessage.success("删除成功");
                    router.back();
                }
            });
        })
        .catch(() => {});
};

// 表单模型与选项
const formRef = ref();
const form = reactive({
    id: "",
    typeId: null,
    brand: "",
    type1: "",
    type2: "",
    type3: "",
    unit: "克",
    method: "1",
    cost: null,
    price: null,
    stock: null,
    waterMin: null,
    waterMax: null,
    speciesIds: [],
});

const rules = {
    id: [{ required: true, message: "请选择药肥名称", trigger: "change" }],
    brand: [{ required: true, message: "请选择药肥品牌", trigger: "change" }],
    typeId: [{ required: true, message: "请选择药肥类型", trigger: "change" }],
    unit: [{ required: true, message: "请选择计量单位", trigger: "change" }],
    method: [{ required: true, message: "请选择施用方式", trigger: "change" }],
    cost: [{ required: true, message: "请输入成本", trigger: "blur" }],
    price: [{ required: true, message: "请输入报价", trigger: "blur" }],
    stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
};

// 单位转换映射
const unitMap = {
    kg: "千克",
    g: "克",
    ml: "毫升",
    l: "升",
    千克: "千克",
    克: "克",
    毫升: "毫升",
    升: "升",
};

// 施用方式转换映射
const methodMap = {
    叶面施: "1",
    根部施: "2",
};

const cascaderProps = {
    value: "id",
    text: "name",
    children: "children",
};

onMounted(() => {
    getSpecieList();
    fetchPesticideOptions();
    fetchTypeOptions();
    
    // 首次加载时初始化表单
    if (isAdd.value) {
        initForm();
    } else {
        getDetail();
    }
});

const specieList = ref([]);
function getSpecieList() {
    VE_API.farm.fetchSpecieList().then(({ data }) => {
        specieList.value = data;
    });
}


// 递归清理空的 children 属性
const cleanEmptyChildren = (data) => {
    if (!Array.isArray(data)) {
        return data;
    }
    return data.map((item) => {
        const newItem = { ...item };
        if (newItem.children) {
            if (Array.isArray(newItem.children) && newItem.children.length > 0) {
                // 递归处理子项
                newItem.children = cleanEmptyChildren(newItem.children);
            } else {
                // 如果 children 为空数组或不存在，删除该属性
                delete newItem.children;
            }
        }
        return newItem;
    });
};

// 用途类型选项
const typeOptions = ref([]);
function fetchTypeOptions() {
    if (typeOptions.value.length === 0) {
        VE_API.z_farm_work_pesticide_fertilizer.typeList().then((res) => {
            if (res.code === 0) {
                // 清理空的 children 属性
                typeOptions.value = cleanEmptyChildren(res.data || []);
            }
        });
    }
}
/**
 * 获取药肥选项
 */
const pesticideOptions = ref([]);
function fetchPesticideOptions() {
    // 每次都重新获取药肥选项，确保数据是最新的
    VE_API.z_farm_work_pesticide_fertilizer
        .selectOption()
        .then((res) => {
            if (res.code === 0) {
                pesticideOptions.value = res.data || [];
            }
        })
        .catch(() => {
            // 获取药肥选项失败
        });
}

// 根据 typeId 查找路径数组
const findPathByTypeId = (options, targetId, path = []) => {
    for (const option of options) {
        const currentPath = [...path, option.id];
        if (option.id === targetId) {
            return currentPath;
        }
        if (option.children && option.children.length > 0) {
            const found = findPathByTypeId(option.children, targetId, currentPath);
            if (found) return found;
        }
    }
    return null;
};

// 根据 typeId 查找显示文本
const findTextByTypeId = (options, targetId) => {
    for (const option of options) {
        if (option.id === targetId) {
            return option.name;
        }
        if (option.children && option.children.length > 0) {
            const found = findTextByTypeId(option.children, targetId);
            if (found) return found;
        }
    }
    return "";
};

// 根据 typeId 设置级联选择器的默认值
const setCascaderDefaultValue = (typeId) => {
    if (!typeId || !typeOptions.value.length) {
        return;
    }
    
    // 查找路径数组
    const path = findPathByTypeId(typeOptions.value, typeId);
    if (path && path.length > 0) {
        cascaderValue.value = path;
        
        // 查找显示文本（完整路径）
        const pathNames = [];
        let current = typeOptions.value;
        for (const id of path) {
            const option = current.find(opt => opt.id === id);
            if (option) {
                pathNames.push(option.name);
                current = option.children || [];
            }
        }
        if (pathNames.length > 0) {
            fieldValue.value = pathNames.join(" / ");
        }
    }
};

// 监听 typeOptions 变化，当数据加载完成后自动设置默认值
watch(
    () => typeOptions.value,
    (newOptions) => {
        if (newOptions.length > 0 && form.typeId) {
            setCascaderDefaultValue(form.typeId);
        }
    },
    { deep: true }
);

// 获取详情数据
const detailData = ref({});
const getDetail = () => {
    const id = route.query.id;
    if (!id || isAdd.value) {
        return;
    }

    VE_API.z_farm_work_pesticide_fertilizer
        .fertilizerDetail({ id })
        .then(({ data }) => {
            if (data) {
                detailData.value = data;
                // 赋值表单数据
                form.id = data.id || "";
                form.brand = data.brand || "";
                form.typeId = data.typeId || null;

                // 转换单位
                form.unit = unitMap[data.unit] || data.unit || "克";

                // 转换施用方式
                if (data.usageModeList && data.usageModeList.length > 0) {
                    const firstMode = data.usageModeList[0];
                    form.method = methodMap[firstMode] || firstMode;
                }

                form.cost = data.cost || null;
                form.price = data.price || null;
                form.stock = data.stock || null;
                form.waterMin = data.unitWaterAmount || null;
                form.waterMax = data.unitWaterAmountMax || null;
                // 适用品种
                if (data.speciesList && Array.isArray(data.speciesList) && data.speciesList.length > 0) {
                    form.speciesIds = data.speciesList.map(item => item.id);
                } else {
                    form.speciesIds = [];
                }
                console.log("form.speciesIds", form.speciesIds, data.speciesList);
                // 设置级联选择器的默认值（watch 会自动处理）
                if (form.typeId && typeOptions.value.length > 0) {
                    setCascaderDefaultValue(form.typeId);
                }
            }
        })
        .catch(() => {
            ElMessage.error("获取详情失败");
        });
};

// 重置表单数据
const resetForm = () => {
    form.id = "";
    form.typeId = null;
    form.brand = "";
    form.type1 = "";
    form.type2 = "";
    form.type3 = "";
    form.unit = "克";
    form.method = "1";
    form.cost = null;
    form.price = null;
    form.stock = null;
    form.waterMin = null;
    form.waterMax = null;
    form.speciesIds = [];
    
    // 重置级联选择器
    showCascader.value = false;
    fieldValue.value = "";
    cascaderValue.value = "";
    
    // 清除表单验证状态
    if (formRef.value) {
        formRef.value.resetFields();
        // formRef.value.clearValidate();
    }
};

// 初始化表单数据（新增模式）
const initForm = () => {
    resetForm();
    // 新增模式下的默认值
    form.unit = "克";
    form.method = "1";
};

onActivated(() => {
    isAdd.value = route.query.isAdd ? true : false;
    // 进入页面时，如果是新增模式，初始化表单；如果是编辑模式，获取详情
    if (isAdd.value) {
        initForm();
    } else {
        getDetail();
    }
});

onDeactivated(() => {
    // 离开页面时清除数据
    resetForm();
});

onUnmounted(() => {
    // 组件卸载时也清除数据
    resetForm();
});

// 根据路径数组获取三级分类名称
const getCategoryNamesByPath = (path) => {
    if (!path || path.length === 0 || !typeOptions.value.length) {
        return {
            categoryLevel1Name: "",
            categoryLevel2Name: "",
            categoryLevel3Name: "",
        };
    }
    
    const names = [];
    let current = typeOptions.value;
    
    for (let i = 0; i < path.length && i < 3; i++) {
        const option = current.find(opt => opt.id === path[i]);
        if (option) {
            names.push(option.name);
            current = option.children || [];
        } else {
            break;
        }
    }
    
    return {
        categoryLevel1Name: names[0] || "",
        categoryLevel2Name: names[1] || "",
        categoryLevel3Name: names[2] || "",
    };
};

// 获取选中的药肥信息
const getSelectedPesticideFertilizer = () => {
    const selected = pesticideOptions.value.find(opt => opt.id === form.id);
    if (!selected) {
        return null;
    }
    return selected;
};

// 单位反向转换（将中文单位转换为英文）
const reverseUnitMap = {
    千克: "kg",
    克: "g",
    毫升: "ml",
    升: "l",
};

// 保存方法
const handleSave = async () => {
    // 表单验证
    try {
        await formRef.value.validate();
    } catch (error) {
        ElMessage.warning("请完善表单信息");
        return;
    }
    
    // 获取选中的药肥信息
    const selectedPesticide = getSelectedPesticideFertilizer();
    if (!selectedPesticide) {
        ElMessage.warning("请选择药肥名称");
        return;
    }
    
    // 获取三级分类名称
    const categoryNames = getCategoryNamesByPath(cascaderValue.value);
    
    // 转换施用方式
    const usageModeList = form.method === "1" ? ["叶面施"] : ["根部施"];
    
    // 转换单位（如果需要英文单位）
    const unit = reverseUnitMap[form.unit] || form.unit;
    
    // 转换适用品种（数组转字符串，用逗号分隔）
    // const speciesIds = Array.isArray(form.crops) 
    //     ? form.crops.join(",") 
    //     : (form.crops || "");
    // 构建请求参数
    const params = {
        pesticideFertilizer: {
            id: selectedPesticide.id || form.id,
            name: selectedPesticide.name || "",
            // pesticideFertilizerCode: selectedPesticide.code || "",
            // typeName: selectedPesticide.typeName || "",
            typeId: form.typeId,
            defaultName: selectedPesticide.name || "",
            unit: unit,
            // price: selectedPesticide.price || form.price || null,
            unitWaterAmount: form.waterMin ? Number(form.waterMin) : null,
            unitWaterAmountMax: form.waterMax ? Number(form.waterMax) : null,
            speciesIds: form.speciesIds,
            usageModeList: usageModeList,
            categoryLevel1Name: categoryNames.categoryLevel1Name,
            categoryLevel2Name: categoryNames.categoryLevel2Name,
            categoryLevel3Name: categoryNames.categoryLevel3Name,
        },
        price: form.price ? Number(form.price) : null,
        cost: form.cost ? Number(form.cost) : null,
        stock: form.stock ? Number(form.stock) : null,
        remark: selectedPesticide.remark || "",
        brand: form.brand,
    };
    // 调用保存接口
    VE_API.z_farm_work_pesticide_fertilizer
        .saveFertilizer(params)
        .then((res) => {
            if (res.code === 0) {
                ElMessage.success(isAdd.value ? "新增报价成功" : "保存报价成功");
                // 延迟返回，让用户看到成功提示
                setTimeout(() => {
                    router.back();
                }, 1000);
            } else {
                ElMessage.error(res.message || "保存失败");
            }
        })
        .catch(() => {
            ElMessage.error("保存失败，请重试");
        });
};
</script>

<style lang="scss" scoped>
.edit-price {
    width: 100%;
    height: 100vh;
    background: #f5f7fb;
    .edit-form {
        margin: 12px;
        padding: 12px;
        background: #ffffff;
        .row-3-selects {
            width: 100%;
            display: flex;
            gap: 5px;
            ::v-deep {
                .van-cell {
                    padding: 4px 10px;
                    border: 1px solid rgba(33, 153, 248, 0.3);
                    border-radius: 5px;
                    box-sizing: border-box;
                }
                .van-field__control {
                    color: #2199f8;
                    &::placeholder {
                        color: rgba(33, 153, 248, 0.43) !important;
                    }
                }
                .van-cell__right-icon {
                    color: #2199f8;
                    transform: rotate(90deg);
                    font-size: 14px;
                }
                .el-select__wrapper {
                    padding: 2px 6px;
                }
            }
            > .el-select {
                flex: 1;
            }
        }
        .water-row {
            color: rgba(0, 0, 0, 0.1);
            display: flex;
            gap: 2px;
            > .el-input {
                flex: 1;
            }
        }

        ::v-deep {
            .el-form-item__label {
                color: rgba(29, 33, 41, 0.2);
                font-size: 14px;
            }
            .el-form-item--default {
                margin-bottom: 16px;
            }
            .el-select__input {
                color: #2199f8;
            }
            .el-select__wrapper {
                // height: 30px;
                color: #2199f8;
                min-height: 30px;
                line-height: 28px;
                box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.3) inset;
            }
            .el-select__caret {
                color: #2199f8;
            }
            .el-select__placeholder {
                color: #2199f8;
            }
            .el-radio {
                margin-right: 16px;
            }
            .has-border,
            .el-cascader {
                .el-input__wrapper {
                    box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.3) inset;
                }
            }
            .el-tag.el-tag--info {
                --el-tag-text-color: #2199f8;
                --el-tag-bg-color: rgba(33, 153, 248, 0.1);
            }
            .el-input__wrapper {
                box-shadow: none;
            }
            .el-input__inner {
                color: #2199f8;
                --el-input-placeholder-color: rgba(33, 153, 248, 0.43);
            }
            .el-input-group__append {
                padding: 0 6px;
                background: none;
                box-shadow: none;
            }
            .el-input-group__append {
                color: rgba(33, 153, 248, 0.5);
            }
            .input-unit {
                .el-input {
                    border: 1px solid rgba(33, 153, 248, 0.3);
                    border-radius: 5px;
                    height: 30px;
                    box-sizing: border-box;
                }
                .el-input__wrapper {
                    padding: 0 2px 0 10px;
                    height: 28px;
                    line-height: 28px;
                    min-height: 28px;
                }
                .el-input__inner {
                    --el-input-inner-height: 28px;
                    height: 28px;
                    line-height: 28px;
                    min-height: 28px;
                    color: #2199f8;
                    --el-input-placeholder-color: rgba(33, 153, 248, 0.43);
                }
            }
        }
    }

    .page-action {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 12px 12px;
        background: #fff;
        box-shadow: 2px 2px 4.5px rgba(0, 0, 0, 0.4);
        display: flex;
        justify-content: space-between;
        align-items: center;
        .btn-item {
            height: 40px;
            line-height: 41px;
            border-radius: 20px;
            width: fit-content;
            padding: 0 20px;
            color: #666666;
            font-size: 14px;
            &.del {
                color: #ff943d;
                background: rgba(255, 148, 61, 0.1);
            }
            &.cancel {
                border: 1px solid rgba(153, 153, 153, 0.5);
            }
            &.primary {
                color: #fff;
                background: linear-gradient(#76c3ff, #2199f8);
            }
        }
        .btn-right {
            display: flex;
            gap: 10px;
        }
    }
}
</style>

<style lang="scss">
// 针对特定作用域设置
.edit-price {
    --van-field-placeholder-text-color: rgba(33, 153, 248, 0.43);
}
</style>
