package com.yizhi.application.report.login;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.system.application.system.remote.LoginLogClient;
import com.yizhi.system.application.vo.LoginDataStatisticsVO;
import com.yizhi.system.application.vo.LoginUserChartVO;
import com.yizhi.system.application.vo.LoginUserExportVO;
import com.yizhi.system.application.vo.LoginUserOrgExportVO;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: XieHaijun
 * @Description:
 * @Date: Created in 19:26 2018/8/28
 * @Modified By
 */
@Api(tags = "报表统计-用户登陆情况统计", description = "报表统计-用户登陆情况统计")
@RestController
@RequestMapping("/manage/report/loginLog/")
public class LoginExportController {

    @Autowired
    private LoginLogClient loginLogClient;

    static final String BY_ORG_EXPORT="byOrgExport";

    static final String BY_ACCOUNT_EXPORT="byAccountExport";

    private static final DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    private static final Logger logger = LoggerFactory.getLogger(LoginExportController.class);

    @ApiOperation(value = "图表数据统计", notes = "图表数据统计", response = LoginUserChartVO.class)
    @GetMapping("/chart/view")
    public Response<List<LoginUserChartVO>> loginLogChart(
            @ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
            @ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
            @ApiParam(value = "类型：1按日 2按周 3按月（默认按日）", required = true) @RequestParam(name = "type", required = true, defaultValue = "1") Integer type
    ){
        if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
            return Response.ok();
        }
        List<LoginUserChartVO> list=loginLogClient.loginLogChart(startDate,endDate,type);
        if (CollectionUtils.isEmpty(list)) {
			list=new ArrayList<LoginUserChartVO>();
		}
        return Response.ok(list);
    }

    @ApiOperation(value = "按组织统计", notes = "按组织统计", response = LoginUserOrgExportVO.class)
    @GetMapping("/list/org")
    public Response<LoginUserOrgExportVO> loginLogByOrg(
            @ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
            @ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
            @ApiParam(value = "查询关键字", required = false) @RequestParam(name = "kwd", required = false) String kwd,
            @ApiParam(value = "每页条数，默认10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo
    ){

        if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
            return Response.ok();
        }
        Page<LoginUserOrgExportVO> result =
                loginLogClient.loginLogByOrg(startDate,endDate,kwd,pageSize,pageNo);
        Map<String, Integer> pageMap = new HashMap<String, Integer>();
        pageMap.put("pageNo", pageNo);
        pageMap.put("pageSize", pageSize);
		pageMap.put("pageTotal",result!=null&&result.getSize()>0?result.getTotal():null);
        List<LoginUserOrgExportVO> ret = result!=null&&result.getSize()>0?result.getRecords():new ArrayList<LoginUserOrgExportVO>();
        return Response.ok(ret, pageMap);
    }

    @ApiOperation(value = "按组织统计导出下载", notes = "按组织统计导出下载")
    @GetMapping("/list/org/export")
    public Response<String> loginLogByOrgExport(
            @ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
            @ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
            @ApiParam(value = "查询关键字", required = false) @RequestParam(name = "kwd", required = false) String kwd,
            @ApiParam(value = "每页条数，默认10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo
    ){
        Map<String,Object> parament = new HashMap<>();
        // 共同字段
        /*RequestContext requestContext = ContextHolder.get();
        logger.info("%%%%%%%%%%%%%%%%%%%%上下文信息="+ JSON.toJSONString(requestContext));
        parament.put("requestContext",requestContext);*/

        parament.put("business",BY_ORG_EXPORT);// 导出的业务类型
        parament.put("startDate",startDate);
        parament.put("endDate",endDate);
        parament.put("kwd",kwd);
        // 执行异步，并且设置成异步启动
        String taskNo = LocalDateTime.now().format(formatter);
        parament.put("serialNo",taskNo);
        //export.execute(parament,true);
        loginLogClient.loginLogByOrgExp(parament);
        String exportName = "部门登录情况统计";
        return Response.ok("任务序号："+ taskNo+"。任务名称："+exportName+"_"+taskNo);
    }

    @ApiOperation(value = "按用户统计", notes = "按用户统计", response = LoginUserExportVO.class)
    @GetMapping("/list/account")
    public Response<LoginUserExportVO> loginLogByAccount(
            @ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
            @ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
            @ApiParam(value = "查询关键字", required = false) @RequestParam(name = "kwd", required = false) String kwd,
            @ApiParam(value = "每页条数，默认10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo
    ){
        if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
            return Response.ok();
        }
        
        Map<String, Integer> pageMap;
		List<LoginUserExportVO> ret;
		try {
			Page<LoginUserExportVO> result =
			        loginLogClient.loginLogByAccount(startDate,endDate,kwd,pageSize,pageNo);
			pageMap = new HashMap<String, Integer>();
			pageMap.put("pageNo", pageNo);
			pageMap.put("pageSize", pageSize);
			pageMap.put("pageTotal",result!=null&&result.getSize()>0?result.getTotal():null);
			ret = result!=null&&result.getSize()>0?result.getRecords():new ArrayList<LoginUserExportVO>();
			return Response.ok(ret, pageMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail();
		}
    }

    @ApiOperation(value = "按用户统计导出下载", notes = "按用户统计导出下载")
    @GetMapping("/list/account/export")
    public Response<String> loginLogByAccountExport(
            @ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
            @ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
            @ApiParam(value = "查询关键字", required = false) @RequestParam(name = "kwd", required = false) String kwd,
            @ApiParam(value = "每页条数，默认10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo
    ){

        Map<String,Object> parament = new HashMap<>();
        // 共同字段
        /*RequestContext requestContext = ContextHolder.get();
        logger.info("%%%%%%%%%%%%%%%%%%%%上下文信息="+ JSON.toJSONString(requestContext));
        parament.put("requestContext",requestContext);*/

        parament.put("business",BY_ACCOUNT_EXPORT);// 导出的业务类型
        parament.put("startDate",startDate);
        parament.put("endDate",endDate);
        parament.put("kwd",kwd);
        String taskNo = LocalDateTime.now().format(formatter);
        parament.put("serialNo",taskNo);
        // 执行异步，并且设置成异步启动
        //export.execute(parament,true);
        loginLogClient.loginLogByAccountExp(parament);
        String exportName = "用户登录情况统计";
        return Response.ok("任务序号："+ taskNo+"。任务名称："+exportName+"_"+taskNo);
    }
    
    @ApiOperation(value = "登录数据统计", notes = "登录数据统计", response = LoginDataStatisticsVO.class)
    @GetMapping("/count")
    public Response<LoginDataStatisticsVO> loginLogChart(){
    	RequestContext context = ContextHolder.get();
    	Long siteId=context.getSiteId();
        return Response.ok(loginLogClient.loginCount(siteId));
    }

}
