package com.yihu.jw.evaluate.score.service;

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateScoreDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zmk
 * @vsrsion 1.0
 * Created at 2019/12/6
 */
@Service
@Transactional
public class BaseEvaluateScoreService extends BaseJpaService<BaseEvaluateScoreDO, BaseEvaluateScoreDao> {

    @Autowired
    private BaseEvaluateScoreDao baseEvaluateScoreDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${wechat.id}")
    private String wxId;

    /**
     * 计算总评分，周同比，日环比
     * @param area
     * @param level
     * @return
     */
    public Map<String, Object> getScoreAndPercentage(String area, int level){
        HashMap<String, Object> map = new HashMap<>();
        //今日凌晨、当前时间
        String startTime = DateUtil.getStringDateShort()+" 00:00:00";
        String nowTime = DateUtil.getStringDate();
        //昨日时间
        String oneDayAgo = DateUtil.getNextDay(startTime, -1);
        String oneStrTime = oneDayAgo + " 00:00:00";
        String oneEndTime = oneDayAgo + " 23:59:59";
        //七天之前时间
        String sevenDayAgo = DateUtil.getNextDay(startTime, -7);
        String sevenStrTime = sevenDayAgo + " 00:00:00";
        String sevenEndTime = sevenDayAgo + " 23:59:59";
        //服务总评分
        map.put("totalAvgScore",getAvgScore(null, null, area, level));
        //周同比
        map.put("weekJudge",judgeScore(getAvgScore(startTime, nowTime, area, level),getAvgScore(sevenStrTime, sevenEndTime, area, level)));
        //日环比
        map.put("dayJudge",judgeScore(getAvgScore(startTime, nowTime, area, level),getAvgScore(oneStrTime, oneEndTime, area, level)));
        return map;
    }


    /**
     * 计算平均分
     * @param startTime
     * @param endTime
     * @param area
     * @param level
     * @return
     */
    private Double getAvgScore(String startTime,String endTime,String area,int level){
        String sql = "select count(*) as total, sum(score) as score from base_evaluate_score o where ";

        if (level == 4){
            sql += " o.doctor IN (SELECT doctor_code FROM `base_doctor_hospital` dh where dh.org_code ='"+area+"' and dh.del=1)";
        }if (level==2){
            sql += " 1=1 ";
        }else if (level == 5){
            sql += " o.doctor IN (SELECT doctor_code FROM `base_doctor_hospital` dh where dh.dept_code ='"+area+"' and dh.del=1)";
        }else if (level == 6){
            sql += " o.doctor ='"+area+"'";
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            if (startTime != null){
                sql += " and o.create_time >= to_date('" + startTime + "','yyyy-mm-dd hh24:mi:ss')";
            }
            if(endTime != null){
                sql += " and o.create_time <=to_date('" + endTime + "','yyyy-mm-dd hh24:mi:ss')";
            }
        }else {
            if (startTime != null){
                sql += " and o.create_time >='" + startTime + "'";
            }
            if(endTime != null){
                sql += " and o.create_time <='" + endTime + "'";
            }
        }

        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        double total = 0d;
        double score = 0d;
        if(rstotal != null && rstotal.size()>0){
            if (null == rstotal.get(0).get("score")){
                return 0.0;
            }
            total = Double.valueOf((rstotal.get(0).get("total")).toString());
            score = Double.valueOf((rstotal.get(0).get("score")).toString());
            if (0 == total || 0 == score){
                return 0.0;
            }
        }
        double avgScore = score / total;
        DecimalFormat df = new DecimalFormat("0.0");//格式化小数，不足的补0
        String filesize = df.format(avgScore);
        return Double.valueOf(filesize);
    }


    /**
     * 计算周同比和日环比
     * @param nowScore
     * @param oldScore
     */
    public Object judgeScore(Double nowScore, Double oldScore){
        JSONObject object = new JSONObject();
        if (nowScore > oldScore){
            if (oldScore == 0){
                object.put("trend",1);
                object.put("percentage",nowScore.toString());
            }else {
                Double difScore = nowScore - oldScore;
                String percentage = getPercentage((float) (difScore.intValue()), (float) oldScore.intValue());
                object.put("trend",1);
                object.put("percentage",percentage);
            }
        }else if (nowScore < oldScore){
            if (nowScore == 0){
                object.put("trend",-1);
                object.put("percentage",oldScore.toString());
            }else {
                Double difScore = oldScore - nowScore;
                String percentage = getPercentage((float) (difScore.intValue()), (float) oldScore.intValue());
                object.put("trend",-1);
                object.put("percentage",percentage);
            }
        }else {
            String percentage = "0%";
            object.put("trend",0);
            object.put("percentage",percentage);
        }
        return object;
    }

    /**
     * 计算百分比
     * @param num1
     * @param num2
     * @return
     */
    public String getPercentage(float num1,float num2){
        //创建一个数值格式化对象
        NumberFormat format = NumberFormat.getInstance();
        //设置精确到小数点后两位
        format.setMaximumFractionDigits(2);
        String result = format.format(num1 / num2 * 100) + "%";
        return result;
    }

}
