/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.feesapi.wxgl.wechatbasicmgt.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.core.dto.Order;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.common.util.GuidGenerator;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.sfgl.entity.YyQfmx;
import com.tofly.feesapi.sfgl.service.YyQfmxService;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.WxMessage;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.WxUser;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.dto.CreateWxMessageDto;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.dto.WxMessagedto;
import com.tofly.feesapi.wxgl.wechatbasicmgt.mapper.WxMessageMapper;
import com.tofly.feesapi.wxgl.wechatbasicmgt.service.WxMessageService;
import com.tofly.feesapi.wxgl.wechatbasicmgt.service.WxUserService;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.YyZjzh;
import com.tofly.feesapi.yhgl.service.IYyZjzhService;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 微信模板消息
 *
 * @author admin
 * @date Tue Jul 04 00:00:00 CST 2023
 */
@Service("wxMessageService")
@Slf4j
public class WxMessageServiceImpl extends ServiceImpl<WxMessageMapper, WxMessage> implements WxMessageService {
    @Autowired
    private YyCblrService cblrService;


    @Autowired
    private YhKhjbxxService yhKhjbxxService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private YyQfmxService yyQfmxService;

    @Autowired
    private IYyZjzhService yyZjzhService;


    /**
     * 生成微信信息
     *
     * @param type
     * @param sscbb
     * @return
     */
    @Transactional
    @Override
    public boolean plScMsg(String type, List<String> sscbb, CreateWxMessageDto dto) {
        if (StringUtil.isEmpty(sscbb)) {
            return false;
        }
        String pch = GuidGenerator.getGuid();
        List<YhKhjbxx> lstKhjbxx = yhKhjbxxService.list(new QueryWrapper<YhKhjbxx>()
                .in("sscbb", sscbb)
                .and(i -> i.eq("yhzt", "1"))
        );
        if (StringUtil.isNotNull(lstKhjbxx)) {
            //  smsMessage=null;
            lstKhjbxx.forEach(yhKhjbxx -> {

                List<WxUser> wxUserList = wxUserService.list(
                        new QueryWrapper<WxUser>()
                                .eq("YHBH", yhKhjbxx.getYhbh())
                                .eq("WXBDBZ", "1")
                );
                if (CollectionUtil.isEmpty(wxUserList)) {
                    log.info("未获取到绑定得微信用户信息。");
                    return;
                }
                wxUserList.forEach(wxUser -> {
                    if (wxUser == null) {
                        return;
                    }
                    WxMessage smsMessage = new WxMessage();
                    smsMessage.setId(GuidGenerator.getGuid());
                    smsMessage.setMsgType(type);
                    if (StringUtil.isEmpty(wxUser.getOpenid())) {
                        return;
                    }

                    smsMessage.setOpenid(wxUser.getOpenid());

                    String wxmsg = "";
                    String typeName = "";

                    //检查欠费
                    List<YyQfmx> list = null;

                    BigDecimal syje = BigDecimal.ZERO;
                    YyZjzh zjzh = yyZjzhService.getById(yhKhjbxx.getYhbh());
                    if (zjzh != null) {
                        syje = zjzh.getNbsyje();
                    }
                    switch (type) {
                        case "02":
                            typeName = "月度水费通知";
                            Date now = new Date();
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            String dateString = dateFormat.format(now);

                            wxmsg = String.format("%s至%s", dateString, dateString);

                            list = yyQfmxService.lambdaQuery().eq(YyQfmx::getSfbz, "0")
                                    .eq(YyQfmx::getChbz, "0")
                                    .eq(YyQfmx::getYhbh, yhKhjbxx.getYhbh())
                                    .eq(YyQfmx::getSfbc, "0")
                                    .ge(YyQfmx::getYsje, 0)
                                    .ne(YyQfmx::getYsje, 0)
                                    .between(YyQfmx::getCwrq, dto.getCwrqStart(), dto.getCwrqEnd())
                                    .list();

                            smsMessage.setFirst(typeName);
                            smsMessage.setKeyword1(yhKhjbxx.getYhxm());
                            smsMessage.setKeyword2(yhKhjbxx.getYhbh());
                            smsMessage.setKeyword3(yhKhjbxx.getYhdz());

                            smsMessage.setKeyword4(wxmsg);

                            //检查欠费
                            if (CollectionUtil.isEmpty(list)) {
                                log.info(typeName + " " + yhKhjbxx.getYhbh() + "为空.");
                                return;
                            }

                            //合计欠费
                            BigDecimal sumqfje = list.stream().map(YyQfmx::getYsje).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal sumqfsl = list.stream().map(YyQfmx::getYssl).reduce(BigDecimal.ZERO, BigDecimal::add);


                            if (sumqfje != null && syje != null && sumqfje.compareTo(syje) > 0) {
                                smsMessage.setKeyword5(sumqfsl.toString() + "吨");
                                smsMessage.setKeyword6(sumqfje.setScale(2, RoundingMode.DOWN).toString() + "元");
                                smsMessage.setPch(pch);
                                smsMessage.setSendState("0");
                                smsMessage.setAddDate(new Date());
                                smsMessage.setUserid(SecurityUtils.getUserId());
                                this.save(smsMessage);
                            }
                            break;

                        case "15":
                            typeName = "欠费停水通知";
                            list = yyQfmxService.lambdaQuery().eq(YyQfmx::getSfbz, "0")
                                    .eq(YyQfmx::getChbz, "0")
                                    .eq(YyQfmx::getYhbh, yhKhjbxx.getYhbh())
                                    .eq(YyQfmx::getSfbc, "0")
                                    .ge(YyQfmx::getYsje, 0)
                                    .ne(YyQfmx::getYsje, 0)
                                    .list();
                            if (CollectionUtil.isEmpty(list)) {
                                log.info(typeName + " " + yhKhjbxx.getYhbh() + "为空.");
                                return;
                            }
                            smsMessage.setFirst(typeName);
                            smsMessage.setKeyword1(yhKhjbxx.getYhbh());
                            smsMessage.setKeyword2(yhKhjbxx.getYhxm());
                            //检查欠费
                            sumqfje = list.stream().map(YyQfmx::getYsje).reduce(BigDecimal.ZERO, BigDecimal::add);

                            if (sumqfje != null && syje != null && sumqfje.compareTo(syje) > 0) {
                                smsMessage.setKeyword3(sumqfje.setScale(2, RoundingMode.DOWN).toString());
                                smsMessage.setKeyword4(syje.setScale(2, RoundingMode.DOWN).toString());
                                smsMessage.setPch(pch);
                                smsMessage.setSendState("0");
                                smsMessage.setAddDate(new Date());
                                smsMessage.setUserid(SecurityUtils.getUserId());
                                this.save(smsMessage);
                            }
                            break;
                    }

                });
            });
        }
        return true;
    }

    /**
     * 发送微信欠费信息(单个)
     *
     * @param type
     * @param pch
     * @param msg
     * @return
     */
    @Transactional
    @Override
    public boolean plUpdateMsg(String type, String pch, String msg) {
        if (StringUtil.isEmpty(pch)) {
            throw new FeesException("批次号不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }

        List<WxMessage> lstMessage = this.list(
                new QueryWrapper<WxMessage>()
                        .eq("pch", pch)
                        .eq("send_state", "0")
        );
        if (CollectionUtil.isEmpty(lstMessage)) {
            throw new FeesException("批次号未查询出相关数据！", FeesErrorCode.BUSINESS_ERROR);
        }

        lstMessage.forEach(wxMessage -> {
            if (wxMessage.getMsgType().equals("02")) {//月度水费通知
                if (!StringUtil.isEmpty(msg)) {
                    wxMessage.setKeyword4(msg);
                }
            }
            if (StringUtil.isNotEmpty(type) && type.equals("send")) {
                wxMessage.setSendState("1");
            }
            this.updateById(wxMessage);
        });
        return true;
    }

    /**
     * 发送微信欠费信息(单个)
     *
     * @param type
     * @param id
     * @param msg
     * @return
     */
    @Override
    public boolean plUpdateMsgOne(String type, String id, String msg) {
        if (StringUtil.isEmpty(id)) {
            throw new FeesException("id不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }

        WxMessage wxMessage = this.getById(id);
        if (StringUtil.isNull(wxMessage)) {
            throw new FeesException("未查询出相关数据！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (!"0".equals(wxMessage.getSendState())) {
            throw new FeesException("该信息处于发送中或已发送！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (wxMessage.getMsgType().equals("02")) {//月度水费通知
            if (!StringUtil.isEmpty(msg)) {
                wxMessage.setKeyword4(msg);
            }
        }
        if (StringUtil.isNotEmpty(type) && type.equals("send")) {
            wxMessage.setSendState("1");
        }
        return this.updateById(wxMessage);
    }

    @Override
    public PageResult<WxMessage> getWxMessagePage(PageDto pageDto, WxMessagedto wxMessagedto) {
        List<Order> orders = pageDto.getOrders();
        if (orders.size() > 0) {
            orders = orders.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    Order order = new Order();
                    order.setColumn("b.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
        } else {
            orders.add(new Order("pch", true));
            //  orders.add(new Order("ADD_DATE", false));
        }

        pageDto.setOrders(orders);
        if (StringUtil.isNotEmpty(wxMessagedto.getUserid())) {
            wxMessagedto.setUserid(SecurityUtils.getUserId().toString());
        }
        return this.baseMapper.getWxMessagePage(pageDto, wxMessagedto).toVo();
    }


    @Override
    public boolean deleteByPch(String pch) {
        boolean isDeleted = false;
        if (StringUtil.isEmpty(pch)) {
            return false;
        }
        isDeleted = this.remove(new QueryWrapper<WxMessage>().eq("pch", pch).and(w -> w.eq("send_state", "0")));
        if (isDeleted) {
            log.info("删除微信消息成功.");
        } else {
            log.info("删除微信消息失败.");
        }
        return isDeleted;
    }


}
