package com.fufan.mtsaas.modules.base.log.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.modules.base.log.bo.request.LogQueryRequest;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
import com.fufan.mtsaas.modules.base.log.bo.response.LogResponse;
import com.fufan.mtsaas.modules.base.log.dao.TLoginLogDao;
import com.fufan.mtsaas.modules.base.log.dao.TSysLogDao;
import com.fufan.mtsaas.modules.base.log.model.TLoginLog;
import com.fufan.mtsaas.modules.base.log.model.TSysLog;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.tools.MapTools;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.ParamUtil;
import com.github.pagehelper.ISelect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

import static com.fufan.mtsaas.util.DateFormatTool.DATETIME_FORMAT;
import static com.fufan.mtsaas.util.DateFormatTool.stringDateFormatToDate;


/**
 * <p>
 * 系统操作日志表 服务实现类
 * </p>
 *
 * @author Liby
 * @since 2022-03-16
 */
@Service("TSysLogSvcImpl")
@Slf4j
@Primary
public class TSysLogSvcImpl extends ServiceImpl<TSysLogDao, TSysLog> implements TSysLogSvc {
    @Autowired
    private TSysLogDao entitymDao;
    @Autowired
    private TLoginLogDao tLoginLogDao;
    private static  long DAY = 86400000;
    /**
     * 查询
     *
     * @param logQueryRequest
     * @return Result.class
     * */
    @Override
    public Result doQueryPage(LogQueryRequest logQueryRequest) {
        RequestPojo requestPojo = ParamUtil.doChange();
        Map<String,String> map = MapTools.objectToMap(logQueryRequest);
        Result result = new Result();
        //分页查询注册证信息表
        Page page = new Page();
        if(!StringUtils.isEmpty(map.get("pageSize")) && !StringUtils.isEmpty(map.get("currentPage"))) {
             page.setSize(Integer.parseInt(map.get("pageSize")));
            page.setCurrent(Integer.parseInt(map.get("currentPage")));
        }
        if(StringUtils.isNotEmpty(map.get("title"))){
            map.put("logTitle",map.get("title"));
        }
        if(StringUtils.isNotEmpty(map.get("content"))){
            map.put("logContent",map.get("content"));
        }
        if(StringUtils.isNotEmpty(logQueryRequest.getOperateStartTime())){
            if(stringDateFormatToDate(logQueryRequest.getOperateStartTime()).getTime() < System.currentTimeMillis() - DAY * 30 ){
                result.setResStatus(ResStatus.STATUS_LOG_ONLY_30_DAY);
                result.setResMsg(ResStatus.STATUS_LOG_ONLY_30_DAY_MSG);
                return result;
            }
        }
        map.put("companyId",requestPojo.getCustId());
        long total = 0;
        if(StringUtils.isNotEmpty(logQueryRequest.getRelatedType()) && logQueryRequest.getRelatedType().equals("login")){
            total = com.github.pagehelper.PageHelper.count(new ISelect() {
                @Override
                public void doSelect() {
                    tLoginLogDao.selectList(page, map);
                }
            });
        }else {
            total = com.github.pagehelper.PageHelper.count(new ISelect() {
                @Override
                public void doSelect() {
                    entitymDao.selectList(page, map);
                }
            });
        }
        ParamUtil.setPage(page.getSize(), page.getCurrent(), page);
        List<TSysLog> entitys = new ArrayList<>();
        if(StringUtils.isNotEmpty(logQueryRequest.getRelatedType()) && logQueryRequest.getRelatedType().equals("login")) {
          List<TLoginLog> tLoginLogList = tLoginLogDao.selectList(page, map);
          for (TLoginLog tLoginLog : tLoginLogList){
              TSysLog tSysLog = new TSysLog();
              BeanUtils.copyProperties(tLoginLog,tSysLog);
              entitys.add(tSysLog);
          }
        }else {
            entitys = entitymDao.selectList(page, map);
        }

        List<LogResponse> logResponseList = new ArrayList<>();
        for(TSysLog tSysLog : entitys){
            LogResponse logResponse = new LogResponse();
            BeanUtils.copyProperties(tSysLog,logResponse);
            logResponse.setId((long)tSysLog.getId());
            logResponse.setOperateTime(DateFormatTool.dateToString(DATETIME_FORMAT,tSysLog.getOperateTime()));
            logResponseList.add(logResponse);
        }
        page.setTotal((int)total);
        page.setRecords(logResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 新增
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    @Transactional
    public Result doSave(LogSaveRequest entitym, RequestPojo requestPojo) {
        log.debug("TSysLogSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(com.alibaba.druid.util.StringUtils.isEmpty(entitym.getLogTitle()) ){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        //名称重复验证
        HashMap mapData = new HashMap();
        Page page = new Page();
        TSysLog entityData = new TSysLog();
        BeanUtils.copyProperties(entitym,entityData);
        entityData.setOperator(requestPojo.getUserName());
        entityData.setOperateTime(new Date());
        entityData.setCompanyId(Long.valueOf(requestPojo.getCustId()));
        entityData.setIpAddress(requestPojo.getIp());
        try{
            entitymDao.insert(entityData);
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            result.setResData(page.setRecords(Arrays.asList(entitym)));
        }catch (Exception e){
            log.error("新增系统操作日志表数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增系统操作日志表数据出错");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;

    }

    @Override
    @Transactional
    public Result saveLogInfo(long relatedId, String relatedType, String title,
                              String content, String operateType, String operateStatus,
                              RequestPojo requestPojo) {
        Result result = new Result();
        try {
            LogSaveRequest logSaveRequest = new LogSaveRequest();
            logSaveRequest.setRelatedId(relatedId);
            logSaveRequest.setRelatedType(relatedType);
            logSaveRequest.setLogTitle(title);
            logSaveRequest.setLogContent(content);
            logSaveRequest.setOperateTime(new Date());
            logSaveRequest.setOperateType(operateType);
            logSaveRequest.setOperateStatus(operateStatus);
            result = doSave(logSaveRequest, requestPojo);
        } catch (Exception e) {
            log.error("Saving log failed: " + e.getMessage());
        }

        return result;
    }

    /**
     * 新增 登入登出日志
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    @Transactional
    public Result doSaveLogin(LogSaveRequest entitym, RequestPojo requestPojo) {
        log.debug("TSysLogSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(com.alibaba.druid.util.StringUtils.isEmpty(entitym.getLogTitle()) ){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        //名称重复验证
        HashMap mapData = new HashMap();
        Page page = new Page();
        TLoginLog entityData = new TLoginLog();
        BeanUtils.copyProperties(entitym,entityData);
        entityData.setOperator(requestPojo.getUserName());
        entityData.setOperateTime(new Date());
        entityData.setCompanyId(Long.valueOf(requestPojo.getCustId()));
        entityData.setIpAddress(requestPojo.getIp());
        try{
            tLoginLogDao.insert(entityData);
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            result.setResData(page.setRecords(Arrays.asList(entitym)));
        }catch (Exception e){
            log.error("新增系统操作日志表数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增系统操作日志表数据出错");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;

    }

}
