package com.yihu.jw.hospital.message.service;

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.hospital.message.BaseUserMessageDO;
import com.yihu.jw.entity.hospital.message.BaseUserMsgContentDO;
import com.yihu.jw.hospital.message.dao.BaseUserMessageDao;
import com.yihu.jw.hospital.message.dao.BaseUserMsgContentDao;
import com.yihu.jw.hospital.message.dao.MsgContentDao;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserMsgContentService extends BaseJpaService<BaseUserMsgContentDO, BaseUserMsgContentDao> {
    @Autowired
    private BaseUserMsgContentDao baseUserMsgContentDao;
    @Autowired
    private BaseUserMessageDao userMessageDao;
    @Autowired
    private MsgContentDao msgContentDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseBannerDoctorService bannerDoctorService;
    @Autowired
    private BaseUserMsgService baseUserMsgService;
    //获取评论
    public List getAllMessage(String relationCode){
        List<BaseUserMessageDO> list = msgContentDao.findByRelationCode(relationCode);
        for(int i=0;i<list.size();i++){
            String id = list.get(i).getId();
            List<BaseUserMsgContentDO> contentlist=baseUserMsgContentDao.getContentListByID(id);
            list.get(i).setMsgList(contentlist);
        }
        return  list;
    }
    //好评率计算
    public List<Map<String, Object>> countPoint(String doctor){
        Map<String,Object> params = new HashedMap();
        /*sqlForExpert.append("select * from wlyy_consult a left join wlyy_consult_team b" +
                " on a.id = b.consult left join base_evaluate_score c on a.relation_code = c.id   where 1=1");
        if(StringUtils.isNotEmpty(doctor)){
            sqlForExpert.append(" and b.doctor = '"+doctor+"'");
        }
        //计算专家咨询
        sqlForExpert.append(" and a.type in (1，2，3，15)");*/
        String sqlForExpert = dealSql(doctor,true);
        String countsqlForExpert = "SELECT COUNT(1) AS \"total\" FROM ("+sqlForExpert+") t";
        //专家咨询业务数总量
        Long count = 1L;
        //专家咨询业务数满意数量
        Long expertFix = 0L;
        System.out.println(countsqlForExpert);
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(countsqlForExpert,params);
        if(total!=null){
            if (!"0".equals(total.get(0).get("total").toString())) {
                count = hibenateUtils.objTransformLong(total.get(0).get("total"));
            }
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换

        }
        String sqlExpertFix = sqlForExpert+" and c.score >= 80";
        String countForExpert = "SELECT COUNT(1) AS \"total\" FROM ("+sqlExpertFix+") t";
        List<Map<String,Object>> expert = hibenateUtils.createSQLQuery(countForExpert,params);
        if (expert!=null){
            expertFix = hibenateUtils.objTransformLong(expert.get(0).get("total"));
        }
        String sql =dealSql(doctor,false);
        String countsqlForOnline= "SELECT COUNT(1) AS \"total\" FROM ("+sql+") t";
        //在线复诊业务数总量
        Long countOnlineTotal = 1L;
        //在线复诊业务数满意数量
        Long onlineFix = 0L;
        List<Map<String,Object>> totalOnline = hibenateUtils.createSQLQuery(countsqlForOnline,params);
        if(totalOnline!=null){
            if (!"0".equals(totalOnline.get(0).get("total").toString())){
                countOnlineTotal = hibenateUtils.objTransformLong(totalOnline.get(0).get("total"));

            }
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
        }
        String sqlOlineFix = sql+" and c.score >= 80";
        String countForFix = "SELECT COUNT(1) AS \"total\" FROM ("+sqlOlineFix+") t";
        System.out.println(countForFix
        );
        List<Map<String,Object>> onlineFixList = hibenateUtils.createSQLQuery(countForFix,params);
        if (onlineFixList!=null){
            onlineFix = hibenateUtils.objTransformLong(onlineFixList.get(0).get("total"));
        }
        float expertMY=(float) expertFix/count;
        float inlineMY = (float)onlineFix/countOnlineTotal;
        float totalConunt = (float)(expertFix+onlineFix)/(count+countOnlineTotal);
        DecimalFormat df = new DecimalFormat("0.00");
        List<Map<String,Object>> resultList= new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("zjzx",df.format(expertMY * 100)+"%");
        resultMap.put("zxfz",df.format(inlineMY * 100)+"%");
        resultMap.put("totalCount",df.format(totalConunt * 100)+"%");
        resultMap.put("doctor",doctor);
        resultList.add(resultMap);
        return resultList;

    }
    private String dealSql(String doctor,Boolean countExpert){
        StringBuffer sqlForExpert = new StringBuffer();
        sqlForExpert.append("select b.consult AS \"consult\" ,c.id AS \"id\" from  wlyy_consult_team b \n" +
                "left join base_evaluate_score c on b.consult = c.relation_code  \n" +
                "where 1=1");
        if(StringUtils.isNotEmpty(doctor)){
            sqlForExpert.append(" and b.doctor = '"+doctor+"'");
        }
        if(countExpert){
            sqlForExpert.append(" and (b.type =1 OR b.type =15)");
        }else{
            sqlForExpert.append(" and (b.type =9 OR b.type =16)");
        }
        return sqlForExpert.toString();
    }
    //医生主页展示的医生信息
    public JSONObject showContentByDoctor(String doctor,Integer page,Integer pageSize) throws ParseException {
        //锦旗总数和各个锦旗数量
        JSONObject jsonObject = bannerDoctorService.getDoctorBanners(doctor);
        //留言总数
        int messageTotal = userMessageDao.getAllMessageTotalCount(doctor);
        //查询医生各项评价平均分
        String sqlscore = "SELECT " +
                "AVG(a.score) AS \"score\"," +
                "a.score_type AS \"score_type\" " +
                "FROM base_evaluate a,base_evaluate_score b " +
                "WHERE " +
                "a.relation_code=b.id " +
                "AND b.doctor='" + doctor + "' " +
                "GROUP BY a.score_type ORDER BY  a.score_type ASC ";
        List<Map<String, Object>> listscore = jdbcTemplate.queryForList(sqlscore);

        Double doctorScore = new Double("0");

        if (listscore != null && listscore.size() > 0) {
            for (Map<String, Object> _listscore : listscore) {
                doctorScore += Double.parseDouble(_listscore.get("score").toString());
            }
        }
        doctorScore = doctorScore / 3;
        //总评
        jsonObject.put("doctorScore", doctorScore);
        if (listscore != null && listscore.size() > 0) {
            //各项平均分
            jsonObject.put("scoreDoctor", listscore);
        } else {
            jsonObject.put("scoreDoctor", null);
        }
        Integer curPage = (page-1)*pageSize;
        String filters = "receiver="+doctor;
        String fields ="";
        String sorts = "";
        List<BaseUserMessageDO> messageList=baseUserMsgService.search(fields,filters,sorts,page,pageSize);
        //List<BaseUserMessageDO> messageList= userMessageDao.getAllMessageByDoctor(doctor,curPage,pageSize);
        if (null!=messageList){
            for (BaseUserMessageDO baseUserMessageDO:messageList){
                String id = baseUserMessageDO.getId();
                Integer type = baseUserMessageDO.getType();
                List<BaseUserMsgContentDO> contentlist=baseUserMsgContentDao.getContentListByID(id);
                if (type!=null&&2==type){
                    baseUserMessageDO.setSenderName(baseUserMessageDO.getSenderName().substring(0,1)+"**");
                    String patientId = baseUserMessageDO.getSender();
                    for (BaseUserMsgContentDO bumLsit:contentlist){
                        bumLsit.setSenderName(bumLsit.getSender()==patientId?bumLsit.getSenderName().substring(0,1)+"**":bumLsit.getSenderName());
                        bumLsit.setReceiverName(bumLsit.getReceiver()==patientId?bumLsit.getReceiverName().substring(0,1)+"**":bumLsit.getReceiverName());
                    }
                }
                baseUserMessageDO.setMsgList(contentlist);
            }
            jsonObject.put("messageList", messageList);
        }
        return jsonObject;
    }

}
