package com.friday.custody.service.basicService.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.dao.AccoBalanceChangeRecordDao;
import com.friday.custody.dto.MsgSendDto;
import com.friday.custody.entity.AccoBalanceChangeRecordEntity;
import com.friday.custody.entity.NotifierInfoEntity;
import com.friday.custody.service.basicService.AccoBalanceChangeRecordService;
import com.friday.custody.service.trustService.htsc.common.HtscConstants;
import com.friday.custody.utils.MailSendUtil;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.friday.custody.common.CustodyContants.*;


@Service("accoBalanceChangeRecordService")
@Slf4j
public class AccoBalanceChangeRecordServiceImpl extends ServiceImpl<AccoBalanceChangeRecordDao, AccoBalanceChangeRecordEntity> implements AccoBalanceChangeRecordService {

    @Autowired
    SubscribeInfoServiceImpl subscribeInfoService;
    @Autowired
    MailSendUtil mailSendUtil;
    @Autowired
    NotifierInfoServiceImpl notifierInfoService;
    @Autowired
    SubscribeFundInfoServiceImpl subscribeFundInfoService;

    private static final int reTryTimes = 2;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AccoBalanceChangeRecordEntity> page = this.page(
                new Query<AccoBalanceChangeRecordEntity>().getPage(params),
                new QueryWrapper<AccoBalanceChangeRecordEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 余额变动-实时提醒
     * @param fundPrdMap
     * @param newAccoBalance
     * @param oldAccoBalance
     * @param admin
     * @param accountTypeCode
     * @param trustNo
     */
    @Override
    public void balanceChangeRemind(Map<String, String> fundPrdMap, BigDecimal newAccoBalance, BigDecimal oldAccoBalance, String admin, String accountTypeCode, String trustNo) {
        if (fundPrdMap != null) {
            String fundCode = fundPrdMap.get("fundCode");
            String fundName = fundPrdMap.get("fundName");
            int mailSendFlag = 0;
            int smsSendFlag = 0;
            //判断是否需要提醒
            Boolean isReminder = subscribeFundInfoService.isReminder(newAccoBalance, admin,
                    trustNo, accountTypeCode, fundCode);
            if (isReminder) {
                //计算出两次值的差值
                BigDecimal subtractValue = newAccoBalance.subtract(oldAccoBalance).setScale(2);
                String accTypeName = HtscConstants.MJ_ACCOUNT_TYPE_CODE.equals(accountTypeCode) ? "募集户" : "托管户";
                String str = subtractValue.compareTo(new BigDecimal(0)) > 0 ? "入账" : "出账";
                // 拼接主题
                String subject = "【" + accTypeName + "余额变动】" + fundName + str + subtractValue.abs().toString() + "元";
                // 邮件内容
                String mailContent = "【华小生】" + subject + "，可前往华小生（" + "<a href=\"https://huatech.htsc.com.cn/helson/home\" target=\"_blank\">" +
                        "https://huatech.htsc.com.cn/helson/home</a>" + "）-私募管理平台查看详情。";
                String smsContent = subject + "，可前往华小生-私募管理平台中查看详情。";
                //查询出该产品订阅的订阅人信息
                List<NotifierInfoEntity> notifierInfoEntities = notifierInfoService.queryByFund(fundCode, admin, accountTypeCode);
                if (notifierInfoEntities != null) {
                    //发送短信,邮件
                    for (NotifierInfoEntity entity : notifierInfoEntities) {
                        //如果配置了统一定时发送，则跳过；由用户设定的时间点的定时任务去发送提醒
                        if (0!=entity.getNotifyType()){
                            continue;
                        }
                        String mailAddress = entity.getEmailAddress();//邮件地址
                        String mobileNo = entity.getMobileNo();//手机号码
                        if (!ObjectUtils.isEmpty(entity.getNoticeMethod())
                                && (entity.getNoticeMethod() == NOTICE_MENTHODS_ALL || entity.getNoticeMethod() == NOTICE_MENTHODS_MAIL)) {
                            if (sendMail(mailAddress, subject, mailContent)) {
                                mailSendFlag = 1;
                            }
                        }
                        if (!ObjectUtils.isEmpty(entity.getNoticeMethod())
                                && (entity.getNoticeMethod() == NOTICE_MENTHODS_ALL || entity.getNoticeMethod() == NOTICE_MENTHODS_SMS)) {
                            if (sendSms(mobileNo, smsContent)) {
                                smsSendFlag = 2;
                            }
                        }

                    }
                }
            }
            //将变动记录插入表中
            AccoBalanceChangeRecordEntity accoBalanceChangeRecordEntity = AccoBalanceChangeRecordEntity.builder()
                    .admin(admin)
                    .accoBalanceAfter(newAccoBalance)
                    .accoBalanceBefore(oldAccoBalance)
                    .updateDate(fundPrdMap.get("updateDate"))
                    .accoTypeCode(accountTypeCode)
                    .bankAcco(fundPrdMap.get("bankAcco"))
                    .fundName(fundName)
                    .fundCode(fundCode)
                    .sendFlag(mailSendFlag + smsSendFlag)
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            baseMapper.insert(accoBalanceChangeRecordEntity);
        }
    }

    public boolean sendMail(String mailAddress, String subject, String mailContent){
        if (StringUtils.isNotBlank(mailAddress)) {
            String[] mailArr = mailAddress.trim().split(";");
            MsgSendDto msgSendDto = MsgSendDto.builder()
                    .subject(subject) //邮件主题
                    .content(mailContent) //邮件内容
                    .emailList(Arrays.asList(mailArr))//接收人邮箱地址
                    .build();
            try {
                for (int i = 0; i < reTryTimes; i++) {
                    Boolean isSendMail = mailSendUtil.sendMail(msgSendDto);
                    if (!isSendMail) {
                        log.error("发送邮件失败:收件人为{},邮件主题为{},邮件内容为{}", mailAddress, subject, mailContent);
                        continue;
                    }
                    return true;
                }
            } catch (Exception e) {
                log.error("募集户,托管户变动提醒发送邮件失败！", e);
            }
        }
        return false;
    }

    public boolean sendSms(String mobileNo, String smsContent){
//        if (StringUtils.isNotBlank(mobileNo)) {
//            String[] mobileNoArr = mobileNo.trim().split(";");
//            List<String> mobileNoList = Arrays.asList(mobileNoArr);
//            // 短信通知
//            SmsMsgDto smsMsgDto = new SmsMsgDto();
//            List<SmsUserPojo> smsUserPojoList = new ArrayList<>();
//            for (String phone : mobileNoList) {
//                smsUserPojoList.add(new SmsUserPojo(phone, "ZZ323472"));
//            }
//            smsMsgDto.setMsg(smsContent);
//            smsMsgDto.setActualWorker("华小生");
//            smsMsgDto.setSmsUsers(smsUserPojoList);
//            smsMsgDto.setWeight(SmsWeightEnum.MID);
//            smsMsgDto.setSendTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
//            try {
//                for (int i = 0; i < reTryTimes; i++) {
//                    DubboResult smsResult = notifyService.doNotify(smsMsgDto);
//                    if (!smsResult.success()) {
//                        log.error("短信发送失败:收件人为{},短信内容为{}", mobileNo, smsContent);
//                        continue;
//                    }
//                    return true;
//                }
//            } catch (Exception e) {
//                log.error("募集户,托管户变动提醒发送短信失败！", e);
//            }
//        }
        return true;
    }
}