package com.zfire.mall.manager.logic.admin;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.OperationLog;
import com.zfire.mall.manager.plus.service.OperationLogService;
import com.zfire.mall.manager.logic.common.CommonLogic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OperationLogLogic {

    @Autowired
    OperationLogService operationLogService;
    @Autowired
    CommonLogic commonLogic;

    /**
     * 操作日志列表分页
     */
    public IPage<OperationLog> listPage(HttpServletRequest request,String moduleName, String startTime, String endTime, Integer pageNo, Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> adminCompanyIds = adminUser.getAdminCompanyIds();

        return operationLogService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminCompanyIds),OperationLog::getAdminCompanyId,adminCompanyIds)
                .like(StringUtils.isNotEmpty(moduleName),OperationLog::getModuleName,moduleName)
                .between(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime),
                        OperationLog::getCreateTime,startTime,endTime)
                .orderByDesc(OperationLog::getCreateTime,OperationLog::getOperationLogId)
                .page(new Page<>(pageNo,pageSize));
    }

    /**
     * 所属模块
     */
    public List<String> moduleList(HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> adminCompanyIds = adminUser.getAdminCompanyIds();

        List<OperationLog> distinctModuleName = operationLogService.lambdaQuery()
                .select(OperationLog::getModuleName)
                .in(CollectionUtils.isNotEmpty(adminCompanyIds),OperationLog::getAdminCompanyId,adminCompanyIds)
                .groupBy(OperationLog::getModuleName)
                .list();
        if(distinctModuleName.size() == 0){
            return new ArrayList<>();
        }
        List<String> collect = distinctModuleName.stream().map(OperationLog::getModuleName).distinct().collect(Collectors.toList());
        return collect;
    }

    /**
     * 详情
     */
    public OperationLog detail(String operationLogId){
        return operationLogService.getById(operationLogId);
    }


}
