// pages/wiki/detail/index.js
import request from '../../../utils/request';

Page({
    data: {
        plant: null,
        activeImageIndex: 0,
        swiperList: [],
    },

    onLoad(options) {
        const eventChannel = this.getOpenerEventChannel();

        if (eventChannel && eventChannel.on) {
            eventChannel.on('acceptDataFromOpenerPage', (res) => {
                if (res.data) {
                    this.setPlantData(res.data);
                }
            });
        }

        if (options.id) {
            // Always fetch latest data (especially favorites status)
            this.loadPlantDetail(options.id);
        }
    },

    loadPlantDetail(id) {
        request.get('/plant/wiki/detail', { id: id }).then(res => {
            const item = res || null;

            if (!item || !item.wiki) {
                wx.showToast({ title: '未找到该植物', icon: 'none' });
                return;
            }

            this.setPlantData(item);
        }).catch(err => {
            console.error('Load plant detail failed', err);
            wx.showToast({ title: '加载失败', icon: 'none' });
        });
    },

    setPlantData(item) {
        if (!item) return;

        // 兼容两种数据来源:
        // 1. 从 API 获取: {wiki: {name:...}, imgList: [...]}
        // 2. 从列表页导航: {id:..., name:..., imgList: [...]} (raw item)
        const wiki = item.wiki || item;

        wx.setNavigationBarTitle({ title: wiki.name });

        // Prepare swiper list — imgList 在顶层
        const swiperList = (item.imgList || []).map(img => img.url);

        // Parse lists
        const commonPests = wiki.pestsDiseases
            ? wiki.pestsDiseases.split(',').map(s => s.trim()).filter(Boolean)
            : [];
        const aliasesList = wiki.aliases
            ? wiki.aliases.split(/[,，、]/).map(s => s.trim()).filter(Boolean)
            : [];
        const reproductionList = wiki.reproductionMethod
            ? wiki.reproductionMethod.split(/[,，、]/).map(s => s.trim()).filter(Boolean)
            : [];

        const diffLabels = { 1: '简单', 2: '中等', 3: '较难', 4: '困难', 5: '专家' };

        const plant = {
            id: wiki.id,
            name: wiki.name,
            latinName: wiki.latinName || '',
            aliases: wiki.aliases || '',
            aliasesList,
            genus: wiki.genus || '',
            distributionArea: wiki.distributionArea || '',
            difficulty: wiki.difficulty || 0,
            difficultyLabel: diffLabels[wiki.difficulty] || '未知',
            isHot: wiki.isHot === true || wiki.isHot === 1,
            lifeCycle: wiki.lifeCycle || '',
            growthHabit: wiki.growthHabit || '',
            reproductionMethod: wiki.reproductionMethod || '',
            reproductionList,
            lightIntensity: wiki.lightIntensity || '',
            lightType: wiki.lightType || '',
            optimalTempPeriod: wiki.optimalTempPeriod || '',
            stem: wiki.stem || '',
            foliageType: wiki.foliageType || '',
            foliageColor: wiki.foliageColor || '',
            foliageShape: wiki.foliageShape || '',
            height: wiki.height || 0,
            floweringPeriod: wiki.floweringPeriod || '',
            floweringColor: wiki.floweringColor || '',
            floweringShape: wiki.floweringShape || '',
            flowerDiameter: wiki.floweringDiameter || 0,
            fruit: wiki.fruit || '',
            pestsDiseases: wiki.pestsDiseases || '',
            commonPests,
            classes: (item.classIds || []).map(id => ({ id })),
            imgList: item.imgList || [],
            isFavorited: wiki.isStar === true || wiki.isStar === 1
        };

        this.setData({
            plant,
            swiperList
        });
    },

    toggleFavorite() {
        if (!this.data.plant) return;

        const { id, isFavorited } = this.data.plant;
        const type = isFavorited ? 2 : 1;

        request.get('/plant/wiki/star', { id, type }).then(() => {
            const newStatus = !isFavorited;
            this.setData({
                'plant.isFavorited': newStatus
            });
            wx.showToast({ title: type === 1 ? '已收藏' : '已取消', icon: 'success' });

            // Sync with previous page (Wiki List)
            const pages = getCurrentPages();
            if (pages.length > 1) {
                const prevPage = pages[pages.length - 2];
                if (prevPage.updateItemFavoriteStatus) {
                    prevPage.updateItemFavoriteStatus(id, newStatus);
                }
            }
        }).catch(err => {
            console.error('Toggle favorite failed', err);
            wx.showToast({ title: '操作失败', icon: 'none' });
        });
    },

    onSwiperChange(e) {
        this.setData({
            activeImageIndex: e.detail.current
        });
    },

    onShareAppMessage() {
        if (!this.data.plant) return {};
        return {
            title: `植物百科 - ${this.data.plant.name}`,
            path: `/pages/wiki/detail/index?id=${this.data.plant.id}`
        };
    },

    askAiAboutPlant() {
        const name = this.data.plant ? this.data.plant.name : '';
        wx.navigateTo({
            url: `/pages/wiki/chat/index?prefillQuestion=${encodeURIComponent(name + '怎么养护？')}`
        });
    }
});
