package com.sqx.modules.errand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.sms.SmsSendResult;
import com.sqx.common.utils.Constant;
import com.sqx.common.utils.PageUtils;
import com.sqx.modules.errand.IndentSmsSendLogVO;
import com.sqx.modules.errand.dao.TbIndentSmsSendLogDao;
import com.sqx.modules.errand.dto.SmsCountQueryDTO;
import com.sqx.modules.errand.dto.SmsLogQueryDTO;
import com.sqx.modules.errand.entity.TbIndentSmsSendLog;
import com.sqx.modules.errand.service.TbIndentSmsSendLogService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TbIndentSmsSendLogServiceImpl extends ServiceImpl<TbIndentSmsSendLogDao, TbIndentSmsSendLog> implements TbIndentSmsSendLogService {

    @Override
    public PageUtils logPage(SmsLogQueryDTO queryDTO) {
        Page<TbIndentSmsSendLog> pages = new Page<>(queryDTO.getPage(), queryDTO.getLimit());

        IPage<IndentSmsSendLogVO> pageRecord;
        // 发送来源：1骑手、2商家
        if ("1".equals(queryDTO.getSourceType())) {
            pageRecord = baseMapper.logPageByRider(pages, queryDTO);
        } else {
            pageRecord = baseMapper.logPageByShop(pages, queryDTO);
        }

        return new PageUtils(pageRecord);
    }

    @Override
    public void saveLog(Long indentId, String sourceType, SmsSendResult smsSendResult) {
        TbIndentSmsSendLog log = new TbIndentSmsSendLog();

        log.setSendTime(new Date());
        log.setOrderId(indentId);
        log.setTemplateId(smsSendResult.getTemplateId());
        log.setSendContent(smsSendResult.getContent());
        log.setSuccessFlag(smsSendResult.getCode());
        log.setSendResult(smsSendResult.getMsg());
        log.setSendFromId(smsSendResult.getSendFromId());
        log.setSendTo(smsSendResult.getSendTo());
        log.setSendSource(sourceType);

        save(log);
    }

    @Override
    public int countOfSendSuccess(SmsCountQueryDTO queryDTO) {
        return baseMapper.countOfSendSuccess(queryDTO);
    }

    @Override
    public TbIndentSmsSendLog getSendSuccessByOrderId(Long indentId) {
        LambdaQueryWrapper<TbIndentSmsSendLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TbIndentSmsSendLog::getOrderId, indentId);
        queryWrapper.eq(TbIndentSmsSendLog::getSuccessFlag, Constant.YES);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }
}
