package com.yihu.wlyy.web.doctor.message;

import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.message.Message;
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.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
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.ResponseBody;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/doctor/message", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-消息")
public class DoctorMessageController extends BaseController {

    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "messages")
    @ResponseBody
    @ApiOperation("查询医生未读消息和最后消息")
    public String messages() {
        try {
            JSONObject json = messageService.findDoctorAllMessage(getUID());
            return write(200, "获取消息总数成功！", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }


    /**
     * 医生消息总数统计接口
     *
     * @return
     */
    @RequestMapping(value = "amount")
    @ResponseBody
    public String amount() {
        try {
            JSONObject json = messageService.findDoctorAllMessageAmount(getUID());
            if (json == null) {
                return error(-1, "获取消息总数失败！");
            } else {
                return write(200, "获取消息总数成功！", "data", json);
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "获取消息总数失败！");
        }
    }

    /**
     * 健康咨询消息列表查询接口
     *
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    @RequestMapping(value = "consults")
    @ResponseBody
    public String consultList(long id, int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<ConsultTeam> list = messageService.findConsultListByDoctor(getUID(), id, pagesize);
            for (ConsultTeam consult : list) {
                if (consult == null) {
                    continue;
                }
                JSONObject json = new JSONObject();
                json.put("id", consult.getId());
                // 设置咨询标识
                json.put("consult", consult.getConsult());
                // 设置患者标识
                json.put("patient", consult.getPatient());
                // 设置患者头像
                json.put("photo", consult.getPhoto());
                // 设置主要症状
                json.put("symptoms", consult.getSymptoms());
                // 设置患者姓名
                json.put("name", consult.getName());
                // 设置状态（0进行中，1已完成，-1患者取消）
                json.put("status", consult.getStatus());
                // 设置消息未读数量
                json.put("unread", consult.getDoctorRead());
                // 设置咨询时间
                json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                array.put(json);
            }
            return write(200, "获取健康咨询列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取健康咨询列表失败！");
        }
    }

    /**
     * 更新体征消息为已读
     *
     * @param msgid
     * @return
     */
    @RequestMapping(value = "read_health")
    @ResponseBody
    @ApiOperation("消息设置成已读")
    @ObserverRequired
    public String readHealth(long msgid) {
        try {
            messageService.readHealth(msgid);
            return success("操作成功！");
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败！");
        }
    }

    /**
     * 根据参数查询发送给我的消息
     *
     * @return
     */
    @RequestMapping(value = "find")
    @ResponseBody
    @ApiOperation("查询发送给我的消息")
    public String findMyMessage(String sender, String signStatus) {
        try {
            Message msg = messageService.findUnreadSign(sender, getUID(), signStatus);
            JSONObject json = null;
            if (msg != null) {
                json = new JSONObject();
                json.put("id", msg.getId());
                json.put("sender", msg.getSender());
                json.put("senderName", msg.getSenderName());
                json.put("type", msg.getType());
                json.put("read", msg.getRead()); // 是否已读：1未读，0已读
                json.put("signStatus", msg.getSignStatus());
                json.put("status", msg.getOver());
                json.put("reason", msg.getReason());
            }
            return write(200, "获取消息成功！", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取消息失败！");
        }
    }


    /**
     * 系统消息（分配健管师 + 随访计划消息 ）
     */
    @RequestMapping(value = "getSystemMessage", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取系统消息")
    public String getSystemMessage(@ApiParam(value = "第几页", defaultValue = "1")
                                   @RequestParam Integer page,
                                   @ApiParam(value = "每页几行", defaultValue = "10")
                                   @RequestParam Integer pagesize) {
        try {
            List<Message> list = messageService.getSystemMessage(getUID(), page, pagesize);
            return write(200, "获取消息成功！", "list", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取消息失败！");
        }
    }

    @RequestMapping(value = "getHealthIndexMessage", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取超标指标消息--根据患者分组")
    public String getHealthIndexMessage() throws Exception {
        try {
            List<Map<String, Object>> list = messageService.getHealthIndexMessage(getUID());     //"D20161008003"

            return write(200, "获取超标指标消息成功", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

    @RequestMapping(value = "getHealthIndexMessageByPatient", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取患者超标指标消息")
    public String getHealthIndexMessageByPatient(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20161008001")
                                                 @RequestParam(value = "patient", required = true) String patient,
                                                 @ApiParam(name = "type", value = "健康指标类型1血糖，2血压，3体重", defaultValue = "1")
                                                 @RequestParam(value = "type", required = true) String type,
                                                 @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                                 @RequestParam(value = "page", required = true) Integer page,
                                                 @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                                 @RequestParam(value = "pagesize", required = true) Integer pagesize) throws Exception {
        try {
            List<Map<String, String>> list = messageService.getHealthIndexMessageByPatient(getUID(), patient, type, page, pagesize);

            return write(200, "获取超标指标消息成功", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, "查询失败");
        }
    }


    /**
     * @param type 消息类型  1.是家庭签约信息  2.体征消息  3分配健管师
     */
    @RequestMapping(value = "findMessageNum")
    @ResponseBody
    @ApiOperation("获取未读消息数(1.2.8版本作废)")
    public String findMessageNum(@ApiParam(value = "消息类型", defaultValue = "3")
                                 @RequestParam Integer type) {
        try {

            JSONObject obj = messageService.findMessageNum(getUID(), type);

            return write(200, "获取消息成功！", "list", obj);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取消息失败！");
        }
    }

    /**
     * 体征指标消息查询接口
     *
     * @param isRead 1未读，0已读
     */
    @RequestMapping(value = "health")
    @ResponseBody
    @ApiOperation("体征指标消息查询接口(1.2.8版本作废)")
    public String health(long id, int pagesize, @RequestParam(required = false) String isRead) {
        try {
            JSONArray array = new JSONArray();
            Page<Message> list = messageService.findHealthListByDoctor(getUID(), id, pagesize, isRead);
            for (Message msg : list) {
                if (msg == null) {
                    continue;
                }
                JSONObject json = new JSONObject();
                // 消息ID
                json.put("id", msg.getId());
                // 发送人标识
                json.put("sender", msg.getSender());
                // 发送人姓名
                json.put("senderName", msg.getSenderName());
                // 发送人头像
                json.put("senderPhoto", msg.getSenderPhoto());
                // 消息类型：1血糖，2血压
                json.put("type", msg.getTzType());
                // 是否已读：1未读，0已读
                json.put("read", msg.getRead());
                // 是否已读：
                json.put("sex", msg.getSex());
                // 当前值/收缩压，正数为高，负数为低
                json.put("value1", msg.getValue1());
                // 上次值/舒张压，正数为高，负数为低
                json.put("value2", msg.getValue2());
                // 发送时间
                json.put("czrq", DateUtil.dateToStrLong(msg.getCzrq()));
                array.put(json);
            }
            return write(200, "获取体征消息成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取体征消息失败！");
        }
    }

    /**
     * @param type 消息类型  1.是家庭签约信息  2.体征消息  3系统消息（分配健管师 + 随访计划消息 ）
     */
    @RequestMapping(value = "findMessage")
    @ResponseBody
    @ApiOperation("获取某类消息(1.2.8版本作废)")
    public String findMessage(String type,
                              long id,
                              int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Message> list = messageService.find(getUID(), type, id, pagesize);
            for (Message msg : list) {
                if (msg == null) {
                    continue;
                }
                JSONObject json = new JSONObject();
                // 消息ID
                json.put("id", msg.getId());
                // 发送人标识
                json.put("sender", msg.getSender());
                // 消息內容
                json.put("content", msg.getContent());
                // 发送人姓名
                json.put("senderName", msg.getSenderName());
                // 发送人头像
                json.put("senderPhoto", msg.getSenderPhoto());
                // 是否已读：1已读，0未读
                json.put("read", msg.getRead());
                // 是否已读：
                json.put("sex", msg.getSex());
                // 发送时间
                json.put("czrq", DateUtil.dateToStrNoSecond(msg.getCzrq()));
                array.put(json);
            }
            return write(200, "获取消息成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取消息失败！");
        }
    }


    /**
     * 设置某类消息已读
     *
     * @param type 消息类型
     * @return
     */
    @RequestMapping(value = "setMessageReaded")
    @ResponseBody
    @ApiOperation("设置某类消息已读")
    @ObserverRequired
    public String setMessageReaded(@RequestParam @ApiParam(value = "消息类型") Integer type) {
        try {
            messageService.setMessageReaded(getUID(), type);
            return write(200, "设置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "设置失败");
        }
    }
}
