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

import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.transaction.Transactional;

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.SystemConf;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.yihu.wlyy.entity.discussion.WlyyTalkGroup;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroupMember;
import com.yihu.wlyy.repository.discussion.DiscussionGroupDao;
import com.yihu.wlyy.repository.discussion.DiscussionGroupMemberDao;
import com.yihu.wlyy.service.BaseService;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class TalkGroupService extends BaseService {

    // 讨论组DAO
    @Autowired
    DiscussionGroupDao discussionGroupDao;
    @Autowired
    // 讨论组成员DAO
            DiscussionGroupMemberDao discussionGroupMemberDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    DoctorDao doctorDao;

    /**
     * 讨论组保存
     *
     * @param talkGroup
     * @return
     */
    public void saveTalkGroup(WlyyTalkGroup talkGroup, List<WlyyTalkGroupMember> members) {
        discussionGroupDao.save(talkGroup);
        discussionGroupMemberDao.save(members);
    }

    /**
     * 保存成员
     *
     * @param members
     */
    public void saveMembers(List<WlyyTalkGroupMember> members) {
        discussionGroupMemberDao.save(members);
    }

    /**
     * 讨论组成员添加
     *
     * @param member
     */
    public void saveTalkMember(WlyyTalkGroupMember member) {
        discussionGroupMemberDao.save(member);
    }

    /**
     * 移除讨论组成员
     *
     * @param groupCode  讨论组标识
     * @param memberCode 成员标识
     */
    public void deleteTalkMember(String groupCode, String memberCode) {
        WlyyTalkGroupMember member = discussionGroupMemberDao.findByGroupCodeAndMemberCode(groupCode, memberCode);
        member.setStatus(2);
    }

    /**
     * 创建咨询对应的讨论组
     *
     * @param doctor
     * @param doctorName
     * @param patient
     * @param patientName
     */
    public void createConsultTalkGroup(String doctor, String doctorName, String hospitalCode, String hospitalName,
                                       String patient, String patientName, String consult) {
        //讨论组建立
        WlyyTalkGroup talkGroup = new WlyyTalkGroup();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");
        String name = patientName + "—咨询(" + dateFormat.format(new Date()) + ")";

        talkGroup.setCode(getCode());
        talkGroup.setName(name);
        talkGroup.setType(1);
        talkGroup.setCreator(patient);
        talkGroup.setCreatorName(patientName);
        talkGroup.setPatient(patient);
        talkGroup.setPatientName(patientName);
        talkGroup.setHospitalCode(hospitalCode);
        talkGroup.setHospitalName(hospitalName);
        talkGroup.setConsultCode(consult);
        talkGroup.setCzrq(new Date());

        List<WlyyTalkGroupMember> members = new ArrayList<WlyyTalkGroupMember>();
        WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();

        patientMember.setMemberCode(patient);
        patientMember.setMemberName(patientName);
        patientMember.setGroupCode(talkGroup.getCode());
        patientMember.setGroupName(name);
        patientMember.setType(4);
        patientMember.setStatus(1);
        patientMember.setCzrq(new Date());

        members.add(patientMember);

        //当前医生加入讨论组
        WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();

        doctorMember.setMemberCode(doctor);
        doctorMember.setMemberName(doctorName);
        doctorMember.setGroupCode(talkGroup.getCode());
        doctorMember.setGroupName(name);
        doctorMember.setType(3);
        doctorMember.setStatus(1);
        doctorMember.setCzrq(new Date());
        members.add(doctorMember);

        saveTalkGroup(talkGroup, members);
    }


    /**
     * 获取医生讨论组列表
     *
     * @param doctor
     * @return
     */
    public List<WlyyTalkGroup> findDoctorTalkGroups(String doctor) {
        return discussionGroupDao.findDoctorTalkGroups(doctor);
    }

    /**
     * 根据医生姓名搜索讨论组
     *
     * @param doctorName
     * @return
     */
    public List<WlyyTalkGroup> searchTalkGroupsByDoctorName(String doctor, String doctorName) {
        String doctorNameCon = "%" + doctorName + "%";
        List<String> argStrings = new ArrayList<String>();
        List<WlyyTalkGroup> groups = discussionGroupDao.findDoctorTalkGroups(doctor);
        //查询参数
        argStrings.add(doctorNameCon);
        argStrings.add(doctor);
        //查询语句
        String sb = "select DISTINCT tg.* from wlyy_talk_group tg,wlyy_talk_group_member tgm " +
                " where tg.code = tgm.group_code and tgm.member_name like ? and tg.code in ( select group_code from " +
                " wlyy_talk_group_member where member_code = ?)";
        List<WlyyTalkGroup> result = jdbcTemplate.query(sb, argStrings.toArray(), new RowMapper<WlyyTalkGroup>() {
            @Override
            public WlyyTalkGroup mapRow(ResultSet rs, int rowNum) throws SQLException {
                WlyyTalkGroup group = new WlyyTalkGroup();

                group.setId(rs.getLong("id"));
                group.setCode(rs.getString("code"));
                group.setName(rs.getString("name"));
                group.setType(rs.getInt("type"));
                group.setPatient(rs.getString("patient"));
                group.setPatientName(rs.getString("patient_name"));
                group.setConsultCode(rs.getString("consult_code"));
                group.setHospitalCode(rs.getString("hospital_code"));
                group.setHospitalName(rs.getString("hospital_name"));
                group.setCreator(rs.getString("creator"));
                group.setCreatorName(rs.getString("creator_name"));
                group.setCzrq(rs.getDate("czrq"));

                return group;
            }
        });

        if (result == null) {
            return new ArrayList<WlyyTalkGroup>();
        } else {
            return result;
        }
    }

    /**
     * 查询讨论组签约量
     *
     * @param groups
     * @return
     */
    public List<Map<String, Object>> getTalkGroupsSing(String[] groups) {
        String params = "";
        List<String> paramList = new ArrayList<>();

        for (int i = 0; i < groups.length; i++) {
            params += (i == 0 ? "?" : ",?");
        }
        paramList.addAll(Arrays.asList(groups));
        paramList.addAll(Arrays.asList(groups));

        String sqlgp = "select group_code,member_code from wlyy_talk_group_member where group_code in (" + params + ") and type = 2";
        String sqlgpm = "select member_code from wlyy_talk_group_member where group_code in (" + params + ") and type = 2";
        String sqlQu = "select * from wlyy_quota_result where qkdoctor_code in (" + sqlgpm + ") and quato_code = '1' and level1_type = '1'";
        String sqlQuSum = "select a.group_code,sum(ifnull(b.result,0)) sign from (" + sqlgp + ") a left join (" + sqlQu + ") b on a.member_code = b.qkdoctor_code group by a.group_code ";

        return jdbcTemplate.queryForList(sqlQuSum, paramList.toArray());
    }

    /**
     * 查询对应讨论组成员列表
     *
     * @param groupCode
     * @return
     */
    public List<WlyyTalkGroupMember> findTalkGroupMembers(String groupCode) {
        return discussionGroupMemberDao.findByGroupCode(groupCode);
    }

    /**
     * 查找讨论组
     *
     * @param groupCode
     * @return
     */
    public WlyyTalkGroup findTalkGroup(String groupCode) {
        return discussionGroupDao.findByCode(groupCode);
    }

    /**
     * 查询咨询对应讨论组
     *
     * @param consult
     * @return
     * @throws Exception
     */
    public JSONObject findConsultTalkGroup(String consult) throws Exception {
        WlyyTalkGroup talkGroup = discussionGroupDao.findByConsultCode(consult);

        if (talkGroup != null) {
            JSONObject result = new JSONObject(talkGroup);
            List<WlyyTalkGroupMember> members = discussionGroupMemberDao.findByGroupCode(talkGroup.getCode());

            if (members != null) {
                result.put("members", members);
            } else {
                result.put("members", "");
            }

            return result;
        } else {
            throw new Exception("没有对应咨询讨论组");
        }
    }

    /**
     * 获取医生对应病人的讨论组纪录
     *
     * @param doctor
     * @param patient
     * @return
     */
    public JSONArray getTalkGroupHistories(String doctor, String patient) {
        List<WlyyTalkGroup> groups = discussionGroupDao.findByDoctorAndPatient(doctor, patient);

        return new JSONArray(groups);
    }

    /**
     * 获取两个成员同在的讨论组
     *
     * @param memberFirst
     * @param memberSencond
     * @return
     */
    public List<WlyyTalkGroup> getTalkGroupRelated(String memberFirst, String memberSencond) {
        List<WlyyTalkGroup> result = new ArrayList<>();
        //查询语句
        String sqlIn = " select tg.* from wlyy_talk_group tg where tg.code in ("
                + " select tgm.group_code "
                + " from "
                + "     (select * from wlyy_talk_group_member where member_code = ?) tgm "
                + "  inner join "
                + "     (select * from wlyy_talk_group_member where member_code = ?) tgmm "
                + "  on tgm.group_code = tgmm.group_code )";
        //查询
        result = jdbcTemplate.query(sqlIn, new Object[]{memberFirst, memberSencond}, new RowMapper<WlyyTalkGroup>() {
            @Override
            public WlyyTalkGroup mapRow(ResultSet rs, int rowNum) throws SQLException {
                WlyyTalkGroup group = new WlyyTalkGroup();

                group.setId(rs.getLong("id"));
                group.setCode(rs.getString("code"));
                group.setName(rs.getString("name"));
                group.setType(rs.getInt("type"));
                group.setPatient(rs.getString("patient"));
                group.setPatientName(rs.getString("patient_name"));
                group.setConsultCode(rs.getString("consult_code"));
                group.setHospitalCode(rs.getString("hospital_code"));
                group.setHospitalName(rs.getString("hospital_name"));
                group.setCreator(rs.getString("creator"));
                group.setCreatorName(rs.getString("creator_name"));
                group.setCzrq(rs.getDate("czrq"));

                return group;
            }
        });
        return result;
    }

    /**
     * 获取医生的讨论组统计个数
     *
     * @param doctor
     * @return
     */
    public long getDoctorTalkGroupCount(String doctor) {
        return discussionGroupMemberDao.countByMemberCode(doctor);
    }


    /**
     * 获取以上一对一聊天
     *
     * @param doctor
     * @param doctorName
     * @return
     */
    public JSONArray getOneToOneIm(String doctor,String doctorName) throws UnsupportedEncodingException {
        JSONArray result = null;
        JSONArray resultArray = new JSONArray();
        String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                + "statistic/getchatlist.im";
        String json = HttpUtil.sendGet(url, "uid=" + doctor);
        if(!StringUtils.isEmpty(json)) {
            result = new JSONArray(json);
        }

        if (result != null && result.length() > 0) {
            for (int i = 0; i < result.length(); i++) {
                JSONObject obj = result.getJSONObject(i);
                if (obj.getInt("msg_type") == 1 && obj.get("peer_uid") != null) {
                    JSONObject objRe = new JSONObject();
                    Doctor fromDoctor = doctorDao.findByCode(obj.get("peer_uid").toString());

                    if(fromDoctor == null){
                        continue;
                    }

                    if(!StringUtils.isEmpty(doctorName)){
                        if(!fromDoctor.getName().contains(doctorName)){
                            continue;
                        }
                    }

                    objRe.put("uid",obj.get("uid") != null ? obj.getString("uid") :"");
                    objRe.put("fromUid",obj.get("peer_uid") != null ? obj.get("peer_uid").toString() : "");
                    objRe.put("fromName",fromDoctor.getName());
                    objRe.put("fromLevel",fromDoctor.getLevel());
                    objRe.put("photo",StringUtils.isEmpty(fromDoctor.getPhoto())?"":fromDoctor.getPhoto());
                    objRe.put("sex",fromDoctor.getSex());
                    objRe.put("lastContentType",obj.getInt("last_content_type"));
                    objRe.put("lastContent",obj.get("last_content") != null?new String(obj.getString("last_content").getBytes(),"utf-8"):"");
                    objRe.put("newMsgCount",obj.getInt("new_msg_count"));
                    objRe.put("lastMsgTime",obj.get("timestamp") != null ? DateUtil.dateToStr(new Date(obj.getLong("timestamp")),DateUtil.YYYY_MM_DD_HH_MM):"");

                    resultArray.put(objRe);
                }
            }
        }

        return resultArray;
    }

}

