// 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('/wiki/detail', { id: id }).then(res => {
            const item = res || null;

            if (!item) {
                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;

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

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

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

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

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

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

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

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

        request.get('/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}`
        };
    }
});
