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.print.Doc;
import javax.transaction.Transactional;

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeamMember;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.IdCardUtil;
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.BeanPropertyRowMapper;
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 {

    @Autowired
    DiscussionGroupDao discussionGroupDao;
    @Autowired
    DiscussionGroupMemberDao discussionGroupMemberDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    DoctorDao doctorDao;
    @Autowired
    AdminTeamService teamService;
    @Autowired
    PatientDao patientDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;

    /**
     * 讨论组保存
     *
     * @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 group
     * @param member
     * @return
     */
    public boolean isMemberExists(String group, String member) {
        WlyyTalkGroupMember m = discussionGroupMemberDao.findByGroupCodeAndMemberCode(group, member);

        if (m != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 移除讨论组成员
     *
     * @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 JSONObject 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()) + ")";
        String groupCode = getCode();
        talkGroup.setCode(groupCode);
        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);

        JSONObject result = new JSONObject(talkGroup);
        result.put("members", result);
        result.put("groupCode", groupCode);
        return result;
    }

    /**
     * 查询咨询对应的求助
     *
     * @param consult
     * @return
     */
    public JSONObject getConsultGroup(String consult) {
        JSONObject json = new JSONObject();
        List<WlyyTalkGroup> groups = discussionGroupDao.findByConsultCodeAndType(consult, 2);

        if (groups != null && groups.size() > 0) {
            json = new JSONObject(groups.get(0));
            List<WlyyTalkGroupMember> members = discussionGroupMemberDao.findByGroupCode(groups.get(0).getCode());
            if (members != null) {
                JSONArray mArray = new JSONArray();
                for (WlyyTalkGroupMember member : members) {
                    mArray.put(new JSONObject(member));
                }
                json.put("members", mArray);
            } else {
                json.put("members", new JSONArray());
            }

            return json;
        } else {
            return null;
        }
    }

    /**
     * 查询咨询对应的求助讨论组
     *
     * @param doctor
     * @return
     */
    public JSONArray getCommonDoctors(String doctor) {
        JSONArray result = new JSONArray();
        String sql = "select DISTINCT d.* from wlyy_consult_team p LEFT JOIN wlyy_doctor d on p.doctor = d.code where p.patient =?  order by p.czrq DESC ";
        List<Doctor> doctors = jdbcTemplate.query(sql, new Object[]{doctor},
                new BeanPropertyRowMapper(Doctor.class));
        for (Doctor doc : doctors) {
            JSONObject json = new JSONObject(doc);

            if (json.has("password")) {
                json.remove("password");
            }
            if (json.has("salt")) {
                json.remove("salt");
            }
            result.put(json);
        }

        return result;
    }

    /**
     * 获取医生讨论组列表
     *
     * @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 {
        List<WlyyTalkGroup> talkGroup = discussionGroupDao.findByConsultCodeAndType(consult, 1);

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

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

            return result;
        } else {
            return null;
        }
    }

    /**
     * 查询咨询对应讨论组
     *
     * @param consult
     * @return
     * @throws Exception
     */
    public List<WlyyTalkGroup> findAllConsultTalkGroup(String consult) throws Exception {
        List<WlyyTalkGroup> talkGroup = discussionGroupDao.findByConsult(consult);

        return talkGroup;
    }

    public WlyyTalkGroup findConsultTalkGroupByType(String consult, int type) throws Exception {
        WlyyTalkGroup talkGroup = discussionGroupDao.findByConsultAndType(consult, type);

        return talkGroup;
    }

    /**
     * 获取医生对应病人的讨论组纪录
     *
     * @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);
    }

    public ConsultTeam findConsultByGroup(String groupCode) {
        WlyyTalkGroup w = discussionGroupDao.findByCode(groupCode);
        return consultTeamDao.findByConsult(w.getConsultCode());
    }

    public WlyyTalkGroupMember findCreateAndDoctor(String create, String doctorCode) {
        return discussionGroupDao.findCreateAndDoctor(create, doctorCode);
    }
}

