package com.cyksj.service.template.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.constant.TemplateEnum;
import com.cyksj.common.util.Jsons;
import com.cyksj.common.util.StringUtil;
import com.cyksj.config.WeChatConfig;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.OrderDonTransportMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.gzh.UserGzhRelationMapper;
import com.cyksj.model.dto.WxMpTemplateData;
import com.cyksj.model.dto.WxMpTemplateMessage;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.request.ReqSetLogisticsPost;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.model.views.WxAppTemplateView;
import com.cyksj.service.sms.SmsService;
import com.cyksj.service.template.TemplateCommonService;
import com.cyksj.service.user.UserSysMsgNotifyService;
import com.cyksj.service.wechat.WeChatService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/*
 *项目名: netflix
 *文件名: TemplateCommonServiceImpl
 *创建者: JavaZou
 *创建时间:2023/1/11 9:59
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TemplateCommonServiceImpl implements TemplateCommonService {
	private final EnvCommonService envCommonService;

	private final WeChatService weChatService;

	private final BeanSearcher beanSearcher;

	private final UserGzhRelationMapper userGzhRelationMapper;

	private final WeChatConfig weChatConfig;

	private final UserMapper userMapper;

	private final GoodsDonMapper goodsDonMapper;

	private final OrderDonTransportMapper transportMapper;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	private final SmsService smsService;

	private final UserSysMsgNotifyService userSysMsgNotifyService;

	public void newOderSendMsgByType(OrderDon order, GoodsDon goodsDon, User user, String toPeople, Boolean isCustomer) throws Exception {
		if (!EnvCommonService.active.equals(envCommonService.getEnv())) {
			String openId = toPeople;
			if (StrUtil.isNotBlank(openId)) {
				WxAppTemplateView wxAppTemplateView = null;
				if (isCustomer) {
					wxAppTemplateView = this.getCustomerTemplateView(TemplateEnum.NEW_ORDER_TEMPLATE.getDesc());
				} else {
					wxAppTemplateView = this.getWxAppByUserId(openId, TemplateEnum.NEW_ORDER_TEMPLATE.getDesc());
				}
				if (wxAppTemplateView != null) {
					WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
							.setToUser(openId)
							.setTemplateId(wxAppTemplateView.getTemplateId())
							//TODO
							.setUrl(" ");
					WxMpTemplateMessage.TemplateData data = templateMessage.getData();
					data.setFirst(new WxMpTemplateData("新订单通知！"));
					data.setKeyword1(new WxMpTemplateData(order.getOrderNo()));
					data.setKeyword2(new WxMpTemplateData(String.format("%s服务", goodsDon.getTitle())));
					data.setKeyword3(new WxMpTemplateData(order.getMoney().divide(BigDecimal.valueOf(100)).toString()));
					data.setRemark(new WxMpTemplateData(goodsDon.getType() == 1 && goodsDon.getSecondType() == 1 ? "需要联系客服邀请才可使用，请联系客服" : "点击查看详情"));
					weChatService.sendTemplateMessage(weChatService.getAccessToken(wxAppTemplateView.getAppId()), Jsons.toJson(templateMessage));
				}
			}
		}
	}

	@Override
	public WxAppTemplateView getWxAppByUserId(String openId, String templateMark) {
		UserGzhRelation userGzhRelation = userGzhRelationMapper.selectOne(Wrappers.lambdaQuery(UserGzhRelation.class)
				.eq(UserGzhRelation::getOpenId, openId).last("limit 1"));
		MapBuilder builder = MapUtils.builder()
				.field(WxAppTemplateView::getRemark, templateMark);
		if (userGzhRelation == null) {
			builder.field(WxAppTemplateView::getAppId, weChatConfig.getAppid());
		} else {
			builder.field(WxAppTemplateView::getWxAppId, userGzhRelation.getWxAppId());
		}
		String type;
		if (EnvCommonService.active.equals(envCommonService.getEnv())) {
			type = EnvCommonService.active;
		} else {
			type = EnvCommonService.active_prd;
		}
		builder.field(WxAppTemplateView::getType, type);
		WxAppTemplateView wxAppTemplateView = beanSearcher.searchFirst(WxAppTemplateView.class, builder.build());
		return wxAppTemplateView;
	}

	public WxAppTemplateView getCustomerTemplateView(String templateMark) {
		WxAppTemplateView wxAppTemplateView = beanSearcher.searchFirst(WxAppTemplateView.class, MapUtils.builder()
				.field(WxAppTemplateView::getRemark, templateMark)
				.field(WxAppTemplateView::getAppId, weChatConfig.getAppid())
				.field(WxAppTemplateView::getType, EnvCommonService.active_prd).build());
		return wxAppTemplateView;
	}

	@Override
	public void sendWxGzhQrCodeSuccessMsg(User user) throws Exception {
		if (!EnvCommonService.active.equals(envCommonService.getEnv())) {
			String openId = user.getOpenId();
			if (StrUtil.isNotBlank(openId)) {
				WxAppTemplateView wxAppTemplateView = this.getWxAppByUserId(openId, TemplateEnum.WX_GZH_QR_CODE_LOGIN.getDesc());
				if (wxAppTemplateView != null) {
					String url = String.format("%sauth/weChat?url=%s", envCommonService.getHost(), envCommonService.getDomain());
					WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
							.setToUser(openId)
							.setTemplateId(wxAppTemplateView.getTemplateId())
							.setUrl(url);
					WxMpTemplateMessage.TemplateData data = templateMessage.getData();
					data.setTime3(new WxMpTemplateData(DateUtil.format(DateTime.now(), "yyyy-MM-dd HH:mm:ss")));
					data.setThing17(new WxMpTemplateData(user.getNickname()));
					weChatService.sendTemplateMessage(weChatService.getAccessToken(wxAppTemplateView.getAppId()), Jsons.toJson(templateMessage));
				}
			}
		}
	}

	@Override
	public void sendTransportMsgNotify(OrderDon orderDon, ReqSetLogisticsPost reqSetLogisticsPost, Boolean isReceiveAll) throws Exception {
		if (!EnvCommonService.active.equals(envCommonService.getEnv())) {
			Long userId = orderDon.getUserId();
			User user = userMapper.selectById(userId);
			if (user != null && StrUtil.isNotBlank(user.getOpenId())) {
				String openId = orderDon.getOpenId();
				WxAppTemplateView wxAppTemplateView = this.getWxAppByUserId(openId, TemplateEnum.ORDER_TRANSPORT_TEMPLATE.getDesc());
				if (wxAppTemplateView != null) {
					String url = String.format("%s%s", envCommonService.getDomain(), "order");
					WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
							.setToUser(openId)
							.setTemplateId(wxAppTemplateView.getTemplateId())
							.setUrl(url);
					String msg = isReceiveAll ? "家庭套餐特权已生效，可在我的车票中查看" : "存在待领取权益，点击查看详情";
					GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
					OrderDonTransport transport = transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, reqSetLogisticsPost.getOrderId()).last("limit 1"));
					WxMpTemplateMessage.TemplateData data = templateMessage.getData();
					data.setFirst(new WxMpTemplateData("订单发货通知"));
					data.setKeyword1(new WxMpTemplateData(orderDon.getOrderNo()));
					data.setKeyword2(new WxMpTemplateData(goodsDon.getTitle()));
					data.setKeyword3(new WxMpTemplateData(reqSetLogisticsPost.getCodeCn()));
					data.setKeyword4(new WxMpTemplateData(reqSetLogisticsPost.getTrackingNumber()));
					data.setKeyword5(new WxMpTemplateData(String.format("%s%s%s%s", transport.getProvince(), transport.getCity(), transport.getDistrict(), transport.getAddress())));
					data.setRemark(new WxMpTemplateData(String.format("可复制运单编号查询物流信息\n%s", msg)));
					weChatService.sendTemplateMessage(weChatService.getAccessToken(wxAppTemplateView.getAppId()), Jsons.toJson(templateMessage));
				}
			}
		}
	}

	@Override
	public void emptySendMsgNotify(OrderDon orderDon, String toPeople) throws Exception {
		if (!EnvCommonService.active.equals(envCommonService.getEnv())) {
			String openId = toPeople;
			WxAppTemplateView wxAppTemplateView = this.getCustomerTemplateView(TemplateEnum.EMPTY_TEMPLATE.getDesc());
			if (wxAppTemplateView != null) {
				User u = userMapper.selectById(orderDon.getUserId());
				WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
						.setToUser(openId)
						.setTemplateId(wxAppTemplateView.getTemplateId())
						//TODO
						.setUrl(" ");
				GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
				GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
				WxMpTemplateMessage.TemplateData data = templateMessage.getData();
				data.setFirst(new WxMpTemplateData("空车位通知！"));
				data.setKeyword1(new WxMpTemplateData(orderDon.getOrderNo()));
				data.setKeyword2(new WxMpTemplateData(String.format("%s,%s", goodsDon.getTitle(), goodsDonSku.getSpecVal())));
				data.setKeyword3(new WxMpTemplateData((u == null ? " " : u.getNickname())));
				data.setKeyword4(new WxMpTemplateData(orderDon.getMoney().divide(BigDecimal.valueOf(100)).toString()));
				data.setKeyword5(new WxMpTemplateData(DateUtil.format(orderDon.getCreatedTime(), "yyyy-MM-dd HH:mm:ss")));
				data.setRemark(new WxMpTemplateData("请尽快关联账号信息"));
				weChatService.sendTemplateMessage(weChatService.getAccessToken(wxAppTemplateView.getAppId()), Jsons.toJson(templateMessage));
			}
		}
	}

	@Override
	public void sendAccountTemplateMsg(Account account) throws Exception {
		boolean isPrd = envCommonService.isPrdEnv();
		List<GroupsRelationView> relations = beanSearcher.searchList(GroupsRelationView.class, MapUtils.builder()
				.field(GroupsRelationView::getAccountId, account.getId())
				.field(GroupsRelationView::getStatus, "validity")
				.build());
		if (CollUtil.isEmpty(relations)) {
			return;
		}
		GoodsDon goodsDon = goodsDonMapper.selectById(account.getGoodsId());
		String title = goodsDon != null ? goodsDon.getTitle() : "车票";
		DateTime now = DateTime.now();
		log.info("开始发送账号修改密码模板消息,大小:{}", relations.size());
		Long skuId = relations.get(0).getSkuId();
		userSysMsgNotifyService.recordUserAccountUpdateSysMsg(account.getGoodsId(), skuId, relations, account.getAccount(), goodsDon.getTitle());
		for (GroupsRelationView relation : relations) {
			if (relation.getExpiryTime() == null) {
				continue;
			}
			//账号有效期小于5天的人，不发账号替换/改密码短信提醒
			if (now.after(DateUtil.offsetDay(relation.getExpiryTime(), -5))) {
				continue;
			}
			//去掉GPT过滤平台
			if (Constant.CHANGE_ACCOUNT_PWD_FILTER_GIDS.get(1) == account.getGoodsId()) {
				continue;
			}
			if (relation.getUserId() != 0 && relation.getYhsId() == 0 && isPrd) {
				String msg = String.format(Constant.CHANGE_GROUPS_TRIPS_ACCOUNT, title, account.getAccount());
				smsService.sendSmsToRelationUser(relation.getUserId(), msg);
			}
		}
	}

	@Override
	public void sendUpdateAccountMsgNotify(GroupsRelationView relation) throws Exception {
		if (!EnvCommonService.active.equals(envCommonService.getEnv())) {
			sendUpdateAccountMsg(relation);
		}
	}

	public void sendUpdateAccountMsg(GroupsRelationView relation) throws Exception {
		String url = String.format("%sauth/weChat?url=%syinhe/web/ticket", envCommonService.getHost(), envCommonService.getDomain());
		User user = userMapper.selectById(relation.getUserId());
		if (user != null && StrUtil.isNotBlank(user.getOpenId())) {
			String openId = user.getOpenId();
			WxAppTemplateView wxAppTemplateView = this.getWxAppByUserId(openId, TemplateEnum.PLAT_ACCOUNT_UPDATE_TEMPLATE.getDesc());
			if (wxAppTemplateView != null) {
				WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
						.setToUser(openId)
						.setTemplateId(wxAppTemplateView.getTemplateId())
						.setUrl(url);
				WxMpTemplateMessage.TemplateData data = templateMessage.getData();
				data.setFirst(new WxMpTemplateData(String.format("%s账号%s密码更改提醒", relation.getTitle(), relation.getTripsAccount())));
				data.setKeyword1(new WxMpTemplateData(relation.getTripsPassword()));
				data.setKeyword2(new WxMpTemplateData(DateTime.now().toString("YYYY-MM-mm HH:mm:ss")));
				data.setRemark(new WxMpTemplateData("您的账号密码已经更新，请到我的车票查看，长期用户请选择拼车/年付。\n" +
						"如您不是在公众号购买，请在浏览器登录查看我的车票"));
				try {
					weChatService.sendTemplateMessage(weChatService.getAccessToken(wxAppTemplateView.getAppId()), Jsons.toJson(templateMessage));
				} catch (Exception e) {
					log.info("发送用户:{}车票账号修改密码模板消息错误,errorMsg:{}", user.getId(), StringUtil.getErrorText(e));
				}
			}
		}
	}
}
