package com.rf.psychological.module.index.rest;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.institution.model.InstitutionEntity;
import com.rf.psychological.institution.service.InstitutionAuthService;
import com.rf.psychological.institution.service.InstitutionService;
import com.rf.psychological.module.index.dao.dto.IndexNumDayDTO;
import com.rf.psychological.module.index.dao.dto.IndexNumMonthDTO;
import com.rf.psychological.module.index.dao.dto.IndexRecordsNumSortDTO;
import com.rf.psychological.module.index.dao.dto.IndexSortNumDTO;
import com.rf.psychological.module.index.service.IndexService;
import com.rf.psychological.plan.dao.model.HisTestPlanEntry;
import com.rf.psychological.plan.dao.model.TestPlanEntity;
import com.rf.psychological.plan.service.HisTestPlanService;
import com.rf.psychological.plan.service.TestPlanService;
import com.rf.psychological.scale.dao.model.WarnEntity;
import com.rf.psychological.scale.service.CognitiveTaskService;
import com.rf.psychological.scale.service.UserRecordService;
import com.rf.psychological.scale.service.WarnService;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.scale.service.SubjectService;
import com.rf.psychological.utils.Constant;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lpf
 * @description:
 * @date 2022/3/14 18:28
 */
@RestController
@Slf4j
@RequestMapping("/index")
@Api(tags = "管理员首页数据接口")
public class IndexController extends BaseController {

    @Resource
    private IndexService indexService;

    @Resource
    private InstitutionAuthService institutionAuthService;

    @Resource
    private TestPlanService testPlanService;

    @Resource
    private HisTestPlanService hisTestPlanService;

    @Resource
    private SubjectService subjectService;

    @Resource
    private CognitiveTaskService cognitiveTaskService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private InstitutionService institutionService;

    @Resource
    private UserRecordService userRecordService;

    @Resource
    private WarnService warnService;

    @Value("${spring.profiles.active}")
    private String profileValue;

    @SafetyProcess
    @GetMapping("/count/{institutionNo}")
    @ApiOperation(value = "机构组数，用户数，管理员数，预警数据接口")
    public Result findIndexFourCount(@PathVariable("institutionNo") String institutionNo) {
        if (institutionNo == null || institutionNo.equals("")) {
            return fail("机构编号空");
        }
        int groupCount = this.indexService.findGroupCount(institutionNo);
        int userCount = this.indexService.findUserCount(institutionNo);
        int institutionAdminCount = this.indexService.findInstitutionAdminCount(institutionNo);
        int warnCount = this.warnService.findByInstitutionNo(institutionNo);
        HashMap<String, Object> result = new HashMap<>();
        result.put("groups", groupCount);
        result.put("users", userCount);
        result.put("admins", institutionAdminCount);
        result.put("warns", warnCount);
        return success(result, "查询成功");
    }

    /**
     * 查询机构量表类别数
     *
     * @param institutionNo
     * @return
     */
    @SafetyProcess
    @GetMapping("/scale/{institutionNo}/sorts")
    @ApiOperation(value = "查询机构量表类别数")
    public Result findScaleSortNum(@PathVariable("institutionNo") String institutionNo) {
        if (institutionNo == null || institutionNo.equals("")) {
            return fail("机构编号空");
        }
        List<IndexSortNumDTO> indexScaleSort = indexService.findIndexSjSort(institutionNo);
        return success(indexScaleSort, "查询成功");
    }

    /**
     * 查询机构认知任务类别数
     *
     * @param institutionNo
     * @return
     */
    @SafetyProcess
    @GetMapping("/cg/{institutionNo}/sorts")
    @ApiOperation(value = "查询机构认知任务类别数")
    public Result findCgSortNum(@PathVariable("institutionNo") String institutionNo) {
        if (institutionNo == null || institutionNo.equals("")) {
            return fail("机构编号空");
        }
        List<IndexSortNumDTO> indexCgSort = indexService.findIndexCgSort(institutionNo);
        return success(indexCgSort, "查询成功");
    }

    @SafetyProcess
    @GetMapping("/months/{institutionNo}/{type}")
    @ApiOperation(value = "查询机构近12个月所做量表和认知任务数")
    public Result findCgSortNum(@PathVariable("institutionNo") String institutionNo, @PathVariable @ApiParam("type:0--量表。1--认知任务") String type) {
        if (institutionNo == null || institutionNo.equals("")) {
            return fail("机构编号空");
        }
        List<IndexNumMonthDTO> indexNumsMonth = indexService.finIndexNumMonth(type, institutionNo);
        if (CollectionUtils.isEmpty(indexNumsMonth)) {
            return fail("没有数据");
        }
        return success(indexNumsMonth, "查询成功");
    }


    @SafetyProcess
    @GetMapping("/days/{institutionNo}/{type}")
    @ApiOperation(value = "查询机构近15天所做量表或认知任务数")
    public Result findCountByDays(@PathVariable("institutionNo") String institutionNo, @PathVariable @ApiParam("type:0--量表。1--认知任务") String type) {
        if (institutionNo == null || institutionNo.equals("")) {
            return fail("机构编号空");
        }
        List<IndexNumDayDTO> indexNumberByDays = indexService.findIndexNumberByDays(type, institutionNo);
        if (CollectionUtils.isEmpty(indexNumberByDays)) {
            return fail("没有数据");
        }
        return success(indexNumberByDays, "查询成功");
    }

    @SafetyProcess
    @GetMapping("/Leaderboard/{institutionNo}/{type}")
    @ApiOperation(value = "查询机构认知任务和量表的测试人数排行")
    public Result findIndexLeaderboard(@PathVariable("institutionNo") String institutionNo, @PathVariable @ApiParam("type:0--量表。1--认知任务") String type, @RequestParam(defaultValue = "10") int limit) {
        List<IndexRecordsNumSortDTO> indexLeaderboard = indexService.findIndexLeaderboard(institutionNo, limit, type);
        if (CollectionUtils.isEmpty(indexLeaderboard)) {
            return fail("没有数据");
        }
        return success(indexLeaderboard, "查询成功");
    }

    @SafetyProcess
    @GetMapping("/taskNumber/{institutionNo}/{type}")
    @ApiOperation(value = "查询量表或认知任务数量")
    public Result findTaskNumber(@PathVariable("institutionNo") String institutionNo, @PathVariable @ApiParam("type:0--量表。1--认知任务") int type) {

        long num = 0L;
        if (type == 0) {
            if (!"10006".equals(institutionNo)) {
                num = this.institutionAuthService.getAllByTableInAuthAndSubInfoNum(institutionNo, String.valueOf(type), "",null);
            } else {
                num = this.subjectService.allNum();
            }

        }
        if (type == 1) {
            if (!"10006".equals(institutionNo)) {
                num = this.institutionAuthService.getAllConTaskNum(institutionNo, String.valueOf(type), "", false);
            } else {
                num = this.cognitiveTaskService.allNum();
            }
        }

        return success(num, "查询成功");
    }

    @SafetyProcess
    @GetMapping("/testPlan/{institutionNo}")
    @ApiOperation(value = "查询测试计划数，自定义量表数量等")
    public Result findTestPlanNumber(@PathVariable("institutionNo") String institutionNo) {
        List<HisTestPlanEntry>  hisTestPlanEntryList = hisTestPlanService.findByInstitutionNo(institutionNo);
        Page<TestPlanEntity> testPlanEntities = this.testPlanService.findAllByInstitutionNo(institutionNo, "", null, null, "", 1, 10);
        long totalTestPlansNum = testPlanEntities.getTotalElements();
        //正在使用中的测试计划
        List<TestPlanEntity> isUsingTestPlan = testPlanEntities.getContent().stream()
                .filter(testPlanEntity -> testPlanEntity.getStatus() == 3)
                .collect(Collectors.toList());
        int isUsingTestPlanNum = isUsingTestPlan.size();
        //查询自定义量表数量
        int customScaleNum = this.subjectService.institutionByTCNum(institutionNo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalTestPlansNum", hisTestPlanEntryList!= null?totalTestPlansNum+hisTestPlanEntryList.size():totalTestPlansNum);
        jsonObject.put("isUsingTestPlanNum", isUsingTestPlanNum);
        jsonObject.put("customScaleNum", customScaleNum);
        return success(jsonObject, "查询成功");
    }

    @SafetyProcess
    @GetMapping("/countOnlineUser/{institutionNo}")
    @ApiOperation(value = "在线人数")
    public Result countOnlineUser(@PathVariable("institutionNo") String institutionNo) {
//        HashMap<String, Long> onlineUserCount = (HashMap<String, Long>) request.getServletContext().getAttribute("onlineUserCount");
//        Long onlineUserNum = 0L;
//        if (!CollectionUtils.isEmpty(onlineUserCount)) {
//            if ("10006".equals(institutionNo)) {
//                Set<String> institutionNos = onlineUserCount.keySet();
//                for (String no : institutionNos) {
//                    onlineUserNum = onlineUserNum + onlineUserCount.get(no);
//                }
//            } else {
//                if (onlineUserCount.containsKey(institutionNo)) {
//                    onlineUserNum = onlineUserCount.get(institutionNo);
//                }
//            }
//        }
        if ("lan".equals(profileValue)){
            return success(0, "查询成功");
        }
        String ownerKey ="session:";
        if (Constant.SYSTEM_INSTITUTION_ON.equals(institutionNo)){
            ownerKey+="*";
        }else {
            ownerKey+=institutionNo+":*";
        }

        Set<String> keys = redisTemplate.keys(ownerKey);
        return success(keys.size(), "查询成功");
    }

    @SafetyProcess
    @GetMapping("/countTestNumber/{institutionNo}")
    @ApiOperation(value = "获取剩余测试次数")
    public Result countTestNumber(@PathVariable("institutionNo") String institutionNo) {
        try {
            JSONObject map = new JSONObject();
            if (StringUtils.isEmpty(institutionNo)){
                return fail("机构编号不能为空");
            }
            InstitutionEntity entity = institutionService.findByInstitutionNo(institutionNo);
            if (entity == null){
                return fail("机构编号不存在");
            }
            String isTest = entity.getIsTestNum()== null? Constant.DEFAULT_VALUE_ZERO:entity.getIsTestNum().toString();
            map.put("isTestNum",isTest);
            if (Constant.DEFAULT_VALUE_ZERO.equals(isTest)){
                map.put("testNum",null);
            }else {
                //获取获取到测试次数
                Integer num = entity.getTestNum()==null?0: entity.getTestNum();
                int count = userRecordService.finAllByInstitutionNo(institutionNo);
                map.put("testNum",String.valueOf(num-count));
            }

            return success(map);
        }catch (Exception e){
            e.printStackTrace();
            return fail("查询失败");
        }
    }


}
