package com.rf.psychological.scale.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.model.DimensionEntity;
import com.rf.psychological.enums.UserRole;
import com.rf.psychological.scale.dao.dto.DimensionEntityDto;
import com.rf.psychological.scale.dao.dto.ResultDto;
import com.rf.psychological.scale.dao.dto.WarnEntityDto;
import com.rf.psychological.scale.dao.model.DimensionOrgEntity;
import com.rf.psychological.scale.dao.model.ScaleMarksEntity;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.dao.model.WarnEntity;
import com.rf.psychological.scale.service.*;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:zzf
 * @Date:2022/10/9:16:10
 * @Description:预警信息处理类
 */
@Slf4j
@RestController
@RequestMapping("/warn")
@Api(tags = "预警信息处理")
public class WarnController extends BaseController {

    @Autowired
    private DimensionService dimensionService;

    @Autowired
    private ScaleMarksService scaleMarksService;

    @Autowired
    private DimensionOrgService dimensionOrgService;

    @Autowired
    private WarnService warnService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private UserService userService;
    @GetMapping("/{flag}/{institutionNo}")
    @SafetyProcess
    @ApiOperation(value = "查询量表维度信息",notes = "flag:量表标志")
    public Result findDimensionByFlag(@PathVariable String flag,@PathVariable String institutionNo){
        List<DimensionEntity> dimensionEntityList = this.dimensionService.getDimensionByFlag(flag);
        List<DimensionEntityDto> dimensionEntityDtos = new ArrayList<>();
        if(dimensionEntityList != null && dimensionEntityList.size()>0){
            dimensionEntityList.forEach(dimensionEntity -> {
                List<ScaleMarksEntity> scaleMarksEntityList = this.scaleMarksService.getScaleMarksByFlagAndName(dimensionEntity.getFlag(),dimensionEntity.getName());
                DimensionEntityDto dimensionEntityDto = new DimensionEntityDto();
                dimensionEntityDto.setId(dimensionEntity.getId());
                dimensionEntityDto.setFlag(dimensionEntity.getFlag());
                dimensionEntityDto.setName(dimensionEntity.getName());
                if(scaleMarksEntityList != null && scaleMarksEntityList.size() > 0 ){
                    //取最大值最小值
                    String minScore = scaleMarksEntityList.get(0).getScoreStart();
                    String maxScore = scaleMarksEntityList.get(0).getScoreEnd();
                    for (int i = 1; i < scaleMarksEntityList.size(); i++) {
                        if(Double.parseDouble(scaleMarksEntityList.get(i).getScoreStart()) < Double.parseDouble(minScore)){
                            minScore = scaleMarksEntityList.get(i).getScoreStart();
                        }
                        if(Double.parseDouble(scaleMarksEntityList.get(i).getScoreEnd()) > Double.parseDouble(maxScore)){
                            maxScore = scaleMarksEntityList.get(i).getScoreEnd();
                        }
                    }
                    dimensionEntityDto.setMinScore(minScore);
                    dimensionEntityDto.setMaxScore(maxScore);
                }
                //查询阈值信息
                DimensionOrgEntity dimensionOrgEntity =  this.dimensionOrgService.findByInstitutionNoAndDimensionId(institutionNo,dimensionEntity.getId());
                if(dimensionOrgEntity != null){
                    dimensionEntityDto.setThreshold(dimensionOrgEntity.getThreshold());
                    dimensionEntityDto.setLogic(dimensionOrgEntity.getLogic());
                    dimensionEntityDto.setThresholdId(dimensionOrgEntity.getId());
                }
                dimensionEntityDtos.add(dimensionEntityDto);
            });
        }
        return success(dimensionEntityDtos);
    }

    @GetMapping("find/dimensionById/{dimensionId}/{institutionNo}")
    @SafetyProcess
    @ApiOperation(value = "查询单个量表维度的信息",notes = "dimensionId:维度id；institutionNo：机构编号")
    public Result findDimensionById(@PathVariable String dimensionId,@PathVariable String institutionNo){
        DimensionEntity dimensionEntity = this.dimensionService.findById(dimensionId);
            List<ScaleMarksEntity> scaleMarksEntityList = this.scaleMarksService.getScaleMarksByFlagAndName(dimensionEntity.getFlag(),dimensionEntity.getName());
            DimensionEntityDto dimensionEntityDto = new DimensionEntityDto();
            dimensionEntityDto.setId(dimensionEntity.getId());
            dimensionEntityDto.setFlag(dimensionEntity.getFlag());
            dimensionEntityDto.setName(dimensionEntity.getName());
            if(scaleMarksEntityList != null && scaleMarksEntityList.size() > 0 ){
                //取最大值最小值
                String minScore = scaleMarksEntityList.get(0).getScoreStart();
                String maxScore = scaleMarksEntityList.get(0).getScoreEnd();
                for (int i = 1; i < scaleMarksEntityList.size(); i++) {
                    if(Double.parseDouble(scaleMarksEntityList.get(i).getScoreStart()) < Double.parseDouble(minScore)){
                        minScore = scaleMarksEntityList.get(i).getScoreStart();
                    }
                    if(Double.parseDouble(scaleMarksEntityList.get(i).getScoreEnd()) > Double.parseDouble(maxScore)){
                        maxScore = scaleMarksEntityList.get(i).getScoreEnd();
                    }
                }
                dimensionEntityDto.setMinScore(minScore);
                dimensionEntityDto.setMaxScore(maxScore);
            }
            //查询阈值信息
            DimensionOrgEntity dimensionOrgEntity =  this.dimensionOrgService.findByInstitutionNoAndDimensionId(institutionNo,dimensionEntity.getId());
            if(dimensionOrgEntity != null){
                dimensionEntityDto.setThreshold(dimensionOrgEntity.getThreshold());
                dimensionEntityDto.setLogic(dimensionOrgEntity.getLogic());
                dimensionEntityDto.setThresholdId(dimensionEntity.getId());
            }
        return success(dimensionEntityDto);
    }


    @PostMapping("/threshold/set")
    @ApiOperation(value = "设置阈值",notes = "id:数据库id，增加时为空，修改时必填；institutionNo:机构编号；dimensionId：维度id；threshold：阈值；logic：逻辑")
    @SafetyProcess
    public Result setThreshold(@RequestBody String json) throws Exception {
        JSONArray jsonArray = JSONArray.parseArray(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        List<DimensionOrgEntity> dimensionOrgEntity = jsonArray.toJavaList(DimensionOrgEntity.class);
        if(dimensionOrgEntity != null &&dimensionOrgEntity.size()>0){
            dimensionOrgEntity.forEach(item ->{
                 this.dimensionOrgService.save(item);
            });
        }
        return success();
    }

    @PostMapping("/find/threshold")
    @SafetyProcess
    @ApiOperation(value = "查询阈值",notes = "id:数据库id，可为空；institutionNo：机构编号，不能为空；scaleName:量表名称 ；scaleType：量表类型;dimensionId:维度id")
    public Result findThreshold(@RequestBody String json) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        if(!jsonObject.containsKey("institutionNo") || StringUtils.isBlank(jsonObject.getString("institutionNo"))){
            return fail("机构编号不能为空");
        }
//        if(!jsonObject.containsKey("flag") || StringUtils.isBlank(jsonObject.getString("flag"))){
//            return fail("量表标志不能为空");
//        }
        List<DimensionOrgEntity> dimensionOrgEntities = this.dimensionOrgService.find(jsonObject);
        return success(dimensionOrgEntities);
    }

    @DeleteMapping("/delete/threshold/{dimensionId}/{institutionNo}")
    @SafetyProcess
    @ApiOperation(value = "删除阈值")
    public Result deleteThreshold(@PathVariable String dimensionId, @PathVariable String institutionNo)  {

        this.warnService.deleteByFlagAndInstitutionNo(dimensionId,institutionNo);
        this.dimensionOrgService.deleteByFlagAndInstitutionNo(dimensionId,institutionNo);
        return success();
    }


    @PostMapping("/save")
    @ApiOperation(value = "保存",notes = "id:新增时未空，修改时必填；")
    @SafetyProcess
    public Result saveWarn(@RequestBody String json) throws Exception {

        WarnEntity warnEntity = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"))).toJavaObject(WarnEntity.class);
        warnEntity = this.warnService.save(warnEntity);
        return success(warnEntity);
    }

   /* @PostMapping("/find/warn")
    @ApiOperation(value = "查找记录",notes = "id:主键id；userId：用户id；institutionNo:机构编号；flag：量表标志；dimensionId：维度id；resultId：测试结果id")
    @SafetyProcess
    @Deprecated
    public Result find(@RequestBody String json) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        if(jsonObject.containsKey("userName") && StringUtils.isNotBlank(jsonObject.getString("userName"))){
            List<String> userId = new ArrayList<>();
            Page<UserEntity> user = this.userService.findUserByPhoneOrNameInInstitutionNo(1, 10000, jsonObject.getString("institutionNo"), jsonObject.getString("userName"), UserRole.COMMON);
            if(user.getTotalElements()>0){
                user.getContent().forEach(item ->{
                    userId.add(item.getId());
                });
                jsonObject.put("userId",userId);
            }else {
                return success("");
            }

        }
        Page<WarnEntity> warnEntities = this.warnService.find(jsonObject);
        List<WarnEntityDto> dtoList = new ArrayList<>();
        if(warnEntities.getTotalElements() >0){
            warnEntities.getContent().forEach(item ->{
                WarnEntityDto warnEntityDto = new WarnEntityDto();
                warnEntityDto.setId(item.getId());
                warnEntityDto.setCreateTime(item.getCreateTime());
                warnEntityDto.setScore(item.getScore());
                warnEntityDto.setDimensionId(item.getDimensionId());
                warnEntityDto.setResultId(item.getResultId());
                warnEntityDto.setInstitutionNo(item.getInstitutionNo());
                warnEntityDto.setUserId(item.getUserId());
                warnEntityDto.setUserName(this.userService.findOne(item.getUserId()).getPetName());
                warnEntityDto.setDimensionName(this.dimensionService.findById(item.getDimensionId()).getName());
                dtoList.add(warnEntityDto);
            });
        }
        JSONObject resultJson = new JSONObject();
        resultJson.put("data",dtoList);
        resultJson.put("allNum",warnEntities.getTotalElements());
        return success(resultJson);
    }*/

    @PostMapping("/find/threshold1")
    @SafetyProcess
    @ApiOperation(value = "查询已设置量表",notes = "institutionNo  机构编号; scaleName：量表名称；scaleType：量表类别；pageNum:页数；pageSize：每页记录数")
    public Result findTSetd(@RequestBody String json) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        //查询机构已设置过阈值的量表信息
        List<SubjectEntity> subjectEntities = this.subjectService.getSubjectListByAuthSeted(jsonObject.getIntValue("pageNum"),jsonObject.getIntValue("pageSize"),jsonObject.getString("scaleName"),jsonObject.getString("institutionNo"),jsonObject.getString("scaleType"));
        int allNum = this.subjectService.getSubjectListByAuthSeted(jsonObject.getString("scaleName"),jsonObject.getString("institutionNo"),jsonObject.getString("scaleType"));
        JSONObject resultJson = new JSONObject();
        resultJson.put("allNum",allNum);
        resultJson.put("data",subjectEntities);
        return success(resultJson);
    }

    @PostMapping("/find/warn")
    @ApiOperation(value = "查找记录",notes = "resultId：测试结果id;pageNum:页数；pageSize：每页记录数")
    @SafetyProcess
    public Result find(@RequestBody String json) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        int pageNum = jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize");
        String flag = jsonObject.getString("flag");
        String institutionNo = jsonObject.getString("institutionNo");
        String searckKey = jsonObject.getString("searckKey");
        List<ResultDto> resultDtos = new ArrayList<>();
        int allCount = this.warnService.findResultListCount(flag,institutionNo,searckKey);
        List<Map<String,Object>> resultIdList = this.warnService.findResultList(pageNum,pageSize,flag,institutionNo,searckKey);
        if(resultIdList!= null && resultIdList.size()>0){
            resultIdList.forEach(item -> {
                System.out.println(item);
                ResultDto resultDto = new ResultDto();
                resultDto.setResultId((String) item.get("result_id"));
                resultDto.setCreateTime((String) item.get("create_time"));
                resultDto.setUserId((String) item.get("user_id"));

                resultDto.setUserName(this.userService.findUserById((String) item.get("user_id")).getPetName());
                List<WarnEntity> warnEntities = this.warnService.findByResultId(resultDto.getResultId());
                List<WarnEntityDto> warnEntityDtoList = new ArrayList<>();
                warnEntities.forEach(warnEntity ->{
                    WarnEntityDto warnEntityDto = new WarnEntityDto();
                    warnEntityDto.setFlag(warnEntity.getFlag());
                    warnEntityDto.setId(warnEntity.getId());
                    warnEntityDto.setCreateTime(warnEntity.getCreateTime());
                    warnEntityDto.setScore(warnEntity.getScore());
                    warnEntityDto.setDimensionId(warnEntity.getDimensionId());
                    warnEntityDto.setResultId(warnEntity.getResultId());
                    warnEntityDto.setInstitutionNo(warnEntity.getInstitutionNo());
                    warnEntityDto.setUserId(warnEntity.getUserId());
                    warnEntityDto.setThreshold(warnEntity.getThreshold());
                    warnEntityDto.setLogic(warnEntity.getLogic());
                    warnEntityDto.setUserName(resultDto.getUserName());
                    warnEntityDto.setDimensionName(this.dimensionService.findById(warnEntity.getDimensionId()).getName());
                    //分值范围
                    List<ScaleMarksEntity> scaleMarksEntityList = this.scaleMarksService.getScaleMarksByFlagAndName(jsonObject.getString("flag"),warnEntityDto.getDimensionName());
                    if(scaleMarksEntityList != null && scaleMarksEntityList.size() > 0 ){
                        //取最大值最小值
                        String minScore = scaleMarksEntityList.get(0).getScoreStart();
                        String maxScore = scaleMarksEntityList.get(0).getScoreEnd();
                        for (int i = 1; i < scaleMarksEntityList.size(); i++) {
                            if(Double.parseDouble(scaleMarksEntityList.get(i).getScoreStart()) < Double.parseDouble(minScore)){
                                minScore = scaleMarksEntityList.get(i).getScoreStart();
                            }
                            if(Double.parseDouble(scaleMarksEntityList.get(i).getScoreEnd()) > Double.parseDouble(maxScore)){
                                maxScore = scaleMarksEntityList.get(i).getScoreEnd();
                            }
                        }
                        warnEntityDto.setMinScore(minScore);
                        warnEntityDto.setMaxScore(maxScore);
                    }
                    //查询阈值信息
                    DimensionOrgEntity dimensionOrgEntity =  this.dimensionOrgService.findByInstitutionNoAndDimensionId(jsonObject.getString("institutionNo"),warnEntity.getDimensionId());
                    if(dimensionOrgEntity != null){
                        warnEntityDto.setThresholdId(warnEntity.getDimensionId());
                    }
                    //判断逻辑
                    //阈值
                    warnEntityDtoList.add(warnEntityDto);
                });
                resultDto.setWarnEntity(warnEntityDtoList);
                resultDtos.add(resultDto);
            });

        }
        JSONObject resultJson = new JSONObject();
        resultJson.put("allNum",allCount);
        resultJson.put("data",resultDtos);
        return success(resultJson);
    }






}
