// pages/plant-detail/index.js
import { MOCK_PLANTS } from '../../utils/mockData';

const INITIAL_GROWTH_RECORDS = [
    {
        id: '1',
        date: '2026-02-01',
        type: 'growth',
        title: '新叶展开',
        content: '虽然是冬天，但在室内温暖的环境下，依然长出了翠绿的新叶。',
        image: 'monstera_plant_1769757312755.png'
    },
    {
        id: '2',
        date: '2026-01-20',
        type: 'growth',
        title: '茎秆长高',
        content: '主茎又长高了约5cm，状态良好。'
    },
    {
        id: '3',
        date: '2025-12-15',
        type: 'repot',
        title: '换盆记录',
        content: '原来的盆有点小了，换了一个大一号的陶盆，底部加了陶粒。'
    },
    {
        id: '4',
        date: '2025-11-28',
        type: 'pest',
        title: '发现蚜虫',
        content: '叶片背面发现少量蚜虫，已用肥皂水清洗处理。'
    },
    {
        id: '5',
        date: '2025-11-10',
        type: 'growth',
        title: '气根生长',
        content: '节点处长出了新的气根，说明生长环境湿度适宜。'
    },
    {
        id: '6',
        date: '2025-10-25',
        type: 'other',
        title: '调整位置',
        content: '从北窗移到了东窗，增加早晨的光照。'
    },
    {
        id: '7',
        date: '2025-10-12',
        type: 'other',
        title: '加入花园',
        content: '欢迎名为"小怪兽"的小家伙正式入住！'
    },
    {
        id: '8',
        date: '2025-09-28',
        type: 'growth',
        title: '购入记录',
        content: '在花市购入，高度约30cm，有5片成熟叶子。',
        image: 'monstera_plant_1769757312755.png'
    }
];

const INITIAL_CARE_LOGS = [
    { id: 'c1', date: '2026-02-02', time: '10:00', type: 'water', remark: '今天天气好，稍微多浇了一点。' },
    { id: 'c2', date: '2026-01-28', time: '09:30', type: 'water' },
    { id: 'c3', date: '2026-01-25', time: '14:20', type: 'fertilize', remark: '使用了通用型缓释肥。' },
    { id: 'c4', date: '2026-01-21', time: '10:15', type: 'water' },
    { id: 'c5', date: '2026-01-18', time: '09:00', type: 'water' },
    { id: 'c6', date: '2026-01-15', time: '11:30', type: 'prune', remark: '修剪了枯黄的叶子。' },
    { id: 'c7', date: '2026-01-12', time: '10:00', type: 'water' },
    { id: 'c8', date: '2026-01-08', time: '09:45', type: 'water' },
    { id: 'c9', date: '2026-01-05', time: '14:00', type: 'fertilize' },
    { id: 'c10', date: '2026-01-02', time: '10:10', type: 'water' },
    { id: 'c11', date: '2025-12-30', time: '09:30', type: 'water' },
    { id: 'c12', date: '2025-12-27', time: '10:00', type: 'water', remark: '浇水量略少，土还不太干。' },
    { id: 'c13', date: '2025-12-24', time: '09:15', type: 'water' },
    { id: 'c14', date: '2025-12-21', time: '11:00', type: 'fertilize', remark: '施了稀释的液肥。' },
    { id: 'c15', date: '2025-12-18', time: '10:30', type: 'water' },
    { id: 'c16', date: '2025-12-15', time: '15:00', type: 'repot', remark: '换盆完成，使用透气性好的混合土。' },
    { id: 'c17', date: '2025-12-12', time: '09:45', type: 'water' },
    { id: 'c18', date: '2025-12-09', time: '10:20', type: 'water' },
];

Page({
    data: {
        currentPlant: null,
        activeImageIndex: 0,
        activeTab: 'care',
        careLogs: [],
        displayCareLogs: [],
        displayCareLimit: 5,
        records: [],
        displayRecords: [],
        displayRecordLimit: 5,
        swiperImages: [],

        // Growth Modal
        showGrowthModal: false,
        newRecordType: 'growth',
        newRecordContent: ''
    },

    onLoad(options) {
        this.initData(options.id);
    },

    onShow() {
        if (this.data.currentPlant && this.data.currentPlant.id) {
            this.initData(this.data.currentPlant.id);
        }
    },

    initData(id) {
        const plant = MOCK_PLANTS.find(p => p.id === id);
        if (plant) {
            this.setData({
                currentPlant: plant,
                swiperImages: (plant.images || ['monstera_plant_1769757312755.png']).map(img => (img.indexOf('http') === 0 || img.indexOf('wxfile') === 0) ? img : `/assets/${img}`),
                careLogs: this.processLogs(INITIAL_CARE_LOGS),
                records: INITIAL_GROWTH_RECORDS
            });
            this.updateDisplayLogs();
            this.updateDisplayRecords();
        }
    },

    processLogs(logs) {
        return logs.map(log => {
            const parts = log.date.split('-');
            return {
                ...log,
                day: parts[2],
                month: parts[1],
                typeLabel: this.getCareTypeLabel(log.type)
            };
        });
    },

    getCareTypeLabel(type) {
        const map = {
            water: '浇水',
            fertilize: '施肥',
            prune: '修剪',
            repot: '换盆'
        };
        return map[type] || '养护';
    },

    updateDisplayLogs() {
        this.setData({
            displayCareLogs: this.data.careLogs.slice(0, this.data.displayCareLimit)
        });
    },

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

    switchTab(e) {
        const tab = e.currentTarget.dataset.tab;
        if (tab) {
            this.setData({ activeTab: tab });
        }
    },

    // Prevent background scroll when modal is open
    preventTouchMove() {
        return false;
    },

    toggleCareLimit() {
        const newLimit = this.data.displayCareLimit + 5;
        this.setData({ displayCareLimit: newLimit });
        this.updateDisplayLogs();
    },

    updateDisplayRecords() {
        this.setData({
            displayRecords: this.data.records.slice(0, this.data.displayRecordLimit)
        });
    },

    toggleRecordLimit() {
        const newLimit = this.data.displayRecordLimit + 5;
        this.setData({ displayRecordLimit: newLimit });
        this.updateDisplayRecords();
    },

    // Navigate to Edit Page
    handleOpenEditModal() {
        if (this.data.currentPlant && this.data.currentPlant.id) {
            wx.navigateTo({
                url: `/pages/plant-detail/edit/index?id=${this.data.currentPlant.id}`
            });
        }
    },

    // Growth Record Logic
    openGrowthModal() { this.setData({ showGrowthModal: true, newRecordContent: '', newRecordType: 'growth' }); },
    onGrowthPopupVisibleChange(e) { this.setData({ showGrowthModal: e.detail.visible }); },
    closeGrowthModal() { this.setData({ showGrowthModal: false }); },

    setRecordType(e) {
        const type = e.currentTarget.dataset.type;
        if (e.detail.checked) {
            this.setData({ newRecordType: type });
        }
    },
    setRecordTypeByTap(e) {
        const type = e.currentTarget.dataset.type;
        this.setData({ newRecordType: type });
    },
    onRecordContentInput(e) { this.setData({ newRecordContent: e.detail.value }); },

    handleAddRecord() {
        if (!this.data.newRecordContent.trim()) return;

        const mapTitle = { growth: '生长记录', repot: '换盆记录', pest: '病虫害记录', other: '日常记录' };
        const now = new Date();
        const dateStr = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;

        const record = {
            id: Date.now().toString(),
            date: dateStr,
            type: this.data.newRecordType,
            title: mapTitle[this.data.newRecordType],
            content: this.data.newRecordContent
        };

        this.setData({
            records: [record, ...this.data.records],
            showGrowthModal: false
        });
        this.updateDisplayRecords();

        wx.showToast({ title: '记录成功', icon: 'success' });
    }
})
