package com.yihu.figure.controller.patient;

import com.yihu.figure.controller.BaseController;
import com.yihu.figure.model.dict.SystemDict;
import com.yihu.figure.model.patient.portrait.UserPortrait;
import com.yihu.figure.service.PortraitService;
import com.yihu.figure.service.dict.SystemDictService;
import com.yihu.figure.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenweida on 2017/3/8.
 * 用户标签
 */
@RestController
@RequestMapping(value = "/portrait", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "用户标签")
public class PortraitController extends BaseController {
    @Autowired
    private PortraitService portraitService;

    @Autowired
    private SystemDictService systemDictService;

    @ApiOperation(value = " 生成用户标签")
    @RequestMapping(value = "newPortrait", method = RequestMethod.POST)
    public String newPortrait(
            @ApiParam(name = "category", value = "标签父类", required = true) @RequestParam(value = "category", required = true) String category,
            @ApiParam(name = "subCategory", value = "标签子类", required = true) @RequestParam(value = "subCategory", required = true) String subCategory,
            @ApiParam(name = "value", value = "标签值", required = false) @RequestParam(value = "value", required = false) String value) {
        try {
            portraitService.newPortrait(category, subCategory);
            return success("成功");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = " 根据标签ID查找标签信息")
    @RequestMapping(value = "/findPortraitById", method = RequestMethod.GET)
    public String findPortraitById(
            @ApiParam(name = "id", value = "标签id", required = true) @RequestParam(value = "id", required = true) Long id) {
        try {
            UserPortrait up= portraitService.findPortraitById(id);
            return write(200, "获取成功！", "data", up);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation(value = " 获取患者的全部标签的全部服务")
    @RequestMapping(value = "/findPortraitServices", method = RequestMethod.GET)
    public String findPortraitServices(
            @ApiParam(name = "userCode", value = "用户code", required = true) @RequestParam(value = "userCode", required = true) String userCode) {
        try {
            List<UserPortrait> ups= portraitService.findPortraits(userCode);
            JSONArray jsonArray=new JSONArray();
            ups.stream().forEach(userPortrait->{
                if(!StringUtils.isEmpty(userPortrait.getRecommendService())){
                    JSONArray second=new JSONArray(userPortrait.getRecommendService());
                    jsonArray.put(second);
                }
            });
            return write(200, "获取成功！", "data", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation(value = "获取疾病-所在区域")
    @RequestMapping(value = "getPortraitsTown", method = RequestMethod.GET)
    public String getPortraits1002001(
            @ApiParam(name = "value", value = "疾病名称(糖尿病，高血压)", required = true) @RequestParam(value = "value", required = true) String value) {
        try {
            Map<String, Integer> data = portraitService.getPortraits("1001005", value);

            JSONObject returnjo=new JSONObject();
            JSONObject return1 = new JSONObject();

            for (Map.Entry<String, Integer> one : data.entrySet()) {
                if (!one.getKey().equals("allSize")) {
                    return1.put(one.getKey(), round(one.getValue(), data.get("allSize"), 4) + "");
                }
            }
            returnjo.put("data",return1);
            String name=getNameTownByKey(value,  return1);
//            List<SystemDict> systemDicts = systemDictService.getDictByDictName(name);
//            if(systemDicts!=null&&systemDicts.size()==1){
//                returnjo.put("message",systemDicts.get(0).getValue());//文字
//            }
            returnjo.put("message",name);
            return write(200, "获取成功！", "data", returnjo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }

    private String getNameTownByKey(String value,JSONObject return1) {

        DecimalFormat df   = new DecimalFormat("######0.00");

        String message="根据{disease}患者所在区域分布情况，{town}{disease}患者人群较高，" +
                "{disease}患者将占全市{townSize}%。重点关注{town}{disease}患者健康情况，" +
                " 需加强{disease}患者健康随访和健康指导。";
        Double haichan=return1.getDouble("海沧区");
        Double huli=return1.getDouble("湖里区");
        Double jimei=return1.getDouble("集美区");
        Double tongan=return1.getDouble("同安区");
        Double siming=return1.getDouble("思明区");
        Double xiangan=return1.getDouble("翔安区");
        if(haichan>huli&&haichan>jimei&&haichan>tongan&&haichan>siming&&haichan>xiangan){
            message=message.replace("{town}","海沧区").replace("{townSize}",df.format(haichan*100));
        }else if(huli>haichan&&
                huli>jimei&&
                huli>tongan&&
                huli>siming&&
                huli>xiangan){
            message=message.replace("{town}","湖里区").replace("{townSize}",df.format(huli*100));
        }else if(jimei>haichan&&
                jimei>huli&&
                jimei>tongan&&
                jimei>siming&&
                jimei>xiangan){
            message=message.replace("{town}","集美区").replace("{townSize}",df.format(jimei*100));
        }else if(tongan>huli&&
                tongan>jimei&&
                tongan>haichan&&
                tongan>siming&&
                tongan>xiangan){
            message=message.replace("{town}","同安区").replace("{townSize}",df.format(tongan*100));
        }else if(siming>huli&&
                siming>jimei&&
                siming>tongan&&
                siming>haichan&&
                siming>xiangan){
            message=message.replace("{town}","思明区").replace("{townSize}",df.format(siming*100));
        }else if(xiangan>huli&&
                xiangan>jimei&&
                xiangan>tongan&&
                xiangan>siming&&
                xiangan>haichan){
            message=message.replace("{town}","翔安区").replace("{townSize}",df.format(xiangan*100));
        }

        switch (value){
            case "高血压":{
                message=message.replace("{disease}","高血压");
                return message;
            }
            case "糖尿病":{
                message=message.replace("{disease}","糖尿病");
                return message;
            }
        }
        return "";
    }

    @ApiOperation(value = "获取疾病-所在年龄")
    @RequestMapping(value = "getPortraitsAge", method = RequestMethod.GET)
    public String getPortraits1002003(
            @ApiParam(name = "value", value = "疾病名称(糖尿病，高血压)", required = true) @RequestParam(value = "value", required = true) String value) {
        try {
            Map<String, Integer> data = portraitService.getPortraits("1001003", value);

            JSONObject returnjo=new JSONObject();
            JSONObject return1 = new JSONObject();

            for (Map.Entry<String, Integer> one : data.entrySet()) {
                if (!one.getKey().equals("allSize")) {
                    return1.put(one.getKey(), round(one.getValue(), data.get("allSize"), 4) + "");
                }
            }

            returnjo.put("data",return1);
            String name=getNameAgeByKey(value,return1);
            returnjo.put("message",name);
//            List<SystemDict> systemDicts = systemDictService.getDictByDictName(name);
//            if(systemDicts!=null&&systemDicts.size()==1){
//                returnjo.put("message",systemDicts.get(0).getValue());//文字
//            }

            return write(200, "获取成功！", "data", returnjo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }

    private String getNameAgeByKey(String value,JSONObject return1) {
        DecimalFormat df   = new DecimalFormat("######0.00");

        String message="针对全市区域高血压患者年龄段分布情况来看，高血压患者主要集中在{big}，" +
                "{Big65}%{disease}患者在65岁以上，" +
                "{between40_65}%{disease}患者在40-65岁，" +
                "{between20_40}%{disease}患者在20-40岁，" +
                "{small20}%{disease}患者在20岁以下。";

        Double Big65=return1.getDouble("65岁以上");
        Double between40_65=return1.getDouble("40-65岁");
        Double between20_40=return1.getDouble("20-40岁");
        Double small20=return1.getDouble("20岁以下");

        message=message.replace("{Big65}",df.format(Big65*100));
        message=message.replace("{between40_65}",df.format(between40_65*100));
        message=message.replace("{between20_40}",df.format(between20_40*100));
        message=message.replace("{small20}",df.format(small20*100));

        if(Big65>between40_65&&Big65>between20_40&&Big65>small20){
            message=message.replace("{big}","65岁以上");
        }else if(between40_65>Big65&&between40_65>between20_40&&between40_65>small20){
            message=message.replace("{big}","40-65岁");
        }else if(between20_40>Big65&&between20_40>between40_65&&between20_40>small20){
            message=message.replace("{big}","20-40岁");
        }else if(small20>Big65&&small20>between40_65&&small20>between20_40){
            message=message.replace("{big}","20岁以下");
        }
        switch (value){
            case "高血压":{
                message=message.replace("{disease}","高血压");
                return message;
            }
            case "糖尿病":{
                message=message.replace("{disease}","糖尿病");
                return message;
            }
        }
        return "";
    }

    @ApiOperation(value = "获取疾病-所在性别")
    @RequestMapping(value = "getPortraitsSex", method = RequestMethod.GET)
    public String getPortraits1001001(
            @ApiParam(name = "value", value = "疾病名称(糖尿病，高血压)", required = true) @RequestParam(value = "value", required = true) String value) {
        try {
            Map<String, Integer> data = portraitService.getPortraits("1001001", value);

            JSONObject returnjo=new JSONObject();
            JSONObject return1 = new JSONObject();

            for (Map.Entry<String, Integer> one : data.entrySet()) {
                if (!one.getKey().equals("allSize")) {
                    return1.put(one.getKey(), round(one.getValue(), data.get("allSize"), 4) + "");
                }
            }
            returnjo.put("data",return1);

            String name=getNameSexByKey(value,return1);
            returnjo.put("message",name);

//            List<SystemDict> systemDicts = systemDictService.getDictByDictName(name);
//            if(systemDicts!=null&&systemDicts.size()==1){
//                returnjo.put("message",systemDicts.get(0).getValue());//文字
//            }

            return write(200, "获取成功！", "data", returnjo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }

    private String getNameSexByKey(String value,JSONObject return1) {
        DecimalFormat df   = new DecimalFormat("######0.00");
        String message="根据区域性别分布比例来看，{sex}性{disease}患病几率较高，分别是男性患糖尿病比例为{arg1}%，女性患糖尿病比例为{arg2}%。";
        Double boy=return1.getDouble("男");
        Double girl=return1.getDouble("女");
        message=message.replace("{arg1}",df.format(boy*100));
        message=message.replace("{arg2}",df.format(girl*100));
        if(boy>girl){
            message=message.replace("{sex}","男");
        }else{
            message=message.replace("{sex}","女");
        }
        switch (value){
            case "高血压":{
                message=message.replace("{disease}","高血压");
                return message;
            }
            case "糖尿病":{
                message=message.replace("{disease}","糖尿病");
                return message;
            }
        }
        return "";
    }

    @ApiOperation(value = "获取一级的标签信息")
    @RequestMapping(value = "getPortraitsLevel1", method = RequestMethod.GET)
    public String getPortraitsLevel1(
            @ApiParam(name = "key", value = "1 疾病 2 健康分布", required = true) @RequestParam(value = "key", required = true) String key) {
        try {
            Map<String, Integer> data = portraitService.getPortraitsLevel1(key);
            JSONObject returnjo=new JSONObject();
            JSONObject return1 = new JSONObject();

            for (Map.Entry<String, Integer> one : data.entrySet()) {
                if (!one.getKey().equals("allSize")) {
                    JSONObject return2 = new JSONObject();
                    return2.put("count", one.getValue());
                    return2.put("scale", round(one.getValue(), data.get("allSize"), 4) + "");
                    return1.put(one.getKey(), return2);
                }
            }
            //特殊处理
            if("2".equals(key)){
                return1 = new JSONObject();

                JSONObject return2 = new JSONObject();
                return2.put("count", "0");
                return2.put("scale", "0.2977");
                return1.put("患病人群", return2);

                return2 = new JSONObject();
                return2.put("count", "0");
                return2.put("scale", "0.0001");
                return1.put("恢复期人群", return2);

                return2 = new JSONObject();
                return2.put("count", "0");
                return2.put("scale", "0.7022");
                return1.put("健康人群", return2);

            }
            returnjo.put("data",return1);//数据

            String name=getNameByKey(key,return1);
//            List<SystemDict> systemDicts = systemDictService.getDictByDictName(name);
//            if(systemDicts!=null&&systemDicts.size()==1){
//                returnjo.put("message",systemDicts.get(0).getValue());//文字
//            }
            returnjo.put("message",name);
            return write(200, "获取成功！", "data", returnjo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }

    private String getNameByKey(String key,JSONObject return1) {
        switch (key){
            case "1":{
                return "从居民近期疾病分析来看，高血压和糖尿病占比较高，需加强高血压和糖尿病人群健康预防和教育。";
            }
            case "2":{
                String message=" 根据市区内居民健康状况分布情况，患病人群占比29.77%，" +
                        " 恢复期人群占比0.01%，健康人群占比70.22%。" ;
                        //" 从区域健康情况看{disease}占比较高，需加强{disease}健康管理和服务。";

//                DecimalFormat df   = new DecimalFormat("######0.00");
//
//                Double huanbing=return1.getJSONObject("患病人群").getDouble("scale");
//                Double huifu=return1.getJSONObject("恢复期人群").getDouble("scale");
//                Double jiankang=return1.getJSONObject("健康人群").getDouble("scale");
//
//                message= message.replace("{huanbing}",df.format(huanbing*100));
//                message=message.replace("{huifu}",df.format(huifu*100));
//                message=message.replace("{jiankang}",df.format(jiankang*100));
//
//                if(huanbing>huifu&&huanbing>jiankang){
//                    message=message.replace("{disease}","患病人群");
//                }else if(huifu>huanbing&&huifu>jiankang){
//                    message=message.replace("{disease}","恢复期人群");
//                }else if(jiankang>huanbing&&jiankang>huifu){
//                    message=message.replace("{disease}","健康人群");
//                }
                return message;
            }
        }
        return "";
    }

    /**
     * 计算百分比的函数
     * @param up  分子
     * @param down 分母
     * @param scale 保留几位小数
     * @return
     */
    public static double round(Integer up, Integer down, int scale) {
        try {

            if (scale < 0) {
                throw new IllegalArgumentException(
                        "The scale must be a positive integer or zero");
            }
            BigDecimal upB = new BigDecimal(up);
            BigDecimal downB = new BigDecimal(down);
            return upB.divide(downB, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception e) {
            return 0;
        }
    }

}
