package com.iformall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.WxAdminLog;
import com.iformall.mapper.WxAdminLogMapper;
import com.iformall.service.WxAdminLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WxAdminLogServiceImpl implements WxAdminLogService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxAdminLogMapper wxAdminLogMapper;


    @Override
    public PageInfo<WxAdminLog> listAsPage(WxAdminLog record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxAdminLogMapper.findList(record));
    }

    @Override
    public WxAdminLog getById(Long id) {
        return wxAdminLogMapper.selectById(id);
    }

    @Override
    public void saveOrUpdate(WxAdminLog record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
            wxAdminLogMapper.insert(record);
        } else {
            wxAdminLogMapper.updateById(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxAdminLogMapper.deleteById(id);
    }
    
    @Override
    public void saveLogCount(WxAdminLog record) {
        // TODO use redis to optimize
        WxAdminLog reqQ = new WxAdminLog();
        reqQ.setTenantId(record.getTenantId());
        reqQ.setUrl(record.getUrl());
        reqQ.setType(record.getType());
        reqQ.setActionDate(record.getActionDate());
        List<WxAdminLog> logList = wxAdminLogMapper.selectList(new QueryWrapper(reqQ));
        if (logList.size() > 0) {
            WxAdminLog log = logList.get(0);
            log.setCount(log.getCount() + 1);
            wxAdminLogMapper.updateById(log);
        } else {
            final IdWorker idWorker = IdWorker.get();
            reqQ.setId(idWorker.nextId());
            reqQ.setCount(1);
            wxAdminLogMapper.insert(reqQ);
        }
    }
    
    
    
    
    
}
