package com.yihu.wlyy.web.common.im;


import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.util.ImUtill;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.web.BaseController;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "im_new", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "IM-即时消息")
public class imController extends BaseController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private ConsultDao consultDao;

    /**
     * 获取单个咨询
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "/getTopic")
    @ResponseBody
    public String getTopic(String consult) {
        try {
            return success(ImUtill.getTopic(consult).get("data").toString());
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }

    /**
     * 获取当前团队的咨询列表
     * status = 10 已结束的咨询，status=0,reply = 1 已回复 ，status=0,reply=0未回复
     * 第一次列表为当前医生（很可能团队长）待回复列表 传参：doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamList", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam int adminTeamCode,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = ImUtill.getTeamConsultByStatus(doctor,adminTeamCode, status, reply, page, pagesize);
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }

                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型：1三师咨询，2家庭医生咨询，3图文咨询，4公共咨询，5病友圈
                map.put("type", con.getType());

                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 获取列表
     * status = 10 已结束的咨询，status=0,reply = 1 已回复 ，status=0,reply=0未回复
     * 第一次列表为当前医生（很可能团队长）待回复列表 传参：doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getList", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = ImUtill.getConsultByStatus(doctor, status, reply, page, pagesize);
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }

                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型：1三师咨询，2家庭医生咨询，3图文咨询，4公共咨询，5病友圈
                map.put("type", con.getType());

                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 获取团队统计数据
     * status = 10 已结束的咨询，status=0,reply = 1 已回复 ，status=0,reply=0未回复
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamData", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamData(@RequestParam int adminTeamCode) {
        try {
            String uid = getUID();
            List<Map<String, Object>> doctors = getMemberByDoctor(uid);
            JSONObject json = new JSONObject();
            List list = new ArrayList();
            int countUnReply = 0;
            int countReply = 0;
            int countConsult = 0;

//        团队下的医生统计数量
            for (Map<String, Object> doc : doctors) {
                Map map = new HashMap();
                String doctor = doc.get("code").toString();
                map.put("photo", doc.get("photo") == null ? "" : doc.get("photo").toString());
                map.put("name", doc.get("name").toString());
                map.put("sex", doc.get("sex").toString());
                map.put("doctor", doctor);
                map.put("type", doc.get("level") == null ? "" : doc.get("level").toString());
//                未回复
                String totalUnReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 0);
                int unReply = Integer.parseInt(totalUnReply);
                map.put("totalUnReply", unReply);
//                已回复
                String totalReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 1);
                String totalReply1 = ImUtill.getConsultData(doctor,adminTeamCode, 10, null);
                int reply = Integer.parseInt(totalReply) + Integer.parseInt(totalReply1);
                map.put("totalReply", reply);
//                总咨询量
                String totalConsult = ImUtill.getConsultData(doctor, adminTeamCode,null, null);
                int consult = Integer.parseInt(totalConsult);
                map.put("totalConsult", consult);

                countUnReply += unReply;
                countReply += reply;
                countConsult += consult;
                list.add(map);
            }
            json.put("totalUnReply", countUnReply);
            json.put("totalReply", countReply);
            json.put("totalConsult", countConsult);
            json.put("doctors", list);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 获取团队医生下居民的咨询
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/getConsultByPatient", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByPatient(@RequestParam String patient) {
        try {
//            1.调im接口
//            2.判断团队长和当前咨询居民是否存在签约关系
            String doctor = getUID();
            int count = signFamilyDao.findByPatientAndDoctor(patient, doctor);
            boolean flag = (count == 0) ? false : true;
            return write(200, "查询成功", "data", flag);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }


    /**
     * 提醒医生相关信息
     *
     * @param doctor  提醒的医生
     * @param content 提醒的内容
     * @return
     */
    @RequestMapping(value = "/message/remain", method = RequestMethod.POST)
    @ResponseBody
    public String reaminDoctor(String doctor, String content) {
        try {
            JSONObject participants = new JSONObject();
            participants.put(doctor, 0);
            participants.put(getUID(), 0);
            Doctor d = doctorDao.findByCode(getUID());
            //创建医生会话讨论组
            JSONObject sessionObj = ImUtill.createSession(participants, ImUtill.SESSION_TYPE_P2P, d.getName() + "发来消息提醒", "");
            if (sessionObj.getInt("status") == -1) {
                throw new RuntimeException(sessionObj.getString("message"));
            }
            JSONObject session = sessionObj.getJSONObject("data");
            ImUtill.sendImMsg(getUID(), d.getName(), session.getString("id"), "1", content, "REMAIN");
            return success("提醒成功！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }


    public List getMemberByDoctor(String doctor) {
        String sql = "SELECT d.photo,d.`name`,d.sex,d.`code`,d.level " +
                " from wlyy_admin_team t,wlyy_admin_team_member m,wlyy_doctor d " +
                " where t.id = m.team_id and m.doctor_code = d.`code` and t.available = 1 and m.available=1 " +
                " and t.leader_code = ? ";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql, doctor);
        return doctors;
    }


}
