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


import com.yihu.wlyy.entity.doctor.profile.Doctor;
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.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;

    /**
     * 获取列表
     * 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 getTeamData(
            @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);
//            Doctor dct = doctorDao.findByCode(doctor);
            /*String photo = dct.getPhoto();
            String dctName = dct.getName();*/
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                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();
                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("sex", sex);
                map.put("create_time", createTime);
                map.put("description", description);

                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() {
        try {
            String uid = getUID();
//           String uid = "6c0cfe5065e011e69f7c005056850d66";
            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").toString());
                map.put("name", doc.get("name").toString());
                map.put("sex", doc.get("sex").toString());
                map.put("doctor", doctor);
//                map.put("code", "ec6714314d6d48a6bfcf1e9119187e02");
                String totalUnReply = ImUtill.getConsultData(doctor, 0, 0);
                int unReply = Integer.parseInt(totalUnReply);
                map.put("totalUnReply", unReply);
                String totalReply = ImUtill.getConsultData(doctor, 0, 1);
                int reply = Integer.parseInt(totalReply);
                map.put("totalReply", reply);
                String totalConsult = ImUtill.getConsultData(doctor, 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 code
     * @param type 0待回复 1进行中 2已完成
     * @return
     *//*
    @RequestMapping(value = "/getTeamDoctor", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamDoctor(@RequestParam String code,
                                @RequestParam int type,
                                @RequestParam int pageNo,
                                @RequestParam int pageSize) {
        try {
//			List list = consultTeamService.getTeamDoctor(code, type);
//			return write(200, "查询成功", "data", list);
            return write(200, "查询成功");
        } 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();
//			Boolean flag = consultTeamService.getConsultByPatient(patient,doctor);
            int count = signFamilyDao.findByPatientAndDoctor(patient, doctor);
            boolean flag = (count == 0) ? false : true;
            return write(200, "查询成功", "data", flag);
//            return write(200, "查询成功");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    public List getMemberByDoctor(String doctor) {
//        List<Doctor> doctors = doctorDao.findMemberByLeader(doctor);
        String sql = "SELECT d.photo,d.`name`,d.sex,d.`code` " +
                " 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;
    }


}
