package com.yunzhi.marketing.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.service.IMiniAppService;
import com.yunzhi.marketing.service.ISysOrgParamsService;
import com.yunzhi.marketing.service.ITaMiniFormidsService;
import com.yunzhi.marketing.service.ITaPersonMessageRuleService;
import com.yunzhi.marketing.common.*;
import com.yunzhi.marketing.entity.*;
import com.yunzhi.marketing.mapper.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MiniAppServiceImpl implements IMiniAppService {

    @Autowired
    TaMiniappQrcodeMapper taMiniappQrcodeMapper;

    @Autowired
    TaMiniFormidsMapper taMiniFormidsMapper;

    @Autowired
    ITaMiniFormidsService taMiniFormidsService;

    @Autowired
    TaMiniappMapper taMiniappMapper;

    @Autowired
    TaMiniappTemplateMapper taMiniappTemplateMapper;

    @Autowired
    SysSmsSettingMapper sysSmsSettingMapper;

    @Autowired
    ITaPersonMessageRuleService iTaPersonMessageRuleService;

    @Autowired
    ISysOrgParamsService iSysOrgParamsService;

    @Autowired
    WxUtils wxUtils;

    @Autowired
    SMSUtils smsUtils;

    @Override
    public WxMaJscode2SessionResult getSessionInfo(String code, String appid) throws WxErrorException {
        WxMaService wxService = wxUtils.getMiniApp(appid);
        System.out.println(wxService);
        System.out.println(wxService.getUserService());
        return wxService.getUserService().getSessionInfo(code);
    }

    @Override
    public boolean checkUserInfo(String sessionKey, String rawData, String signature, String appid) {
        WxMaService wxService = wxUtils.getMiniApp(appid);
        return wxService.getUserService().checkUserInfo(sessionKey, rawData, signature);
    }

    @Override
    public WxMaUserInfo getUserInfo(String sessionKey, String encryptedData, String iv, String appid) {
        WxMaService wxService = wxUtils.getMiniApp(appid);
        return wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
    }

    @Override
    public WxMaPhoneNumberInfo getPhoneNoInfo(String sessionKey, String encryptedData, String iv, String appid) {
        WxMaService wxService = wxUtils.getMiniApp(appid);
        return wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
    }

    @Override
    public void sendNoticeMessage(TaPerson toUser, String link, String name, String phone, String content, LocalDateTime dt) {
        TaMiniapp miniapp = taMiniappMapper.selectById(toUser.getMiniappId());
        if (null == miniapp) {
            log.error("小程序 {} 不存在", toUser.getMiniappId());
            return;
        }

        // 消息内容类型
        String contentType = CommConstant.MESSAGE_CONTENT_OF_NOTICE;

        // 查询消息类型, 优先选择订阅消息发送
        TaMiniappTemplate tpl = getTplByType(contentType, toUser.getMiniappId());

        boolean isSubscribe = null != tpl && (null == tpl.getIsSubscribe() ? false : tpl.getIsSubscribe());

        // 入库的消息类型使用的是 MESSAGE_TYPE_OF_SOMEWAY, 不能使用真正的类型
        // 因为 通知消息 只注重内容, 不在乎 发送方式
        String messageType = CommConstant.MESSAGE_TYPE_OF_SOMEWAY;

        // 消息发送间隔, -1 代表不限制
        float interval = -1f;

        // 获取系统设置, 单位分钟
        SysOrgParams sysOrgParams = iSysOrgParamsService.getParamByCode(CommConstant.SYSPARAM_NOTICE_MESSAGE_INTERVAL, toUser.getOrgId());
        if (null != sysOrgParams && !StringUtils.isEmpty(sysOrgParams.getParamValue())) {
            interval = Float.parseFloat(sysOrgParams.getParamValue());
        }

        // 获取用户消息发送记录
        TaPersonMessageRule taPersonMessageRule = iTaPersonMessageRuleService.getByPersonAndType(toUser.getPersonId(), messageType, contentType, toUser.getOrgId());
        if (null == taPersonMessageRule) {
            interval = -1f;
        }

        // 如果需要判断间隔
        if (interval > 0 && null != taPersonMessageRule.getLastSendTime()) {
            LocalDateTime now = LocalDateTime.now();
            // 间隔时间
            Duration diff = Duration.between(taPersonMessageRule.getLastSendTime(), now);

            // 统一转换为 秒 比较
            // 如果间隔时间小于设定时间, 就不发送消息
            if ((diff.toMillis() / 1000) < (interval * 60)) {
                log.info("通知消息间隔小于设定值, 不变发送消息");
                return;
            }
        }

        String[] smsParams = {name, miniapp.getName() + "小程序"};
        if (null == tpl) {
            log.error("小程序 {} 不存在 或者 无通知消息模板 {}", toUser.getMiniappId(), contentType);

            // 短信发送
            sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);
        } else {

            if (isSubscribe) {
                String[] data = new String[]{name, phone, content, DateUtils.cutSecond(dt)};
                ResponseBean res = sendSubscribeMessage(tpl, toUser, link, data);
                if (res.getCode() != ResponseBean.CODE_SUCCESS) {
                    // 使用短信发送
                    sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);
                }
            } else {
                List<WxMaTemplateData> data = new ArrayList<>();
                data.add(new WxMaTemplateData("keyword1", name, "#fffff"));
                data.add(new WxMaTemplateData("keyword2", phone, "#fffff"));
                data.add(new WxMaTemplateData("keyword3", content, "#fffff"));
                data.add(new WxMaTemplateData("keyword4", DateUtils.cutSecond(dt), "#fffff"));

                sendMessage(contentType, toUser, link, data);
            }
        }

        // 更新消息发送时间
        iTaPersonMessageRuleService.saveOrUpdateByPersonAndMessage(toUser.getPersonId(), messageType, contentType, toUser.getOrgId());
    }

    @Override
    public void sendHelpMessage(TaPerson toUser, String link, String result, String activityName, LocalDateTime dt) {
        TaMiniapp miniapp = taMiniappMapper.selectById(toUser.getMiniappId());
        if (null == miniapp) {
            log.error("小程序 {} 不存在", toUser.getMiniappId());
            return;
        }

        // 消息内容类型
        String contentType = CommConstant.MESSAGE_CONTENT_OF_HELP;

        TaMiniappTemplate tpl = getTplByType(contentType, toUser.getMiniappId());

        boolean isSubscribe = null != tpl && (null == tpl.getIsSubscribe() ? false : tpl.getIsSubscribe());

        // 消息发送类型
        String messageType = null == tpl ? CommConstant.MESSAGE_TYPE_OF_SMS :
                isSubscribe ? CommConstant.MESSAGE_TYPE_OF_MINIAPP_SUBSCRIBE : CommConstant.MESSAGE_TYPE_OF_MINIAPP_TEMPLATE;

        String[] smsParams = {miniapp.getName() + "小程序-" + activityName};

        if (null == tpl) {
            log.error("小程序 {} 无通知消息模板 {}", toUser.getMiniappId(), contentType);

            // 短信发送
            sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);
        } else {

            if (isSubscribe) {
                String[] data = new String[]{activityName, result, DateUtils.cutSecond(dt)};
                ResponseBean res = sendSubscribeMessage(tpl, toUser, link, data);
                if (res.getCode() != ResponseBean.CODE_SUCCESS) {
                    // 使用短信发送
                    sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);

                    messageType = CommConstant.MESSAGE_TYPE_OF_SMS;
                }
            } else {
                List<WxMaTemplateData> data = new ArrayList<>();
                data.add(new WxMaTemplateData("keyword1", result, "#fffff"));
                data.add(new WxMaTemplateData("keyword2", activityName, "#fffff"));
                data.add(new WxMaTemplateData("keyword3", DateUtils.cutSecond(dt), "#fffff"));
                sendMessage(contentType, toUser, link, data);
            }
        }

        // TODO 写消息发送日志

        // 更新消息发送时间
        iTaPersonMessageRuleService.saveOrUpdateByPersonAndMessage(toUser.getPersonId(), messageType, contentType, toUser.getOrgId());
    }

    @Override
    public void sendGroupMessage(TaPerson toUser, String link, String result, String activityName, LocalDateTime dt) {
        TaMiniapp miniapp = taMiniappMapper.selectById(toUser.getMiniappId());
        if (null == miniapp) {
            log.error("小程序 {} 不存在", toUser.getMiniappId());
            return;
        }

        // 消息内容类型
        String contentType = CommConstant.MESSAGE_CONTENT_OF_GROUP;

        TaMiniappTemplate tpl = getTplByType(contentType, toUser.getMiniappId());

        boolean isSubscribe = null != tpl && (null == tpl.getIsSubscribe() ? false : tpl.getIsSubscribe());

        // 消息发送类型
        String messageType = null == tpl ? CommConstant.MESSAGE_TYPE_OF_SMS :
                isSubscribe ? CommConstant.MESSAGE_TYPE_OF_MINIAPP_SUBSCRIBE : CommConstant.MESSAGE_TYPE_OF_MINIAPP_TEMPLATE;

        String[] smsParams = {miniapp.getName() + "小程序-" + activityName};

        if (null == tpl) {
            log.error("小程序 {} 无通知消息模板 {}", toUser.getMiniappId(), contentType);

            // 短信发送
            sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);
        } else {

            if (isSubscribe) {
                String[] data = new String[]{activityName, result, DateUtils.cutSecond(dt)};
                ResponseBean res = sendSubscribeMessage(tpl, toUser, link, data);
                if (res.getCode() != ResponseBean.CODE_SUCCESS) {
                    // 使用短信发送
                    sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);

                    messageType = CommConstant.MESSAGE_TYPE_OF_SMS;
                }
            } else {
                List<WxMaTemplateData> data = new ArrayList<>();
                data.add(new WxMaTemplateData("keyword1", result, "#fffff"));
                data.add(new WxMaTemplateData("keyword2", activityName, "#fffff"));
                data.add(new WxMaTemplateData("keyword3", DateUtils.cutSecond(dt), "#fffff"));
                sendMessage(contentType, toUser, link, data);
            }
        }

        // TODO 写消息发送日志

        // 更新消息发送时间
        iTaPersonMessageRuleService.saveOrUpdateByPersonAndMessage(toUser.getPersonId(), messageType, contentType, toUser.getOrgId());
    }

    @Override
    public void sendCheckMessage(TaPerson toUser, String link, String name, String result, String programName,
                                 String failReason, String remark, LocalDateTime dt, Boolean isSuccess) {
        TaMiniapp miniapp = taMiniappMapper.selectById(toUser.getMiniappId());
        if (null == miniapp) {
            log.error("小程序 {} 不存在", toUser.getMiniappId());
            return;
        }

        // 消息内容类型
        String contentType = CommConstant.MESSAGE_CONTENT_OF_HOUSE;
        TaMiniappTemplate tpl = getTplByType(contentType, toUser.getMiniappId());
        boolean isSubscribe = null != tpl && (null == tpl.getIsSubscribe() ? false : tpl.getIsSubscribe());
        // 消息发送类型
        String messageType = null == tpl ? CommConstant.MESSAGE_TYPE_OF_SMS :
                isSubscribe ? CommConstant.MESSAGE_TYPE_OF_MINIAPP_SUBSCRIBE : CommConstant.MESSAGE_TYPE_OF_MINIAPP_TEMPLATE;

        String[] smsParams = {miniapp.getName() + "小程序-" + programName + name};

        if (null == tpl) {
            if (isSuccess) {
                log.error("小程序 {} 无通知消息模板 {}", toUser.getMiniappId(), contentType);
                // 短信发送
                sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);
            }
        } else {
            if (isSubscribe) {
                String[] data = new String[]{name, result, programName, remark, failReason, DateUtils.cutSecond(dt)};
                ResponseBean res = sendSubscribeMessage(tpl, toUser, link, data);
                if (res.getCode() != ResponseBean.CODE_SUCCESS && isSuccess) {
                    // 使用短信发送
                    sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), contentType, smsParams);
                    messageType = CommConstant.MESSAGE_TYPE_OF_SMS;
                }
            } else {
                log.info("发送模板消息");
            }
        }
        // TODO 写消息发送日志
        // 更新消息发送时间
        iTaPersonMessageRuleService.saveOrUpdateByPersonAndMessage(toUser.getPersonId(), messageType, contentType, toUser.getOrgId());
    }


    @Override
    public ResponseBean getQrCode(String paramsStr, String appid) {
        if (null == paramsStr) return ResponseBean.error("请指定二维码生成参数", ResponseBean.ERROR_MISSING_PARAMS);

        WxMaService wxService = wxUtils.getMiniApp(appid);

        // 先去数据库中查询
        QueryWrapper<TaMiniappQrcode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("appid", appid);
        queryWrapper.eq("qr_params", paramsStr);
        queryWrapper.ge("expire_date", LocalDateTime.now());
        queryWrapper.orderByDesc("create_date");
        queryWrapper.isNotNull("qr_code");
        queryWrapper.last("limit 1");

        TaMiniappQrcode taMiniappQrcode = taMiniappQrcodeMapper.selectOne(queryWrapper);
        if (null != taMiniappQrcode) {
            return ResponseBean.success(taMiniappQrcode.getQrCode());
        }

        // 如果没有找到则生成一个
        JSONObject params = JSONObject.parseObject(paramsStr);
        String scene = params.getString("scene");
        String page = StringUtils.ifNull(params.getString("page"), "");
        Integer width = params.getInteger("width");
        if (null == width) {
            width = 430;
        }

        Boolean autoColor = params.getBoolean("auto_color");
        if (null == autoColor) {
            autoColor = false;
        }

        String lineColorStr = StringUtils.ifNull(params.getString("line_color"), "{\"r\":0,\"g\":0,\"b\":0}");
        WxMaCodeLineColor lineColor = JSONObject.parseObject(lineColorStr, WxMaCodeLineColor.class);
        Boolean isHyaline = params.getBoolean("is_hyaline");
        if (null == isHyaline) {
            isHyaline = true;
        }

        try {

            TaMiniappQrcode taQrcode = new TaMiniappQrcode();
            taQrcode.setAppid(appid);
            taQrcode.setCreateDate(LocalDateTime.now());
            taQrcode.setExpireDate(LocalDateTime.now().plusDays(7));
            taQrcode.setQrParams(paramsStr);
            if (scene.indexOf("&qrCodeId=") > -1) {
                String str = scene.substring(scene.indexOf("&qrCodeId=") + 10);
                taQrcode.setTargetId(Integer.parseInt(str.substring(0, str.indexOf("&"))));
            }

            boolean success = taMiniappQrcodeMapper.insert(taQrcode) > 0;
            if (!success) {
                return ResponseBean.error("生成二维码异常", ResponseBean.ERROR_UNAVAILABLE);
            }

            // 使用ID作为场景值
            String newScene = String.valueOf(taQrcode.getSerialNo());
            System.out.println("==========生成二维码参数--->" + newScene);

            File qrFile = wxService.getQrcodeService().createWxaCodeUnlimit(newScene, page, width, autoColor, lineColor, isHyaline);
            String qrcode = AliOSSUtils.putObject(qrFile, CommConstant.ALIOSS_DEFAULT_UPLOAD);
            taQrcode.setQrCode(qrcode);
            taMiniappQrcodeMapper.updateById(taQrcode);

            return ResponseBean.success(qrcode);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error("生成二维码异常", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @Override
    public String createQrCode(WxMaService service, String path) throws Exception {
        File qrFile = service.getQrcodeService().createWxaCode(path);
        String qrcode = AliOSSUtils.putObject(qrFile, CommConstant.ALIOSS_DEFAULT_UPLOAD);
        return qrcode;
    }

    @Override
    public TaMiniappQrcode getQrCodeBySerialNo(Integer id) {
        return taMiniappQrcodeMapper.selectById(id);
    }

    @Override
    public List<TaMiniapp> getAllAvaliableMiniapps() {
        List<TaMiniapp> taMiniappList = taMiniappMapper.getAllAvaliableMiniapps();

        if (null != taMiniappList) {
            for (TaMiniapp miniapp : taMiniappList) {
                QueryWrapper<TaMiniappTemplate> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("miniapp_id", miniapp.getMiniappId());
                miniapp.setTpls(taMiniappTemplateMapper.selectList(queryWrapper));
            }
        }

        return taMiniappList;
    }

    @Deprecated
    private void sendMessage(String tplName, TaPerson toUser, String link, List<WxMaTemplateData> data) {
        String appid = toUser.getMiniappId();
        if (StringUtils.isEmpty(appid)) {
            log.error("人员 {} 无对应来源小程序信息", toUser);
        }

        TaMiniappTemplate tpl = getTplByType(tplName, toUser.getMiniappId());
        if (null == tpl) return;

        String formid = taMiniFormidsService.getFormidBy(toUser.getMiniOpenid(), true);
        if (StringUtils.isEmpty(formid)) {
            log.error("发送消息失敗, 沒有有效的 formid");
            return;
        }

        WxMaTemplateMessage message = WxMaTemplateMessage.builder()
                .templateId(tpl.getTplId())
                .data(data)
                .formId(formid)
                .page(StringUtils.ifNull(link, CommConstant.MINIAPP_INDEX))
                .toUser(toUser.getMiniOpenid())
                .build();
        try {
            WxMaService wxService = wxUtils.getMiniApp(appid);
            wxService.getMsgService().sendTemplateMsg(message);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        // TODO 写消息发送日志
    }

    private ResponseBean sendSubscribeMessage(TaMiniappTemplate tpl, TaPerson toUser, String link, String[] data) {
        String appid = toUser.getMiniappId();
        if (StringUtils.isEmpty(appid)) {
            log.error("人员 {} 无对应来源小程序信息", toUser);
            return ResponseBean.error("消息接收人无 appid 信息", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        if (null == tpl) {
            return ResponseBean.error("小程序未设置消息模板", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        if (StringUtils.isEmpty(tpl.getTplFields())) {
            return ResponseBean.error("小程序消息模板未设置字段内容", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        List<WxMaSubscribeMessage.Data> sendData = createMessageData(data, tpl.getTplFields());

        WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
                .templateId(tpl.getTplId())
                .data(sendData)
                .page(StringUtils.ifNull(link, CommConstant.MINIAPP_INDEX))
                .toUser(toUser.getMiniOpenid())
                .build();

        try {
            WxMaService wxService = wxUtils.getMiniApp(appid);
            wxService.getMsgService().sendSubscribeMsg(message);

            // TODO 写消息发送日志

            return ResponseBean.success("消息发送成功");
        } catch (WxErrorException e) {
            e.printStackTrace();

            // TODO 写消息发送日志

            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    private String sendSmsMessage(String tel, String type, String[] params) {
        if (StringUtils.isEmpty(tel) || StringUtils.isEmpty(type)) {
            return "短信发送失败: 没有手机号或者短信模板";
        }

        QueryWrapper<SysSmsSetting> query = new QueryWrapper<>();
        query.eq("sms_type", type);
        query.eq("status", CommConstant.STATUS_NORMAL);
        query.last("limit 1");

        SysSmsSetting smsSetting = sysSmsSettingMapper.selectOne(query);
        if (null == smsSetting) {

            // TODO 写消息发送日志

            return "没有设置有效的【" + type + "】短信模板";
        }

        boolean success = smsUtils.sendMessage(smsSetting.getTplCode(), tel, params);

        // TODO 写消息发送日志

        return success ? null : "短信发送失败";
    }

    private List<WxMaSubscribeMessage.Data> createMessageData(String[] list, String fieldsStr) {
        List<WxMaSubscribeMessage.Data> data = new ArrayList<>();
        if (list == null || list.length == 0 || StringUtils.isEmpty(fieldsStr)) return data;

        String[] fileds = fieldsStr.split("\\|");

        int length = Math.min(fileds.length, list.length);
        for (int i = 0; i < length; i++) {
            data.add(new WxMaSubscribeMessage.Data(fileds[i], list[i]));
        }
        return data;
    }

    @Override
    public TaMiniappTemplate getTplByType(String type, String appid) {
        TaMiniappTemplate tpl = taMiniappTemplateMapper.selectTplByType(type, appid);
        return tpl;
    }

    @Override
    public List<TaMiniappTemplate> getTpls(String appid) {
        QueryWrapper<TaMiniappTemplate> query = new QueryWrapper<>();
        query.eq("miniapp_id", appid);
        query.orderByAsc("serial_no");

        return taMiniappTemplateMapper.selectList(query);
    }

    @Override
    public ResponseBean getOrgQrCode(String paramsStr, Integer orgId) {
        QueryWrapper<TaMiniapp> query = new QueryWrapper<>();
        query.eq("org_id", orgId);
        query.last("limit 1");

        TaMiniapp taMiniapp = taMiniappMapper.selectOne(query);
        if (taMiniapp == null) {
            return ResponseBean.error("当前组织没有维护小程序信息", ResponseBean.ERROR_UNAVAILABLE);
        }

        return this.getQrCode(paramsStr, taMiniapp.getMiniappId());
    }

    public TaMiniapp getMinappByOrg(Integer org) {
        QueryWrapper<TaMiniapp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", org);
        queryWrapper.last("limit 1");

        return taMiniappMapper.selectOne(queryWrapper);
    }

    public void sendContractMessage(TaPerson toUser, String link, String name, String result, String programName,
                                    String failReason, String remark, LocalDateTime dt, Boolean isSuccess) {

        TaMiniapp miniapp = taMiniappMapper.selectById(toUser.getMiniappId());
        if (null == miniapp) {
            log.error("小程序 {} 不存在", toUser.getMiniappId());
            return;
        }

        // 消息内容类型
        String contentType = CommConstant.MESSAGE_CONTENT_OF_HOUSE;
        TaMiniappTemplate tpl = getTplByType(contentType, toUser.getMiniappId());
        boolean isSubscribe = null != tpl && (null == tpl.getIsSubscribe() ? false : tpl.getIsSubscribe());
        // 消息发送类型
        String messageType = null == tpl ? CommConstant.MESSAGE_TYPE_OF_SMS :
                isSubscribe ? CommConstant.MESSAGE_TYPE_OF_MINIAPP_SUBSCRIBE : CommConstant.MESSAGE_TYPE_OF_MINIAPP_TEMPLATE;

        String[] smsParams = {programName, "电子合同待签署"};

        if (null == tpl) {
            if (isSuccess) {
                log.error("小程序 {} 无通知消息模板 {}", toUser.getMiniappId(), contentType);
                // 短信发送
                sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), "contract", smsParams);
            }
        } else {
            if (isSubscribe) {
                String[] data = new String[]{name, result, programName, remark, failReason, DateUtils.cutSecond(dt)};
                ResponseBean res = sendSubscribeMessage(tpl, toUser, link, data);
                if (res.getCode() != ResponseBean.CODE_SUCCESS) {
                    // 使用短信发送
                    sendSmsMessage(StringUtils.ifNull(toUser.getTel(), toUser.getPhone()), "contract", smsParams);
                    messageType = CommConstant.MESSAGE_TYPE_OF_SMS;
                }
            } else {
                log.info("发送模板消息");
            }
        }
        // TODO 写消息发送日志
        // 更新消息发送时间
        iTaPersonMessageRuleService.saveOrUpdateByPersonAndMessage(toUser.getPersonId(), messageType, "contract", toUser.getOrgId());
    }
}
