package com.yihu.wlyy.statistics.job.message;

import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import com.yihu.wlyy.statistics.service.DoctorWorkTimeService;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/7.
 */

@Component
@Scope("prototype")
public class NoticeJob implements Job {
    public static String jobKey = "Notice_JOB";
    public static String jobCron = "0 0 8,14 * * ?"; //每天8点，14点，20 点执行一次
    private static String noticeKey1 = "D_ST_01";//专科
    private static String noticeKey2 = "D_ST_02";//全科
    private static String noticeKey3 = "D_ST_03";//健康管理师
    private static String noticeTitle = "系统消息";

    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private QuartzJobLogDao dbStorage;
    @Autowired
    private DoctorDao doctorDao;
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MessageDao messageDao;

    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(jobKey);
        quartzJobLog.setJobName(jobKey);
        try {
            List<Doctor> doctors = doctorDao.findAllDoctors();
            //得到所有未发送的医生的通知
            Map<String, JSONObject> maps = new HashMap<>();
            //发送通知
            for (Doctor doctor : doctors) {
                //判断医生是不是在工作时间内
                String noticeContent1 = " 您当前有[zxsize]条未处理消息，其中[qysize]条为签约消息。请尽快处理~";
                String noticeContent2 = " 您当前有[zxsize]条未处理消息，请尽快处理~";
                String noticeContent3 = " 您当前有[qysize]条签约消息待处理，请尽快处理~";
                String workTime = "";
                try {
                    workTime = doctorWorkTimeService.isDoctorWorking(doctor.getCode(), -1).getString("status");
                } catch (Exception e) {

                }
                if ("1".equals(workTime)) {
                    //得到医生多少条咨询消息
                    Integer zxsize = getDoctorMesssageCount(doctor.getCode(), 1);
                    //得到医生多少条签约消息
                    Integer qysize = getDoctorMesssageCount(doctor.getCode(), 2);
                    //如果既有签约又有咨询
                    if (zxsize > 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent1 = noticeContent1.replace("[zxsize]", zxsize + "");
                        noticeContent1 = noticeContent1.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent1);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize > 0 && qysize == 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent2 = noticeContent2.replace("[zxsize]", zxsize + "");
                        jo.put("content", noticeContent2);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize == 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent3 = noticeContent3.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent3);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                }
            }
            JSONArray jsonArray = new JSONArray();
            //发送通知
            for (Map.Entry<String, JSONObject> entry : maps.entrySet()) {
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", entry.getKey());
                json.put("type", getType(entry.getValue().getInt("level")));
                json.put("title", noticeTitle);
                json.put("msg", entry.getValue().getString("content"));
                json.put("data", "");
                jsonArray.add(json);
            }
            // 推送消息给医生
            PushMsgTask.url = url + "/api/v1/chats/sm";
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知成功");
            quartzJobLog.setJobType("1");
            dbStorage.save(quartzJobLog);
        } catch (Exception e) {
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知失败");
            quartzJobLog.setJobType("0");
            dbStorage.save(quartzJobLog);
            e.printStackTrace();
        }

    }

    private String getType(Integer level) {
        switch (level) {
            case 1: {
                //专科
                return noticeKey1;
            }
            case 2: {
                //全科
                return noticeKey2;
            }
            case 3: {
                //健康管理师
                return noticeKey3;
            }
        }
        return "";
    }


    /**
     * 得到医生的未读数目
     *
     * @param doctorCode 医生code
     * @param type       1是咨询 2个签约 3是体征
     * @return
     */
    private Integer getDoctorMesssageCount(String doctorCode, int type) throws Exception {
        switch (type) {
            case 1: {
                return getImMsgAmount(doctorCode);
            }
            case 2: {
                String sql = "select count(a.id) from wlyy_message a where a.type =1 and a.has_read=1 and a.receiver=?";
                return jdbcTemplate.queryForObject(sql, Integer.class, doctorCode);
            }
        }
        return 0;
    }

    private int findDoctorAllMessage(String doctor) {
        // 签约未读消息总数
        int sign = messageDao.amountUnreadByReceiver(doctor);
        // 体征指标未读消息总数
        int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
        //系统消息
        int systemMessage = messageDao.amountUnreadSystemByReceiver(doctor);
        Integer doctorCount = 0;
        Integer patientCount = 0;
        JSONObject json = new JSONObject();
        getImMsgAmount(json, doctor);
        if (json.containsKey("imMsgCount")) {
            JSONObject jsonC = json.getJSONObject("imMsgCount");
            if (jsonC.containsKey("doctor")) {
                doctorCount = jsonC.getInt("doctor");
            }
            if (jsonC.containsKey("patient")) {
                patientCount = jsonC.getInt("patient");
            }
        }

        return sign + healthIndex + systemMessage + doctorCount + patientCount;
    }

    private void getImMsgAmount(JSONObject obj, String doctor) {
        String urlall = url + "/api/v1/chats/msg/amount?user_id=" + doctor;
        String response = HttpClientUtil.get(urlall, "UTF-8");
        obj.put("imMsgCount", response);
    }

    private Integer getImMsgAmount(String doctor) throws Exception {
        /**
         * {"msg":"获取消息总数成功！","data":{"imMsgCount":"{\"doctor\":0,\"patient\":0}","healthIndex":{"amount":0},"sign":{"amount":0}},"status":200}
         */
        return findDoctorAllMessage(doctor);
    }
}
