package com.seer.teach.mp.admin.service;

import cn.hutool.core.collection.CollectionUtil;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.BeanToMapConverter;
import com.seer.teach.mall.api.MallOrderApi;
import com.seer.teach.mall.api.resp.OrderDTO;
import com.seer.teach.mp.admin.controller.req.MpTemplateMessageReq;
import com.seer.teach.mp.entity.MpTemplateMessageEntity;
import com.seer.teach.mp.factory.MpServiceFactory;
import com.seer.teach.mp.service.IMpTemplateMessageService;
import com.seer.teach.mp.service.dto.MpTemplateMessageDTO;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class AdminTemplateMessageService {

    @Resource
    private MallOrderApi mallOrderApi;

    @Resource
    private IMpTemplateMessageService mpTemplateMessageService;

    @Resource
    private MpServiceFactory mpServiceFactory;

    @Resource
    private UserInfoServiceApi userInfoServiceApi;

    /**
     * 发送模板消息
     */
    public void sendTemplateMessage(MpTemplateMessageReq request) {
        if(CollectionUtil.isEmpty(request.getUserIds()) && CollectionUtil.isEmpty(request.getGroupIds())){
            throw new CommonException(ResultCodeEnum.MESSAGE_GROUP_USER_NON_EMPTY);
        }
        OrderDTO order = mallOrderApi.getOrder(request.getOrderId());
        AssertUtils.notNull(order, ResultCodeEnum.ORDER_NOT_FOUND);

        UserInfoDTO userInfoDTO = userInfoServiceApi.getById(order.getUserId());
        if(Objects.nonNull(userInfoDTO)){
            order.setConsignee(getUserName(userInfoDTO));
        }
        Map<String, Object> data = BeanToMapConverter.toFlatMap(order);

        MpTemplateMessageDTO mpTemplateMessageDTO = getMpTemplateMessageDTO(request, data, order);

        mpTemplateMessageService.sendTemplateMessage(mpTemplateMessageDTO);

    }

    private String getUserName(UserInfoDTO userInfoDTO){
        if(StringUtils.hasText(userInfoDTO.getRealName())){
            return userInfoDTO.getRealName();
        }
        if(StringUtils.hasText(userInfoDTO.getNickName())){
            return userInfoDTO.getNickName();
        }
        return userInfoDTO.getUserName();
    }

    /**
     * 获取所有模板
     * @return 微信模板列表
     */
    public List<WxMpTemplate> getAllPrivateTemplate(String appId){
        WxMpTemplateMsgService wxMpTemplateMsgService = mpServiceFactory.getWxMpTemplateMsgService(appId);
        try {
            return wxMpTemplateMsgService.getAllPrivateTemplate();
        } catch (WxErrorException e) {
            log.error(e.getMessage(),e);
            return Collections.emptyList();
        }
    }

    /**
     * 获取模板消息历史
     *
     * @param businessId 业务ID
     * @return 模板消息历史
     */
    public List<MpTemplateMessageEntity> getTemplateMessageHistory(String businessId){
        return mpTemplateMessageService.getTemplateMessageHistory(businessId);
    }

    private MpTemplateMessageDTO getMpTemplateMessageDTO(MpTemplateMessageReq request, Map<String, Object> data, OrderDTO order) {
        MpTemplateMessageDTO mpTemplateMessageDTO = new MpTemplateMessageDTO();
        mpTemplateMessageDTO.setData(data);
        mpTemplateMessageDTO.setUserIds(request.getUserIds());
        mpTemplateMessageDTO.setGroupIds(request.getGroupIds());
        mpTemplateMessageDTO.setTemplateId(request.getTemplateId());
        mpTemplateMessageDTO.setAppId(request.getAppId());
        mpTemplateMessageDTO.setNotifyType(request.getNotifyType());
        mpTemplateMessageDTO.setBusinessId(order.getId().toString());
        mpTemplateMessageDTO.setUrl(request.getUrl());
        mpTemplateMessageDTO.setMiniProgramAppId(request.getMiniProgramAppId());
        mpTemplateMessageDTO.setMiniProgramPagePath(request.getMiniProgramPagePath());
        return mpTemplateMessageDTO;
    }

}