// pages/community/create/index.js
import request from '../../../utils/request';

Page({
    data: {
        content: '',
        images: [],
        canPublish: false, // Only depends on content
        autoFocus: true,
        location: '',
        selectedTopics: [],
        suggestedTopics: ['植物养护', '多肉日记', '绿植分享', '花卉美照', '阳台花园', '新手入门'],
        showImageSheet: false,
        imageSheetItems: [
            { label: '拍照', value: 'camera' },
            { label: '从相册选择', value: 'album' }
        ]
    },

    onLoad() {
        // No draft loading
    },

    onUnload() {
        // No draft saving
    },

    onContentInput(e) {
        const content = e.detail.value;
        this.setData({
            content,
            canPublish: content.trim().length > 0
        });
    },

    showImageSourceSheet() {
        this.setData({ showImageSheet: true });
    },

    hideImageSheet() {
        this.setData({ showImageSheet: false });
    },

    onImageSheetSelect(e) {
        const { value } = e.detail.selected;
        this.setData({ showImageSheet: false });

        if (value === 'camera') {
            this.takePhoto();
        } else {
            this.chooseImage();
        }
    },

    chooseImage() {
        const remaining = 9 - this.data.images.length;
        if (remaining <= 0) {
            wx.showToast({ title: '最多9张图片', icon: 'none' });
            return;
        }

        wx.chooseMedia({
            count: remaining,
            mediaType: ['image'],
            sourceType: ['album'],
            success: (res) => {
                const newImages = res.tempFiles.map(f => f.tempFilePath);
                this.setData({
                    images: [...this.data.images, ...newImages]
                });
            }
        });
    },

    takePhoto() {
        if (this.data.images.length >= 9) {
            wx.showToast({ title: '最多9张图片', icon: 'none' });
            return;
        }

        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            camera: 'back',
            success: (res) => {
                const newImage = res.tempFiles[0].tempFilePath;
                this.setData({
                    images: [...this.data.images, newImage]
                });
            }
        });
    },

    removeImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = [...this.data.images];
        images.splice(index, 1);
        this.setData({ images });
    },

    showImageMenu(e) {
        const index = e.currentTarget.dataset.index;
        wx.showActionSheet({
            itemList: ['设为封面', '删除'],
            success: (res) => {
                if (res.tapIndex === 0) {
                    // Move to first position
                    const images = [...this.data.images];
                    const [img] = images.splice(index, 1);
                    images.unshift(img);
                    this.setData({ images });
                    wx.showToast({ title: '已设为封面', icon: 'success' });
                } else if (res.tapIndex === 1) {
                    this.removeImage({ currentTarget: { dataset: { index } } });
                }
            }
        });
    },

    chooseLocation() {
        wx.chooseLocation({
            success: (res) => {
                this.setData({ location: res.name || res.address });
            },
            fail: () => {
                // User cancelled or no permission
            }
        });
    },

    toggleTopic(e) {
        const topic = e.currentTarget.dataset.topic;
        const hashtag = `#${topic} `;
        let { content, selectedTopics } = this.data;

        if (selectedTopics.includes(topic)) {
            // Remove topic and hashtag from content
            selectedTopics = selectedTopics.filter(t => t !== topic);
            content = content.replace(hashtag, '');
        } else {
            if (selectedTopics.length >= 3) {
                wx.showToast({ title: '最多选择3个话题', icon: 'none' });
                return;
            }
            // Add topic and insert hashtag into content
            selectedTopics.push(topic);
            content = content + hashtag;
        }

        this.setData({
            selectedTopics,
            content,
            canPublish: content.trim().length > 0
        });
    },

    handleCancel() {
        wx.navigateBack();
    },

    async handlePublish() {
        if (!this.data.content || !this.data.content.trim()) {
            wx.showToast({ title: '请输入内容', icon: 'none' });
            return;
        }

        wx.showLoading({ title: '发布中...', mask: true });

        try {
            // 1. Upload Images
            const ossIds = [];
            const images = this.data.images;

            if (images.length > 0) {
                const uploadPromises = images.map(filePath => {
                    return request.upload(filePath).then(res => {
                        // Res structure: { file: { id: "...", url: "..." } }
                        return res && res.file ? res.file.id : null;
                    });
                });

                const uploadedIds = await Promise.all(uploadPromises);

                uploadedIds.forEach(id => {
                    if (id) ossIds.push(id);
                });

                if (images.length > 0 && ossIds.length === 0) {
                    throw new Error('图片上传失败');
                }
            }

            // 2. Publish Post
            // Title is removed from UI. Using content snippet or default title.
            const content = this.data.content.trim();
            const title = content.length > 20 ? content.substring(0, 20) + '...' : content;

            const payload = {
                title: title || '新动态', // Fallback title
                content: content,
                location: this.data.location || '',
                ossIds: ossIds
            };

            await request.post('/post/publish', payload);

            wx.hideLoading();
            wx.showToast({ title: '发布成功', icon: 'success' });

            // Refresh previous page
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.onRefresh) {
                prevPage.onRefresh();
            }

            setTimeout(() => {
                wx.navigateBack();
            }, 1000);

        } catch (err) {
            wx.hideLoading();
            console.error('Publish failed', err);
            wx.showToast({ title: '发布失败', icon: 'none' });
        }
    }
})
