package cn.pluss.platform.notice.impl;

import cn.pluss.platform.PushService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.channel.BaseMerchantAuditService;
import cn.pluss.platform.entity.Notice;
import cn.pluss.platform.entity.NoticeTemplate;
import cn.pluss.platform.entity.UserTask;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.NoticeMapper;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.notice.template.NoticeTemplateService;
import cn.pluss.platform.schedule.UserTaskService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author nb2020
 */
@Service("noticeService")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private PushService pushService;

    @Setter(onMethod_ = {@Autowired})
    private NoticeTemplateService noticeTemplateService;

    @Autowired
    private UserTaskService userTaskService;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Override
    public boolean saveOrUpdate(Notice entity) {
        if (entity.getTypeFirst() == null) {
            entity.setTypeFirst(1);
        }

        if (entity.getTypeSecond() == null) {
            entity.setTypeSecond(-1);
        }

        if (StringUtils.isNotBlank(entity.getUrl())) {
            entity.setConrtent(null);
        }

        if (StringUtils.isBlank(entity.getNoticeCode())) {
            entity.setNoticeCode(UUID.randomUUID().toString().replace("-", ""));
        }

        entity.setCreateDt(new Date());
        entity.setIsDeal(0);

        return super.saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public boolean save(Notice notice) {
        // 发推送给个人，如果没有指定用户id，则推送到所有人
//        if ("1".equals(notice.getPushFlag())) {
//            if ("-1".equals(notice.getUserId())) {
//                pushService.pushAll(notice.getTitle(), notice.getDesc());
//            } else {
//                List<String> userIdList = Collections.singletonList(notice.getUserId());
//                GeneralPushUtil.sendAllPlatByAlias(userIdList, notice.getTitle(), notice.getDesc(), "1");
//            }
//        }
//        if ("2".equals(notice.getPushFlag())) {
//            if ("-1".equals(notice.getUserId())) {
//                pushService.pushAll(notice.getTitle(), notice.getDesc());
//            } else {
//                List<String> userIdList = new ArrayList<String>() {{
//                    add(notice.getUserId());
//                }};
//                UserApp userApp = new UserApp().setUserId(Long.parseLong(notice.getUserId()));
//                userApp = userAppService.queryUserApp(userApp);
//                if (userApp != null && userApp.getParentId() != null) {
//                    userIdList.add(userApp.getParentId().toString());
//                }
//                GeneralPushUtil.sendAllPlatByAlias(userIdList, notice.getTitle(), notice.getDesc(), "1");
//            }
//        }
        Integer result;
        switch (notice.getTypeSecond()) {
            case Notice.TYPE_MER_OUT_LINE:
                result = saveMerOutLineNotice(notice);
                break;
            case Notice.TYPE_MER_EXCEPTION:
                result = saveMerExceptionNotice(notice);
                break;
            case Notice.TYPE_MER_FREEZE:
                result = saveMerFreezeNotice(notice);
                break;
            default:
                result = baseMapper.insert(notice);
                break;
        }
        return result != null && result >= 1;
    }

    private Integer saveSwitchNotice(String userId, Notice notice, NoticeTemplate noticeTemplate, String regContent, String userName) {
        Integer result = 0;
        notice.setUserId(userId);
        notice.setUserName(userName);
        notice.setDesc(noticeTemplate.getContent().replace(noticeTemplate.getVariable(), regContent));
        switch (notice.getTypeSecond()) {
            case Notice.TYPE_MER_OUT_LINE:
                result = saveMerOutLineNotice(notice);
                break;
            case Notice.TYPE_MER_EXCEPTION:
                result = saveMerExceptionNotice(notice);
                break;
            case Notice.TYPE_MER_FREEZE:
                result = saveMerFreezeNotice(notice);
                break;
            default:
//                        result = baseMapper.insert(notice);
                break;
        }
        return result;
    }

    @Override
    public void saveNotice(Notice notice) {
        save(notice);
    }

    /**
     * @param notice:
     * @return cn.pluss.platform.api.Result<?>
     * @description:发送自定义模板消息
     * @date: 2021/8/31 16:51
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendTempNotice(Notice notice) {
        String pushFlag = notice.getPushFlag();
        String userId = notice.getUserId();
        if ("-1".equals(userId)) {
            // 广播就不做定时任务
            notice.setCreateDt(new Date());
            if (notice.getTypeFirst() == null) {
                notice.setTypeFirst(1);
            }
            if (notice.getTypeSecond() == null) {
                notice.setTypeSecond(-1);
            }
            baseMapper.insert(notice);
            if (!"0".equals(pushFlag)) {
                pushService.pushAll(notice.getTitle(), notice.getDesc());
            }

        } else {
            List<String> userNameList = Arrays.asList(notice.getUserName().split(","));
            List<String> aliasList = Arrays.asList(notice.getAliass().split(","));
            NoticeTemplate template = noticeTemplateService.getNoticeTemplateByType(notice.getTypeSecond() + "");
            MsgException.checkNull(template, "当前类型暂无模板，请在自定义模板中添加！");

            if ("0".equals(pushFlag)) {
                for (int i = 0; i < userNameList.size(); i++) {
                    List<String> pushIds = new ArrayList<>();
                    if (StringUtils.isNotBlank(notice.getUserIds())) {
                        List<String> uids = Arrays.asList(notice.getUserIds().split(","));
                        pushIds.add(uids.get(i));
                    }
                    if (StringUtils.isNotBlank(notice.getParentIds()) && "2".equals(notice.getPushFlag())) {
                        List<String> pids = Arrays.asList(notice.getParentIds().split(","));
                        pushIds.add(pids.get(i));
                    }
                    String reDesc = aliasList.get(i);
                    String desc = template.getContent();
                    if (StringUtils.isNotBlank(template.getVariable())) {
                        desc = template.getContent().replace(template.getVariable(), reDesc);
                    }
                    generalPushUtil.sendAllPlatByAlias(pushIds, notice.getTitle(), desc, "1");
                }
            }

            List<String> uids = Arrays.asList(notice.getUserIds().split(","));
            List<String> pids = null;
            for (int i = 0; i < aliasList.size(); i++) {
                Map<String, Object> mapArgs = new HashMap<>();
                mapArgs.put(template.getVariable(), aliasList.get(i));
                sendTempNotice(notice.getTitle(), notice.getDesc(), notice.getConrtent(), notice.getUrl(), uids.get(i), mapArgs);
                // 同步发到上级
                if (StringUtils.isNotBlank(notice.getParentIds()) && "2".equals(notice.getPushFlag())) {
                    if (pids == null) {
                        pids = Arrays.asList(notice.getParentIds().split(","));
                    }
                    sendTempNotice(notice.getTitle(), notice.getDesc(), notice.getConrtent(), notice.getUrl(), pids.get(i), mapArgs);
                }
            }
        }
    }

    @Override
    public void sendTempNotice(Notice notice, String scheduleFlag) {
        String userId = notice.getUserId();

        // 立即发送和全员发送的不直接走发送的逻辑
        if (Objects.equals(scheduleFlag, "0") || "-1".equals(userId)) {
            sendTempNotice(notice);
            return;
        }

        List<String> aliasList = Arrays.asList(notice.getAliass().split(","));
        NoticeTemplate template = noticeTemplateService.getNoticeTemplateByType(notice.getTypeSecond() + "");
        MsgException.checkNull(template, "当前类型暂无模板，请在自定义模板中添加！");

        List<String> uids = Arrays.asList(notice.getUserIds().split(","));
        List<String> pids = null;

        for (int i = 0; i < aliasList.size(); i++) {
            UserTask userTask = new UserTask();
            userTask.setType(scheduleFlag);

            userTask.setArg0(notice.getTitle());
            String content = notice.getDesc().replace(template.getVariable(), aliasList.get(i));
            userTask.setArg1(content);
            userTask.setArg2(notice.getUrl());
            userTask.setArg3(notice.getConrtent());
            userTask.setStatus(UserTask.STATUS_ENABLED);
            userTask.setTaskCode("SCHE_NOTICE");
            userTask.setUserId(Integer.parseInt(uids.get(i)));
            userTaskService.save(userTask);
            // 同步发到上级
            if (StringUtils.isNotBlank(notice.getParentIds()) && "2".equals(notice.getPushFlag())) {
                if (pids == null) {
                    pids = Arrays.asList(notice.getParentIds().split(","));
                }
                userTask.setUserId(Integer.parseInt(pids.get(i)));
                userTask.setCreateTime(null);
                userTask.setUpdateTime(null);
                userTaskService.save(userTask);
            }
        }
    }

    @Override
    public void sendTempNotice(String templateTitle, String templateDesc, String content, String url, String userId, Object... args) {
        Map<String, Object> mapArgs = new HashMap<>();
        for (int i = 0; i < args.length; i++) {
            mapArgs.put("$" + (i + 1), args[i].toString());
        }

        sendTempNotice(templateTitle, templateDesc, content, url,userId, mapArgs);
    }

    @Override
    public void sendTempNotice(String templateTitle, String templateDesc, String content, String url, String userId, Map<String, Object> mapArgs) {
        sendTempNotice(templateTitle, templateDesc, content, url, userId, mapArgs, true);
    }

    @Override
    public void sendTempNotice(String templateTitle, String templateDesc, String content, String url, String userId, Map<String, Object> mapArgs, boolean pushFlag) {
        String desc = templateDesc;

        for (Map.Entry<String, Object> entry : mapArgs.entrySet()) {
            if (StringUtils.isNotBlank(entry.getKey())) {
                desc = desc.replace(entry.getKey(), entry.getValue().toString());
            }
        }

        if (content != null) {
            for (Map.Entry<String, Object> entry : mapArgs.entrySet()) {
                if (StringUtils.isNotBlank(entry.getKey())) {
                    content = content.replace(entry.getKey(), entry.getValue().toString());
                }
            }
        }

        Notice notice = new Notice(1, -1, userId, null);
        notice.setTitle(templateTitle);
        notice.setUrl(url);
        notice.setDesc(desc);

        if (content == null) {
            notice.setConrtent(desc);
        } else {
            notice.setConrtent(content);
        }

        save(notice);

        if (pushFlag) {
            generalPushUtil.sendAllPlatByAlias(Collections.singletonList(userId), templateTitle, notice.getDesc(), "");
        }
    }

    @Override
    public void sendEditApplyNotice(String userId, String alias, String settleName) {
        sendTempNotice("结算卡修改申请通知", BaseMerchantAuditService.editApplyNoticeTemplate, null, null, userId, alias, settleName);
    }

    @Override
    public void sendEditApplySuccessNotice(String userId, String alias, String settleName) {
        sendTempNotice("结算卡修改申请通知", BaseMerchantAuditService.editApplyResultNoticeTemplate, null, null, userId, alias, settleName);
    }
}

