package com.yihu.wlyy.service.app.message;

import java.util.*;

import javax.transaction.Transactional;

import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.service.BaseService;

/**
 * 消息业务处理类
 *
 * @author George
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class MessageService extends BaseService {

    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDao patientDao;

    /**
     * IM消息数量
     */
    private String getImMsgAmount(String doctor) {
        String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                + "/api/v1/chats/msg/amount?user_id=" + doctor;
        return HttpClientUtil.get(url, "UTF-8");
    }

    /**
     * 汇总查询医生的消息总数
     *
     * @param doctor
     * @return
     */
    public JSONObject findDoctorAllMessageAmount(String doctor) {
        // 三师咨询未读消息总数
        int consult = 0;
        try {
            consult = consultTeamDao.amountAllDoctorUnread(doctor);
        } catch (Exception e) {
        }
        // 签约未读消息总数
        int sign = messageDao.amountUnreadByReceiver(doctor);
        // 体征指标未读消息总数
        int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
        JSONObject json = new JSONObject();
        json.put("consultTeam", consult);
        json.put("sign", sign);
        json.put("healthIndex", healthIndex);
        return json;
    }

    /**
     * 查询医生未读消息和最后消息
     */
    public JSONObject findDoctorAllMessage(String doctor) throws Exception {

        // 签约未读消息总数
        int sign = messageDao.amountUnreadByReceiver(doctor);
        JSONObject signJson = new JSONObject();
        signJson.put("amount", sign);
        if (sign > 0) {
            PageRequest pageRequest = new PageRequest(0, 1);
            Page<Message> msgs = messageDao.amountUnreadLastByReceiver(doctor, pageRequest);

            if (msgs != null && msgs.getSize() > 0) {
                for (Message msg : msgs) {
                    JSONObject msgJson = new JSONObject();
                    msgJson.put("title", msg.getTitle());
                    msgJson.put("type", msg.getType());
                    if (msg.getSignStatus().equals("4")) {
                        msgJson.put("msg", msg.getSenderName() + "申请与您解除家庭签约");
                    } else {
                        msgJson.put("msg", msg.getSenderName() + "申请与您签约家庭医生");
                    }
                    msgJson.put("msgTime", DateUtil.dateToStrLong(msg.getCzrq()));
                    signJson.put("lastMessage", msgJson);
                }
            }
        }

        // 体征指标未读消息总数
        Integer healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
        JSONObject indexJson = new JSONObject();
        indexJson.put("amount", healthIndex);
        if (healthIndex > 0) {
            PageRequest pageRequest = new PageRequest(0, 1);
            List<Message> msgs = messageDao.amountUnreadHealthLastByReceiver(doctor, pageRequest);

            if (msgs != null && msgs.size() > 0) {
                JSONObject msgJson = new JSONObject();
                msgJson.put("title", msgs.get(0).getTitle());
                msgJson.put("type", msgs.get(0).getType());
                msgJson.put("msg", msgs.get(0).getContent());
                msgJson.put("msgTime", DateUtil.dateToStrLong(msgs.get(0).getCzrq()));
                indexJson.put("lastMessage", msgJson);
            }
        }

        //获取未读系统消息
        List<Message> systemMessage = messageDao.getSystemMessageUnread(doctor);
        JSONObject systemJson = new JSONObject();
        if (systemMessage != null && systemMessage.size() > 0) {
            systemJson.put("amount", systemMessage.size());
            JSONObject msgJson = new JSONObject();
            msgJson.put("title", systemMessage.get(0).getTitle());
            msgJson.put("type", systemMessage.get(0).getType());
            msgJson.put("msg", systemMessage.get(0).getContent());
            msgJson.put("msgTime", DateUtil.dateToStrLong(systemMessage.get(0).getCzrq()));
            systemJson.put("lastMessage", msgJson);
        } else {
            systemJson.put("amount", 0);
        }

        JSONObject json = new JSONObject();
        json.put("imMsgCount", getImMsgAmount(doctor));//IM消息数量
        json.put("sign", signJson);//签约数
        json.put("healthIndex", indexJson);//健康指标
        json.put("system", systemJson);//系统消息

        return json;
    }


    /**
     * 查询健康咨询列表
     *
     * @param doctor   医生标识
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<ConsultTeam> findConsultListByDoctor(String doctor, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        //健康咨询
        if (id > 0) {
            return consultTeamDao.findListByUnreadDoctor(doctor, id, pageRequest);
        } else {
            return consultTeamDao.findListByUnreadDoctor(doctor, pageRequest);
        }

    }

    /**
     * 查询体征消息列表
     *
     * @param doctor   医生标识
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<Message> findHealthListByDoctor(String doctor, long id, int pagesize, String isRead) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("receiver", new SearchFilter("receiver", Operator.EQ, doctor));
        filters.put("type", new SearchFilter("type", Operator.EQ, "2"));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        if (StringUtils.isNoneEmpty(isRead)) {
            filters.put("read", new SearchFilter("read", Operator.EQ, Integer.parseInt(isRead)));
        }
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
    }

    /**
     * 更新体征消息为已读
     *
     * @param msgid
     */
    public int readHealth(long msgid) {
        return messageDao.read(msgid);
    }

    /**
     * 未读签约信息
     */
    public Message findUnreadSign(String sender, String receiver, String signStatus) {

        return messageDao.findUnreadSign(sender, receiver, signStatus);
    }

    public Page<Message> find(String doctor, String type, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("receiver", new SearchFilter("receiver", Operator.EQ, doctor));
        filters.put("type", new SearchFilter("type", Operator.EQ, type));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
    }

    public JSONObject findMessageNum(String doctor, Integer type) {
        JSONObject jo = new JSONObject();
        //得到消息总数
        int count = messageDao.findMessageNum(doctor, type);
        String DateString = "";
        String message = "";
        String sql = "select w.* from wlyy_message w where w.type='" + type + "' and w.receiver='" + doctor + "' order by w.czrq desc limit 0,1";
        List<Message> returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Message.class));
        if (returnList != null && returnList.size() > 0) {
            Message m = returnList.get(0);
            DateString = DateUtil.dateToStrShort(m.getCzrq());
            message = m.getContent();

        }
        jo.put("count", count);
        jo.put("message", message);
        jo.put("date", DateString);
        return jo;
    }

    /**
     * 获取超标指标消息--根据患者分组
     */
    public List<Map<String, Object>> getHealthIndexMessage(String doctor) throws Exception {
        List<Map<String, Object>> re = new ArrayList<>();
        String sql = "select a.sender,a.tz_type,count(1) count,max(date_format(a.czrq,'%Y-%c-%d %h:%i:%s')) last_time from wlyy_Message a where a.receiver='" + doctor + "' and a.has_read='1' and a.type='2' group by a.sender,a.tz_type order by last_time desc";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

        for (Map<String, Object> item : list) {
            Map<String, Object> obj = new HashMap<>();
            String patientCode = String.valueOf(item.get("sender"));
            //获取患者信息
            Patient patient = patientDao.findByCode(patientCode);
            if (patient != null) {
                String type = String.valueOf(item.get("tz_type")); //1血糖，2血压，3体重，4腰
                obj.put("patient", patientCode);
                obj.put("type", type);
                obj.put("time", item.get("last_time"));
                obj.put("name", patient.getName());
                obj.put("sex", patient.getSex());
                obj.put("birthday", DateUtil.dateToStrShort(patient.getBirthday()));
                obj.put("sex", patient.getSex());
                obj.put("photo", patient.getPhoto());
                if ("1".equals(type)) {
                    obj.put("message", "有" + item.get("count") + "条血糖异常未读消息");
                } else if ("2".equals(type)) {
                    obj.put("message", "有" + item.get("count") + "条血压异常未读消息");
                } else {
                    break;
                }

                re.add(obj);
            } else {
                System.out.print("not exit patient!code:" + patientCode);
            }
        }
        return re;
    }

    /**
     * 获取患者超标指标消息
     */
    public List<Map<String, String>> getHealthIndexMessageByPatient(String doctor, String patient, String type, Integer page, Integer pagesize) throws Exception {

        List<Map<String, String>> re = new ArrayList<>();
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "czrq");
        Pageable pageRequest = new PageRequest(page - 1, pagesize, sort);
        List<Message> list = messageDao.getHealthIndexMessageByPatient(doctor, patient, type, pageRequest);

        if (list != null && list.size() > 0) {
            for (Message item : list) {
                Map<String, String> map = new HashMap<>();
                map.put("id", String.valueOf(item.getId()));
                map.put("sender", item.getSender());
                map.put("senderName", item.getSenderName());
                map.put("senderPhoto", item.getSenderPhoto());
                map.put("type", type);
                map.put("read", String.valueOf(item.getRead()));
                map.put("sex", String.valueOf(item.getSex()));
                map.put("value1", String.valueOf(item.getValue1()));
                map.put("value2", String.valueOf(item.getValue2()));
                map.put("czrq", DateUtil.dateToStrLong(item.getCzrq()));
                re.add(map);

                item.setRead(0);//把消息设置为已读
            }
            messageDao.save(list);
        }
        return re;
    }

    /**
     * 获取系统消息
     */
    public List<Message> getSystemMessage(String doctor, Integer page, Integer pagesize) throws Exception {
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "czrq");
        // 分页信息
        Pageable pageRequest = new PageRequest(page - 1, pagesize, sort);
        return messageDao.getSystemMessage(doctor, pageRequest);
    }

    /**
     * 设置某类消息已读
     *
     * @param doctor
     * @param type
     */
    public void setMessageReaded(String doctor, int type) {
        if (type == 3) {
            messageDao.setSysMessageReaded(doctor);
        } else {
            messageDao.setMessageReaded(doctor, type);
        }
    }
}
