package com.yuchen.saas.park.service.listener.property;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.thinkunion.park.service.common.enums.wechat.OfficialTempEnum;
import com.thinkunion.park.service.common.utils.CommonStringUtil;
import com.yuchen.saas.consumer.api.dto.wechat.OfficialTempMessageData;
import com.yuchen.saas.consumer.api.dto.wechat.SendTemplateReqDTO;
import com.yuchen.saas.consumer.api.feign.WeChatOfficialTempClient;
import com.yuchen.saas.manage.system.api.enums.BusinessScopeEnum;
import com.yuchen.saas.manage.system.api.feign.ApplyManageFeignServer;
import com.yuchen.saas.manage.system.api.vo.applet.SaasApplyInfoDataVO;
import com.yuchen.saas.manage.user.api.entity.SaasWechatSubscribeData;
import com.yuchen.saas.manage.user.api.entity.SaasWechatUser;
import com.yuchen.saas.manage.user.api.enums.SubscribeEnum;
import com.yuchen.saas.manage.user.api.feign.ISaasWechatSubscribeDataClient;
import com.yuchen.saas.manage.user.api.feign.IUserClient;
import com.yuchen.saas.park.api.dto.property.*;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class PropertyBillReminderMessageEventListener {
    @Resource
    private IUserClient userClient;
    @Resource
    private ISaasWechatSubscribeDataClient saasWechatSubscribeDataClient;

    @Resource
    private ApplyManageFeignServer applyManageFeignServer;

    @Resource
    private WeChatOfficialTempClient officialTempClient;



    @TransactionalEventListener(fallbackExecution = true)
    public void billReminderMessageSend(PropertyBillReminderMessageDTO dto) {
        if(Func.isEmpty(dto)||Func.isEmpty(dto.getMessageSendDTOS())){
            return;
        }
        List<SendTemplateReqDTO> reqDTOList = new ArrayList<>();
        for (PropertyBillReminderMessageSendDTO item:dto.getMessageSendDTOS()) {
            R<List<SaasWechatUser>> wechatUserListByPhoneList = userClient.getWechatUserListByPhoneList(Arrays.asList(item.getPhone()));
            if (R.isNotSuccess(wechatUserListByPhoneList)||Func.isEmpty(wechatUserListByPhoneList.getData())){
                continue;
            }
            List<String> openIdList = wechatUserListByPhoneList.getData().stream().map(SaasWechatUser::getOpenid).distinct().collect(Collectors.toList());
            if (Func.isEmpty(openIdList)){
                continue;
            }
            for (String openId : openIdList) {
                SaasWechatSubscribeData unionIdDataByOpenId = getUnionIdDataByOpenId(openId);
                if (Func.isEmpty(unionIdDataByOpenId)||Func.isEmpty(unionIdDataByOpenId.getUnionId())){
                    continue;
                }
                List<SendTemplateReqDTO> itemList=sendOccupyMessage(item, unionIdDataByOpenId.getUnionId());
                if(Func.isNotEmpty(itemList)){
                    reqDTOList.addAll(itemList);
                }
            }
        }
        // 发送模板消息
        if (CollUtil.isNotEmpty(reqDTOList)) {
            R<Boolean> result = officialTempClient.sendOfficialTempMessage(reqDTOList);
        }

    }
    private List<SendTemplateReqDTO>  sendOccupyMessage(PropertyBillReminderMessageSendDTO dto, String unionId ){
        if (StrUtil.isBlank(unionId)) {
            return Collections.emptyList();
        }
        R<List<SaasApplyInfoDataVO>> listR = applyManageFeignServer.findApplyInfoDataList(BusinessScopeEnum.PARK.getCode(),dto.getParkId());
        List<SendTemplateReqDTO> reqDTOList = new ArrayList<>();
        if (listR.isSuccess() && CollUtil.isNotEmpty(listR.getData())) {
            for (SaasApplyInfoDataVO saasApplyInfoDataVO : listR.getData()) {
                // 获取到公众号对应的openId
                SaasWechatSubscribeData saasWechatSubscribeData = getOpenIdByUnionIdAndAppId(unionId, saasApplyInfoDataVO.getAppId());
                if (Func.isEmpty(saasWechatSubscribeData)||Func.isEmpty(saasWechatSubscribeData.getOpenId())) {
                    continue;
                }
                // 封装出入场模板消息对象
                String openId = saasWechatSubscribeData.getOpenId();
                SendTemplateReqDTO reqDTO = new SendTemplateReqDTO();
                reqDTO.setOfficialAppId(saasApplyInfoDataVO.getAppId());
                reqDTO.setTouser(openId);
                reqDTO.setTemplateCode(OfficialTempEnum.PROPERTY_BILL_REMINDER_MESSAGE.getTempCode());
                // 跳转小程序
                JSONObject miniProgram = new JSONObject();
                miniProgram.put("appid", saasApplyInfoDataVO.getMiniAppId());
                reqDTO.setMiniprogram(miniProgram);
                // 模板内容
                JSONObject data = new JSONObject();

                data.put("thing3", new OfficialTempMessageData(dto.getCreateBillTypeName()));
                data.put("amount16", new OfficialTempMessageData(CommonStringUtil.formatFenToYuan(dto.getReceivableAmtFen())));
                data.put("time17", new OfficialTempMessageData(dto.getPeriodicCharge()));
                reqDTO.setData(data);
                reqDTOList.add(reqDTO);
            }
        }
        return reqDTOList;
    }

    private SaasWechatSubscribeData getUnionIdDataByOpenId(String openId) {
        // 获取用户对应的unionId
        R<SaasWechatSubscribeData> wechatSubscribeDataByOpenId = saasWechatSubscribeDataClient.getWechatSubscribeDataByOpenId(openId);
        if (R.isNotSuccess(wechatSubscribeDataByOpenId)){
            return null;
        }
        return wechatSubscribeDataByOpenId.getData();
    }

    private SaasWechatSubscribeData getOpenIdByUnionIdAndAppId(String unionId, String appId) {

        R<SaasWechatSubscribeData> wechatSubscribeDataByUnionId= saasWechatSubscribeDataClient.getSubscribeDataByUnionIdAndAppId(unionId, appId);
        if (R.isNotSuccess(wechatSubscribeDataByUnionId)){
            return null;
        }
        if (!SubscribeEnum.SUBSCRIBE.getCode().equals(wechatSubscribeDataByUnionId.getData().getSubscribeFlag())) {
            return null;
        }
        return wechatSubscribeDataByUnionId.getData();

    }

}
