package shop.alien.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeNotice;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.store.service.ArrivalReminderNoticeService;
import shop.alien.util.type.LifeNoticeUtil;

/**
 * 到店提醒用户站内通知：独立实现，便于维护与测试
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ArrivalReminderNoticeServiceImpl implements ArrivalReminderNoticeService {

    private static final String TITLE = "到店提醒";
    private static final int NOTICE_TYPE_ORDER = 2;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    @Override
    public boolean sendArrivalReminderNotice(String userPhone, Integer orderId, Integer businessOrderId,
                                             Integer reservationId, String startTimeRaw,
                                             String storeName, String tableNumbers) {
        if (StringUtils.isBlank(userPhone) || orderId == null) {
            return false;
        }
        String phone = userPhone.trim();
        String hm = extractHourMinute(startTimeRaw);
        String shop = StringUtils.isNotBlank(storeName) ? storeName.trim() : "未知店铺";
        String tables = StringUtils.isNotBlank(tableNumbers) ? tableNumbers.trim() : "未知桌号";
        String message = "您在" + hm + "预订了" + shop + tables + "的桌位,请您及时到店";

        try {
            JSONObject ctx = new JSONObject();
            ctx.put("message", message);
            ctx.put("orderId", orderId);
            ctx.put("reservationId", reservationId);

            LifeNotice notice = new LifeNotice();
            notice.setSenderId("system");
            notice.setReceiverId("user_" + phone);
            notice.setBusinessId(businessOrderId);
            notice.setTitle(TITLE);
            notice.setContext(ctx.toJSONString());
            notice.setNoticeType(NOTICE_TYPE_ORDER);
            notice.setIsRead(0);
            lifeNoticeUtil.fillUserTypeAndRefId(notice);
            lifeNoticeMapper.insert(notice);
            log.info("到店提醒站内通知已写入，orderId={}, receiverId=user_{}", orderId, phone);
            return true;
        } catch (Exception e) {
            log.error("到店提醒站内通知写入失败，orderId={}", orderId, e);
            return false;
        }
    }

    /**
     * 从预约开始时间解析 HH:mm；无法解析时返回「未知时间」
     */
    private static String extractHourMinute(String startTimeRaw) {
        if (StringUtils.isBlank(startTimeRaw)) {
            return "未知时间";
        }
        String s = startTimeRaw.trim();
        int space = s.lastIndexOf(' ');
        if (space >= 0 && space + 1 < s.length()) {
            String tail = s.substring(space + 1).trim();
            if (tail.length() >= 5 && tail.charAt(2) == ':') {
                return tail.substring(0, 5);
            }
            return tail.length() > 5 ? tail.substring(0, 5) : tail;
        }
        return s.length() >= 5 ? s.substring(0, 5) : s;
    }
}
