import { $http } from '../config/https';
import Cache from './cache';

/**
 * 计算日期字符串 (YYYY-MM-DD)
 */
function formatDate(date) {
    var y = date.getFullYear();
    var m = String(date.getMonth() + 1).padStart(2, '0');
    var d = String(date.getDate()).padStart(2, '0');
    return y + '-' + m + '-' + d;
}

/**
 * 获取未读消息列表
 * 接口文档：MY_MiniApp_Doctor_H5/docs/文档.md (code: 04180005)
 *
 * @param {Object} opts
 * @param {string} [opts.messageEventCode='ALL'] 消息事件代码
 * @param {string} [opts.messageStatusCode='U'] 消息状态代码（U=未读, ALL=全部）
 * @param {number} [opts.currentPage=1] 当前页
 * @param {number} [opts.pageSize=20] 每页条数
 * @param {function} [opts.success] 成功回调 ({ list, total })
 * @param {function} [opts.fail] 失败回调 (res)
 */
function fetchUnreadMessages(opts) {
    opts = opts || {};
    var userData = Cache.get('userData');
    if (!userData || !userData.userID) {
        return;
    }

    // 日期范围：最近7天
    var today = new Date();
    var from = new Date(today);
    from.setDate(today.getDate() - 6);

    var data = {
        params: [
            {
                userID: userData.userID,
                messageEventCode: opts.messageEventCode || 'ALL',
                eventImportCode: 'ALL',
                messageStatusCode: opts.messageStatusCode || 'U',
                admDateFrom: '', //  formatDate(from)
                admDateTo: '', //  formatDate(today)
            }
        ],
        pagination: [
            {
                pageSize: opts.pageSize || 50,
                currentPage: opts.currentPage || 1
            }
        ]
    };

    $http.post(
        'urlDeault',
        {},
        {
            code: '04180005',
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    var result = res.result || {};
                    var list = result.MessageRecordArr || [];
                    var total = result.total || 0;
                    if (opts.success) {
                        opts.success({ list: list, total: total });
                    }
                } else if (opts.fail) {
                    opts.fail(res);
                }
            }
        },
        { error: 'Y' }
    );
}

/**
 * 标记消息为已读
 * 接口 code: 04180007
 * @param {string} receiveID 消息接收ID
 * @param {function} [opts.success] 成功回调
 */
function markAsRead(receiveID, opts) {
    opts = opts || {};
    var userData = Cache.get('userData');
    if (!userData || !userData.userID) return;

    var data = {
        params: [{ receiveID: receiveID }]
    };

    $http.post(
        'urlDeault',
        {},
        {
            code: '04180007',
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    if (opts.success) opts.success(res);
                }
            }
        },
        { error: 'Y' }
    );
}

/**
 * 根据未读总数更新消息 tab 红点
 * @param {number} total 未读消息总数
 */
function updateMessageRedDot(total) {
    try {
        // 消息 Tab 暂时隐藏，避免未读消息红点显示在当前索引 1 的“我的”Tab 上。
        uni.hideTabBarRedDot({ index: 1 });

        /* 恢复消息 Tab 后，取消以下注释以恢复未读红点展示逻辑。
        if (total > 0) {
            uni.showTabBarRedDot({ index: 1 });
        } else {
            uni.hideTabBarRedDot({ index: 1 });
        }
        */
    } catch (e) {
        console.warn('[unreadMessage] updateMessageRedDot failed:', e);
    }
}

export default {
    fetchUnreadMessages: fetchUnreadMessages,
    markAsRead: markAsRead,
    updateMessageRedDot: updateMessageRedDot
};
