// pages/chat/chat.js
import {
  goto_camera,
} from '../../utils.js'

const app = getApp();

Page({

    /**
     * Page initial data
     */
    data: {
        show_modal: '',
        prompt: [],
        response: [],
        messages: [], // Store chat history
        currentMessage: '', // Current input
        isLoading: false, // Loading state
        sessionId: null, // Session ID for chat
        welcome_response: [
            {
                type: 'text',
                content: '欢迎使用徵象AI客服！我是您的智能防伪验证助手，可以帮您解答关于产品验证、防伪技术等问题。'
            },
            {
                type: 'text',
                content: '您可以向我提问任何关于产品验证、防伪技术的问题，或者点击下方按钮开启AI验证。'
            },
        ],
        prompt_message_verify_result: [
            {
                type: 'text',
                content: '查看验证结果'
            },
        ],
    },

    /**
     * Lifecycle function--Called when page load
     */
    onLoad(options) {
        this.setData({
            serial_code: options.serial_code,
            verify_time: options.time || new Date().toLocaleString(),
            sessionId: this.generateSessionId(),
        });

        // Add welcome message to chat history
        this.addMessageToHistory('assistant', '欢迎使用徵象AI客服！我是您的智能防伪验证助手，可以帮您解答关于产品验证、防伪技术等问题。请随时向我提问！');

        if (options.serial_code) {
            this.show_verify_result(true);
        } else {
            this.show_welcome_response();
        }
    },

    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady() {

    },

    /**
     * Lifecycle function--Called when page show
     */
    onShow() {

    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide() {

    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload() {

    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh() {

    },

    /**
     * Called when page reach bottom
     */
    onReachBottom() {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage() {

    },
    
    goto_camera() {
        goto_camera(true, "ai_chat_mode=1");
    },

    show_service() {
        this.setData({
            show_modal: 'service',
        })
    },

    show_channel() {
        this.setData({
            show_modal: 'channel',
        })
    },
    hide_modal() {
        console.log('hide_modal');
        this.setData({
            show_modal: '',
        })
    },
    show_verify_tech() {
        this.set_content({
            prompt: [
                {
                    type: 'text',
                    content: '这个验证结果可信吗？'
                },
            ],
            response: [
                {
                    type: 'text',
                    content: '本次验证使用「Al图像识别+微米级特征对比」T4.2.2模型',
                    classes: 'margin-bottom-10',
                },
                {
                    type: 'text',
                    content: '更新时间:2025年2月27日',
                    classes: 'secondary',
                },
                {
                    type: 'text',
                    content: '1.微观特征捕捉:系统以0.1mm精度扫描二维码的30+项微观特征'
                },
                {
                    type: 'text',
                    content: '2.加密特征匹配:比对云端预存的特征图像代码,误差率万分之一'
                },
                {
                    type: 'text',
                    content: '若对验证结果有疑虑,可通过人工客服通道咨询'
                },
                {
                    type: 'splitline',
                },
                {
                    type: 'text',
                    content: '你可能会问:'
                },
                {
                    type: 'suggestion',
                    title: '重看验证结果',
                    onclick: () => {
                        this.show_verify_result(false);
                    }
                },
                {
                    type: 'suggestion',
                    title: '这个产品怎么样?',
                    onclick: () => {
                        this.show_product_details();
                    }
                },
                {
                    type: 'suggestion',
                    title: '有什么福利活动吗?',
                    onclick: () => {
                        this.show_promotions();
                    }
                }
            ]
        })
    },
    show_verify_result(is_first_time) {
        var serial_code = this.data.serial_code || "";
        var resp = [
            {
                type: 'text',
                content: '正在生成您的专属验真档案...'
            },
            {
                type: 'text',
                content: '验真结论:',
                classes: 'margin-bottom-10',
            },
            {
                type: 'text',
                content: '正品认证通过!',
                mark: 'tick',
            },
            {
                type: 'text',
                content: '经系统比对,您扫描的【徵象AI体验码】产品二维码为官方认证正品,可放心使用。'
            },
            {
                type: 'text',
                content: '验证编码: ' + serial_code,
                classes: 'margin-bottom-10 link',
                onclick: () => {
                    wx.navigateTo({
                        url: '/pages/productinfo/productinfo?serial_code=' + serial_code,
                    });
                }
            },
            {
                type: 'text',
                content: '验证时间: ' + this.data.verify_time,
            },
            {
                type: 'splitline',
            },
            {
                type: 'text',
                classes: 'secondary',
                content: '你可能会问:'
            },
            {
                type: 'suggestion',
                title: '这个验证结果可信吗?',
                onclick: () => {
                    this.show_verify_tech();
                }
            },
            {
                type: 'suggestion',
                title: '这个产品怎么样?',
                onclick: () => {
                    this.show_product_details();
                }
            },
            {
                type: 'suggestion',
                title: '有什么福利活动吗?',
                onclick: () => {
                    this.show_promotions();
                }
            },
        ]
        var prompt = is_first_time ? [] : [{
            type: 'text',
            content: '查看验证结果'
        }];
        this.set_content({
            prompt: prompt,
            response: resp,
        })
    },
    show_welcome_response() {
        this.set_content({
            prompt: [],
            response: this.data.welcome_response,
        })
    },
    show_product_details() {
        var resp = [
            {
                type: 'text',
                content: '微象AI是由「广州市诚投科技有限公司」开发的AI驱动的智能防伪平台。'
            },
            {
                type: 'text',
                content: '通过「多模态特征识别」构建新一代防伪验证体系,实现从物理防伪到数字认证的全链路保护。系统采用ISO 12931国际防伪标准,已获取国家发明专利(证书编号:CN 115222000 B)。'
            },
            {
                type: 'text',
                content: '应用场景',
                classes: 'margin-bottom-10 bold',
            },
            {
                type: 'text',
                content: '1.商品防伪',
                classes: 'margin-bottom-10 bold',
            },
            {
                type: 'text',
                content: '2.证件安全验证',
                classes: 'margin-bottom-10 bold',
            },
            {
                type: 'text',
                content: '3.工业品防伪',
                classes: 'bold',
            },
            {
                type: 'splitline',
            },
            {
                type: 'text',
                content: '你可能会问:',
                classes: 'secondary',
            },
            {
                type: 'suggestion',
                title: '重看验证结果',
                onclick: () => {
                    this.show_verify_result(false);
                }
            },
            {
                type: 'suggestion',
                title: '这个验证结果可信吗?',
                onclick: () => {
                    this.show_verify_tech();
                }
            },
            {
                type: 'suggestion',
                title: '有什么福利活动吗?',
                onclick: () => {
                    this.show_promotions();
                }
            }
        ]
        this.set_content({
            prompt: [{
                type: 'text',
                content: '这个产品怎么样'
            }],
            response: resp,
        })
    },
    show_promotions() {
        var resp = [
            {
                type: 'text',
                content: '感谢您选择正品!为保障权益,建议:'
            },
            {
                type: 'text',
                content: '·关注品牌公众号',
                classes: 'margin-bottom-10',
            },
            {
                type: 'text',
                content: '·定期访问「会员中心」查看产品溯源信息',
                classes: 'margin-bottom-10',
            },
            {
                type: 'text',
                content: '·参与【正品守护计划】赢取专属福利'
            },
            {
                type: 'text',
                content: '若发现异常验证结果,请立即通过官方客服通道举报'
            },
            {
                type: 'splitline',
            },
            {
                type: 'text',
                content: '你可能会问:',
                classes: 'secondary',
            },
            {
                type: 'suggestion',
                title: '重看验证结果',
                onclick: () => {
                    this.show_verify_result(false);
                }
            },
            {
                type: 'suggestion',
                title: '这个产品怎么样?',
                onclick: () => {
                    this.show_product_details();
                }
            },
            {
                type: 'suggestion',
                title: '这个验证结果可信吗?',
                onclick: () => {
                    this.show_verify_tech();
                }
            }
        ]
        this.set_content({
            prompt: [{
                type: 'text',
                content: '有什么福利活动吗?'
            }],
            response: resp,
        })
    },
    set_content({prompt, response}) {
        this.setData({
            prompt: prompt,
            response: response,
        })
        this.selectComponent('#response').restart_content_output();
        var x = this.selectComponent('#prompt');
        if (x) {
            x.restart_content_output();
        }
    },

    // New methods for AI chat integration
    generateSessionId() {
        return 'session_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11);
    },

    addMessageToHistory(role, content) {
        const messages = this.data.messages;
        messages.push({
            role: role,
            content: content,
            timestamp: new Date(),
        });
        this.setData({
            messages: messages,
        });
    },

    onInputChange(e) {
        this.setData({
            currentMessage: e.detail.value,
        });
    },

    async sendMessage() {
        const message = this.data.currentMessage.trim();
        if (!message || this.data.isLoading) {
            return;
        }

        // Clear input
        this.setData({
            currentMessage: '',
            isLoading: true,
        });

        // Add user message to history
        this.addMessageToHistory('user', message);

        // Show user message in UI
        this.set_content({
            prompt: [{
                type: 'text',
                content: message,
            }],
            response: [{
                type: 'text',
                content: '正在思考中...',
            }],
        });

        try {
            // Call AI chat API
            const response = await this.callAIChatAPI(message);

            // Add AI response to history
            this.addMessageToHistory('assistant', response);

            // Show AI response in UI
            this.set_content({
                prompt: [{
                    type: 'text',
                    content: message,
                }],
                response: [{
                    type: 'text',
                    content: response,
                }],
            });
        } catch (error) {
            console.error('AI Chat Error:', error);
            const errorMessage = '抱歉，我遇到了一些技术问题。请稍后再试，或联系技术支持。';
            this.addMessageToHistory('assistant', errorMessage);

            this.set_content({
                prompt: [{
                    type: 'text',
                    content: message,
                }],
                response: [{
                    type: 'text',
                    content: errorMessage,
                }],
            });
        } finally {
            this.setData({
                isLoading: false,
            });
        }
    },

    callAIChatAPI(message) {
        return new Promise((resolve, reject) => {
            wx.request({
                url: app.globalData.server_url + '/api/v1/ai-chat/',
                method: 'POST',
                data: {
                    message: message,
                    session_id: this.data.sessionId,
                    chat_type: 'platform',
                },
                header: {
                    'content-type': 'application/json',
                },
                success: (res) => {
                    if (res.statusCode === 200 && res.data.response) {
                        // Update session ID if provided
                        if (res.data.session_id) {
                            this.setData({
                                sessionId: res.data.session_id,
                            });
                        }
                        resolve(res.data.response);
                    } else {
                        reject(new Error(res.data.error || 'Unknown error'));
                    }
                },
                fail: (error) => {
                    reject(error);
                }
            });
        });
    },
})