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

import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
import com.yihu.wlyy.entity.patient.PatientFamilyTemp;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import com.yihu.wlyy.entity.security.AccessToken;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.repository.patient.PatientFamilyTempDao;
import com.yihu.wlyy.repository.patient.PatientInvitationLogDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 家庭成员服务
 * <p>
 * Created by lyr on 2016/10/17.
 */
@Service
public class FamilyMemberService extends BaseService {
    @Autowired
    PatientFamilyMemberDao memberDao;
    @Autowired
    PatientDao patientDao;
    @Autowired
    SMSService smsService;
    @Autowired
    private PatientInvitationLogDao patientInviteLogDao;
    @Autowired
    FamilyContractService contractService;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private PatientFamilyTempDao patientFamilyTempDao;

    @Autowired
    JdbcTemplate jdbcTemplate;

    Map<Integer, String> relations = new HashMap<>();

    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
    }

    /**
     * 添加家庭成员
     *
     * @param patient 患者
     * @param member  成员
     * @param captcha 验证码
     * @param member  成员
     * @return
     */
    public int addMember(String patient, String member, String captcha, String password, int relation) throws Exception {
        if (patient.equals(member)) {
            return 0;
        }

        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);

        if (p == null) {
            return -1;
        }
        // 添加的成员是否注册判断
        if (m == null) {
            return -2;
        }

        if (relation>0&&relation < 5) {//家庭关系为父亲、母亲、老公、老婆时只能有一个
            List<PatientFamilyMember> familyMembers = memberDao.findByPatientAndFamilyRelation(patient, relation);

            if (familyMembers != null && familyMembers.size() > 0) {
                return -5;
            }
        }

        // 验证码验证
        if (StringUtils.isNotEmpty(captcha)) {
            int checkStatus = smsService.check(m.getMobile(), 10, captcha);
            if (checkStatus == -2) {
                return -6;  // 验证码过期
            } else if (checkStatus == -1) {
                return -3; // 验证码错误
            }
        }
        if (StringUtils.isNotEmpty(password)) {
            String loginPassword = MD5.GetMD5Code(password + m.getSalt());
            if (!loginPassword.equals(m.getPassword())) {
                return -3;
            }
        }
        // 添加自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        // 家庭关系已存在时，不重复添加
        if (fm != null) {
            return -4;
        } else {
            fm = new PatientFamilyMember();
            fm.setPatient(patient);
            fm.setFamilyMember(member);
        }
        fm.setFamilyRelation(relation);
        fm.setIsAuthorize(1);//默认授权
        fm.setCzrq(new Date());

        // 添加对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);
        // 不存在则创建
        if (fmt == null) {
            fmt = new PatientFamilyMember();
            fmt.setPatient(member);
            fmt.setFamilyMember(patient);
        }

        // 对方与自己的关系转换
        int relationTrans = familyRelationTrans(p, relation);
        fmt.setFamilyRelation(relationTrans);
        fmt.setCzrq(new Date());
        fmt.setIsAuthorize(1);//默认授权

        memberDao.save(fm);
        memberDao.save(fmt);

        //设置家人openid
        if(StringUtils.isBlank(m.getOpenid())){
            m.setOpenid(p.getOpenid());
            patientDao.save(m);
        }

        return 1;
    }

    public int addMember(Patient p, String member, int type) throws Exception {
        if (p.getCode().equals(member)) {
            return 0;
        }
        // 添加自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(p.getCode(), member);
        // 家庭关系已存在时，不重复添加
        if (fm != null) {
            return -4;
        } else {
            fm = new PatientFamilyMember();
            fm.setPatient(p.getCode());
            fm.setFamilyMember(member);
        }
        fm.setFamilyRelation(type);
        fm.setCzrq(new Date());

        // 添加对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, p.getCode());
        // 不存在则创建
        if (fmt == null) {
            fmt = new PatientFamilyMember();
            fmt.setPatient(member);
            fmt.setFamilyMember(p.getCode());
        }

        // 对方与自己的关系转换
        int relationTrans = familyRelationTrans(p, type);
        fmt.setFamilyRelation(relationTrans);
        fmt.setCzrq(new Date());
        memberDao.save(fm);
        memberDao.save(fmt);
        return 1;
    }

    /**
     * 设置授权关系
     * @param patient
     * @param member
     * @param isAuthorize
     * @return
     * @throws Exception
     */
    public int authorizeMember(String patient, String member,Integer isAuthorize) throws Exception{
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        if(fm==null){
            return -1;
        }

        fm.setIsAuthorize(isAuthorize);
        memberDao.save(fm);
        return 1;
    }


    /**
     * 修改家庭成员关系
     *
     * @param patient  居民
     * @param member   成员
     * @param relation 关系
     * @return
     */

    public int modifyFamilyRelation(String patient, String member, int relation) throws Exception {
        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);

        if (p == null) {
            return -1;
        }
        // 成员是否注册判断
        if (m == null) {
            return -2;
        }

        // 自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        if (fm == null) {
            return -3;
        }

        if (relation>0&&relation < 5) {
            List<PatientFamilyMember> familyMembers = memberDao.findByPatientAndFamilyRelation(patient, relation);

            if (familyMembers != null && familyMembers.size() > 0) {
                return -5;
            }
        }

        fm.setFamilyRelation(relation);
        fm.setCzrq(new Date());

        // 对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);

        // 不存在则创建
        if (fmt == null) {
            fmt = new PatientFamilyMember();
            fmt.setPatient(patient);
            fmt.setFamilyMember(member);
        }

        int relationTrans = familyRelationTrans(p, relation);
        fmt.setFamilyRelation(relationTrans);
        fmt.setCzrq(new Date());

        memberDao.save(fm);
        memberDao.save(fmt);

        return 1;
    }

    /**
     * 删除家庭成员
     *
     * @param patient 居民
     * @param member  成员
     * @return
     */
    public int deleteMember(String patient, String member) {
        // 自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        if (fm == null) {
            return -1;
        }
        // 对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);

        memberDao.delete(fm);
        if (fmt != null) {
            memberDao.delete(fmt);
        }
        //删除微信模板临时表
        List<PatientFamilyTemp> patientFamilyTemps = patientFamilyTempDao.findByDealerAndPatient(member,patient);

        if(patientFamilyTemps!=null&&patientFamilyTemps.size()>0){
            for(PatientFamilyTemp temp : patientFamilyTemps){
                patientFamilyTempDao.delete(temp);
            }
        }

        return 1;
    }

    /**
     * 判断成员是否注册
     *
     * @param idcard 身份证号
     * @return
     */
    public JSONObject isRegister(String idcard, String patient) {
        JSONObject result = new JSONObject();
        Patient p = patientDao.findByIdcard(idcard);

        if (p == null) {
            result.put("isRegister", 0);
        } else {
            if (patient.equals(p.getCode())) {
                result.put("isRegister", -1); //不能添加自己
                return result;
            }
            result.put("isRegister", 1);
            result.put("mobile", StringUtils.isEmpty(p.getMobile()) ? "" : p.getMobile());
            result.put("name", StringUtils.isEmpty(p.getName()) ? "" : p.getName());
            result.put("code", StringUtils.isEmpty(p.getCode()) ? "" : p.getCode());
            result.put("photo", StringUtils.isEmpty(p.getPhoto()) ? "" : p.getPhoto());
        }

        return result;
    }

    public JSONObject getPatient(String patient){
        Patient p = patientDao.findByCode(patient);

        JSONObject obj = new JSONObject();
        List<SignFamily> signs = contractService.findAllSignByPatient(p.getCode());
        boolean ssSign = false;
        boolean jtSign = false;

        for (SignFamily sign : signs) {
            if (sign.getType() == 1 && sign.getStatus() > 0) {
                ssSign = true;
            } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                jtSign = true;
            } else if (sign.getStatus() == 0) {
            }
        }

        obj.put("code", p.getCode());
        obj.put("name", p.getName());
        obj.put("sex", p.getSex());
        obj.put("birthday", p.getBirthday());
        obj.put("isAuthorize", 1);
        String idCard = StringUtils.isEmpty(p.getIdcard()) ? "" : p.getIdcard();
        obj.put("idcard", CommonUtil.getIdcardEncode(idCard));
        obj.put("idcardAll", idCard);
        obj.put("ssc", p.getSsc());
        obj.put("photo", StringUtils.isEmpty(p.getPhoto()) ? "" : p.getPhoto());
        obj.put("mobile", StringUtils.isEmpty(p.getMobile()) ? "" : p.getMobile());
        obj.put("address", StringUtils.isEmpty(p.getAddress()) ? "" : p.getAddress());
        obj.put("familyRelation", -1);
        obj.put("familyRelationName", "自己");
        obj.put("isAuthorize", 1);//0:未授权,1:已授权

        if (ssSign && jtSign) {
            obj.put("signType", 3);
        } else if (!ssSign && jtSign) {
            obj.put("signType", 2);
        } else if (ssSign && !jtSign) {
            obj.put("signType", 1);
        } else {
            obj.put("signType", 0);
        }
        return obj;
    }

    /**
     * 撤销添加家人
     * @param id
     * @return
     */
    public int revokeAddMember(Long id){
        PatientFamilyTemp temp = patientFamilyTempDao.findOne(id);
        if("1".equals(temp.getState())){
            return 1;
        }else if("2".equals(temp.getState())){
            return 2;
        }else if("3".equals(temp.getState())){
            return 3;
        }else if("0".equals(temp.getState())){
            temp.setState("3");
            patientFamilyTempDao.save(temp);
        }
        return 200;
    }

    /**
     * 获取所有家庭成员，包括自己
     * @param patient
     * @return
     */
    public JSONArray getAllFamilyMembers(String patient){
        JSONArray resultArray = new JSONArray();
        resultArray.put(getPatient(patient));

        String sql = "select * " +
                " from " +
                "    wlyy_patient_family_member t1, " +
                "    wlyy_patient t2 " +
                " where " +
                "    t2.code in (select family_member from wlyy_patient_family_member where patient = ? ) " +
                "    and t1.patient = ? " +
                "    and t1.family_member = t2.code order by t1.family_relation ASC ";

        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{patient, patient});

        if (result != null && result.size() > 0) {
            JSONArray tem = new JSONArray();//存储其他
            for (Map<String, Object> map : result) {
                JSONObject obj = new JSONObject();
                List<SignFamily> signs = contractService.findAllSignByPatient(map.get("code").toString());
                boolean ssSign = false;
                boolean jtSign = false;
                for (SignFamily sign : signs) {
                    if (sign.getType() == 1 && sign.getStatus() > 0) {
                        ssSign = true;
                    } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                        jtSign = true;
                    } else if (sign.getStatus() == 0) {
                    }
                }
                Integer family_relation = Integer.valueOf(map.get("family_relation").toString());

                obj.put("code", map.get("code"));
                obj.put("name", map.get("name"));
                obj.put("sex", map.get("sex"));
                obj.put("isAuthorize", map.get("is_authorize"));//0:未授权,1:已授权
                obj.put("birthday", map.get("birthday"));
                obj.put("idcard", StringUtils.isEmpty(String.valueOf(map.get("idcard"))) ? "" : map.get("idcard").toString());
                obj.put("photo", map.get("photo"));
                obj.put("mobile", map.get("mobile"));
                obj.put("address", StringUtils.isEmpty(String.valueOf(map.get("address"))) ? "" : map.get("address"));
                obj.put("familyRelation", family_relation);
                obj.put("familyRelationName", relations.get(map.get("family_relation")));


                if (ssSign && jtSign) {
                    obj.put("signType", 3);
                } else if (!ssSign && jtSign) {
                    obj.put("signType", 2);
                } else if (ssSign && !jtSign) {
                    obj.put("signType", 1);
                } else {
                    obj.put("signType", 0);
                }

                if(family_relation==0){
                    tem.put(obj);
                }else {
                    resultArray.put(obj);
                }
            }

            if(tem.length()>0){
                for(int i =0;i<tem.length();i++){
                    resultArray.put(tem.get(i));
                }
            }
        }
        return resultArray;
    }

    /**
     * 获取居民的家庭成员
     *
     * @param patient 居民
     * @return
     */
    public JSONArray getPatientFamilyMembers(String patient, String doctorCode,Integer isAgree) {
        JSONArray resultArray = new JSONArray();
        String sql = "select * " +
                " from " +
                "    wlyy_patient_family_member t1, " +
                "    wlyy_patient t2 " +
                " where " +
                "    t2.code in (select family_member from wlyy_patient_family_member where patient = ? ) " +
                "    and t1.patient = ? " +
                "    and t1.family_member = t2.code ";

        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{patient, patient});

        if (result != null && result.size() > 0) {
            for (Map<String, Object> map : result) {
                JSONObject obj = new JSONObject();
                List<SignFamily> signs = contractService.findAllSignByPatient(map.get("code").toString());
                boolean ssSign = false;
                boolean jtSign = false;
                int status = 0;

                for (SignFamily sign : signs) {
                    if (sign.getType() == 1 && sign.getStatus() > 0) {
                        ssSign = true;
                        status = 3;
                    } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                        jtSign = true;
                        status = 3;
                    } else if (sign.getStatus() == 0) {
                        status = 2;
                    }
                }

                if (!StringUtils.isEmpty(doctorCode)) {
                    List<PatientInvitationLog> patientInviteLog = patientInviteLogDao.getPatientInviteLog(doctorCode,
                            patient, map.get("code").toString());
                    if (patientInviteLog != null && patientInviteLog.size() > 0 && status != 0) {
                        status = 1;
                    }
                }

                Integer isAuthorize = (Integer)map.get("is_authorize");

                obj.put("code", map.get("code"));
                obj.put("name", map.get("name"));
                obj.put("sex", map.get("sex"));
                obj.put("isAuthorize", isAuthorize);//0:未授权,1:已授权
                obj.put("birthday", map.get("birthday"));
                obj.put("idcard", StringUtils.isEmpty(String.valueOf(map.get("idcard"))) ? "" : map.get("idcard").toString());
                obj.put("photo", map.get("photo"));
                obj.put("mobile", map.get("mobile"));
                obj.put("address", StringUtils.isEmpty(String.valueOf(map.get("address"))) ? "" : map.get("address"));
                obj.put("familyRelation", map.get("family_relation"));
                obj.put("familyRelationName", relations.get(map.get("family_relation")));

                if (!StringUtils.isEmpty(doctorCode)) {
                    obj.put("relaholder", relations.get(map.get("family_relation")));
                    obj.put("addressCode", "");
                    obj.put("addressName", StringUtils.isEmpty(String.valueOf(map.get("address"))) ? "" : map.get("address"));
                    obj.put("status", status);
                    obj.put("source", 1);

                    if (isAuthorize==1){
                        PatientFamilyMember familyMember = memberDao.findByPatientAndFamilyMember(String.valueOf(map.get("family_member")),patient);
                        if(familyMember.getIsAuthorize()==1){
                            obj.put("authorizeStatus", 1);//相互授权
                        }else {
                            obj.put("authorizeStatus", 2);//居民单方向向家人授权
                        }

                    }else {
                        obj.put("authorizeStatus", 3);//居民被家人授权
                    }

                }

                if (ssSign && jtSign) {
                    obj.put("signType", 3);
                } else if (!ssSign && jtSign) {
                    obj.put("signType", 2);
                } else if (ssSign && !jtSign) {
                    obj.put("signType", 1);
                } else {
                    obj.put("signType", 0);
                }
                obj.put("state","1");//0 ：未处理；1：已同意；2：已拒绝
                obj.put("id",map.get("id"));
                resultArray.put(obj);
            }
        }

        //待审核记录
        if(StringUtils.isEmpty(doctorCode)&&isAgree==null){
            List<PatientFamilyTemp> tempList = patientFamilyTempDao.findByPatientAndState(patient,"0");
            if(tempList!=null&&tempList.size()>0){
                for (PatientFamilyTemp temp:tempList){
                    JSONObject obj = new JSONObject();
                    Patient p = patientDao.findByCode(temp.getFamilyMember());
                    obj.put("code", p.getCode());
                    obj.put("name", p.getName());
                    obj.put("sex", p.getSex());
                    obj.put("isAuthorize", 0);//0:未授权,1:已授权
                    obj.put("birthday", p.getBirthday());
                    obj.put("idcard", StringUtils.isEmpty(p.getIdcard()) ? "" : p.getIdcard());
                    obj.put("photo", p.getPhoto());
                    obj.put("mobile", p.getMobile());
                    obj.put("address", StringUtils.isEmpty(p.getAddress()) ? "" : p.getAddress());
                    obj.put("familyRelation", temp.getFamilyRelation());
                    obj.put("familyRelationName", relations.get(temp.getFamilyRelation()));
                    obj.put("signType", 0);
                    obj.put("state","0");//0 ：未处理；1：已同意；2：已拒绝
                    obj.put("id",temp.getId());
                    resultArray.put(obj);
                }
            }
        }

        return resultArray;
    }

    /**
     * 是否授权，如果有授权就返回member的个人信息
     * @param patient
     * @param member
     * @return
     */
    public JSONObject isAuthorize(String patient,String member){
        JSONObject json = new JSONObject();
        PatientFamilyMember familyMember = memberDao.findByPatientAndFamilyMember(patient,member);
        if(familyMember==null||0==familyMember.getIsAuthorize()){
            return null;
        }
        return json;
    }

    /**
     * 获取有授权的家庭成员
     * @param patient
     * @return
     */
    public JSONArray getAuthorizeMembers(String patient) throws Exception{
        JSONArray resultArray = new JSONArray();
        resultArray.put(getPatient(patient));

        List<PatientFamilyMember> list = memberDao.findByFamilyMemberAndIsAuthorize(patient,1);

        if (list != null && list.size() > 0) {
            JSONArray tem = new JSONArray();
            for (PatientFamilyMember member : list) {
                JSONObject obj = new JSONObject();
                Patient p = patientDao.findByCode(member.getPatient());
                List<SignFamily> signs = contractService.findAllSignByPatient(p.getCode());
                boolean ssSign = false;
                boolean jtSign = false;

                for (SignFamily sign : signs) {
                    if (sign.getType() == 1 && sign.getStatus() > 0) {
                        ssSign = true;
                    } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                        jtSign = true;
                    } else if (sign.getStatus() == 0) {
                    }
                }

                Integer relation = familyRelationTrans(p,member.getFamilyRelation());

                obj.put("code", p.getCode());
                obj.put("name", p.getName());
                obj.put("sex", p.getSex());
                obj.put("isAuthorize", member.getIsAuthorize());//0:未授权,1:已授权
                obj.put("birthday", p.getBirthday());
                String idCard = StringUtils.isEmpty(p.getIdcard()) ? "" : p.getIdcard();
                obj.put("idcard", CommonUtil.getIdcardEncode(idCard));
                obj.put("idcardAll", idCard);
                obj.put("photo", p.getPhoto());
                obj.put("mobile", p.getMobile());
                obj.put("ssc", p.getSsc());
                obj.put("familyRelation", relation);
                obj.put("familyRelationName", relations.get(relation));

                if (ssSign && jtSign) {
                    obj.put("signType", 3);
                } else if (!ssSign && jtSign) {
                    obj.put("signType", 2);
                } else if (ssSign && !jtSign) {
                    obj.put("signType", 1);
                } else {
                    obj.put("signType", 0);
                }

                if(member.getIsAuthorize()==0){
                    tem.put(obj);
                }else {
                    resultArray.put(obj);
                }
            }

            if(tem.length()>0){
                for(int i =0;i<tem.length();i++){
                    resultArray.put(tem.get(i));
                }
            }
        }

        return resultArray;
    }


    /**
     * 获取居民的家庭成员
     *
     * @param patient 居民
     * @return
     */
    public JSONArray getPatientMembers(String patient, String doctorCode, boolean isContain, String current,Integer isAgree) {
        JSONArray resultArray = getPatientFamilyMembers(patient, doctorCode,isAgree);

        if (resultArray == null) {
            resultArray = new JSONArray();
        }

        if (isContain && !patient.equals(current)) {
            Patient p = patientDao.findByCode(patient);

            JSONObject obj = new JSONObject();
            List<SignFamily> signs = contractService.findAllSignByPatient(p.getCode());
            boolean ssSign = false;
            boolean jtSign = false;

            for (SignFamily sign : signs) {
                if (sign.getType() == 1 && sign.getStatus() > 0) {
                    ssSign = true;
                } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                    jtSign = true;
                } else if (sign.getStatus() == 0) {
                }
            }

            obj.put("code", p.getCode());
            obj.put("name", p.getName());
            obj.put("sex", p.getSex());
            obj.put("birthday", p.getBirthday());
            obj.put("idcard", StringUtils.isEmpty(p.getIdcard()) ? "" : p.getIdcard());
            obj.put("photo", StringUtils.isEmpty(p.getPhoto()) ? "" : p.getPhoto());
            obj.put("mobile", StringUtils.isEmpty(p.getMobile()) ? "" : p.getMobile());
            obj.put("address", StringUtils.isEmpty(p.getAddress()) ? "" : p.getAddress());
            obj.put("familyRelation", "-1");
            obj.put("familyRelationName", "自己");
            obj.put("isAuthorize", 1);//0:未授权,1:已授权
            obj.put("authorizeStatus", 3);//

            if (ssSign && jtSign) {
                obj.put("signType", 3);
            } else if (!ssSign && jtSign) {
                obj.put("signType", 2);
            } else if (ssSign && !jtSign) {
                obj.put("signType", 1);
            } else {
                obj.put("signType", 0);
            }

            resultArray.put(obj);
        }

        return resultArray;
    }


    /**
     * 查询居民的某个家庭成员
     *
     * @param patient
     * @param family
     * @return
     */
    public PatientFamilyMember getPatientFamilyMember(String patient, String family) {
        PatientFamilyMember member = memberDao.findByPatientAndFamilyMember(patient, family);

        return member;
    }

    /**
     * 家庭关系转换
     *
     * @param patient  居民
     * @param relation 关系 1父亲 2母亲 3老公 4老婆 5儿子 6女儿 7其他
     * @return
     */
    public int familyRelationTrans(Patient patient, int relation) throws Exception {
        int relationTrans = 0;

        switch (relation) {
            case 1:
            case 2:
                if (patient.getSex() == 1) {
                    relationTrans = 5;
                } else if (patient.getSex() == 2) {
                    relationTrans = 6;
                } else {
                    relationTrans = 0;
                }
                if (relationTrans == 0) {
                    if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("1")) {
                        relationTrans = 6;
                    } else if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("2")) {
                        relationTrans = 5;
                    }
                }
                break;
            case 3:
                relationTrans = 4;
                break;
            case 4:
                relationTrans = 3;
                break;
            case 5:
            case 6:
                if (patient.getSex() == 1) {
                    relationTrans = 1;
                } else if (patient.getSex() == 2) {
                    relationTrans = 2;
                } else {
                    relationTrans = 0;
                }
                if (relationTrans == 0) {
                    if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("1")) {
                        relationTrans = 2;
                    } else if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("2")) {
                        relationTrans = 1;
                    }
                }
                break;
        }

        return relationTrans;
    }

    /**
     * 验证添加的家庭成员
     *
     * @param menber 预绑定成员
     * @return 0未绑定微信，1仅绑定微信，2仅绑定手机,3手机微信都绑定
     */
    public JSONObject checkFamilyMember(String menber) throws Exception {

        JSONObject r = new JSONObject();

        //未绑定微信，未绑定手机
        int result = 0;

        //1.判断微信过滤
        //判断是否绑定微信，如果版绑定了微信，将状态改变为 1
        Patient p = patientDao.findByCode(menber);

        if (StringUtils.isNotBlank(p.getOpenid())) {
            String sus = getIsSus(p.getOpenid());
            if(StringUtils.isNotBlank(sus)){
                if ("1".equals(sus)) {
                    result = 1;
                }
            }
        }
        //2.判断手机过滤
        //判断是否绑定了手机

        if (StringUtils.isNoneBlank(p.getMobile())&&isMobileNO(p.getMobile())) {
            //如果用户绑定了微信，将状态更改为4
            if (result == 1) {
                result = 3;
                //如果用户未绑定微信，将状态更改为2
            } else if (result == 0) {
                result = 2;
            }
        }
        //返回过滤后的状态
        r.put("state", result);
        if (result == 0) {
            r.put("mes", "未绑定微信和手机");
        } else if (result == 1) {
            r.put("mes", "仅绑定微信");
        } else if (result == 2) {
            r.put("mes", "仅绑定手机");
        } else if (result == 3) {
            r.put("mes", "手机和微信皆绑定");
        }

        return r;


    }


    /**
     * 获取微信的access_token
     *
     * @return
     */
    public String getAccessToken() throws Exception {
        Iterable<AccessToken> accessTokens = accessTokenService.findAccessToken();
        if (accessTokens != null) {
            for (AccessToken accessToken : accessTokens) {
                if ((System.currentTimeMillis() - accessToken.getAdd_timestamp()) < (accessToken.getExpires_in() * 1000)) {
                    return accessToken.getAccess_token();
                } else {
                    accessTokenService.delAccessToken(accessToken);
                    break;
                }
            }
        }
        String token_url = "https://api.weixin.qq.com/cgi-bin/token";
        String params = "grant_type=client_credential&appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret();
        String result = HttpUtil.sendGet(token_url, params);
        JSONObject json = new JSONObject(result);
        if (json.has("access_token")) {
            String token = json.get("access_token").toString();
            String expires_in = json.get("expires_in").toString();
            AccessToken newaccessToken = new AccessToken();
            newaccessToken.setAccess_token(token);
            newaccessToken.setExpires_in(Long.parseLong(expires_in));
            accessTokenService.addAccessToken(newaccessToken);
            return token;
        } else {
            return null;
        }
    }

    /**
     * 查询所有待处理列表
     *
     * @param code
     * @return
     */
    public JSONObject getFamilyMesList(String code) {
        JSONObject result = new JSONObject();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(getFamilyMesListSql(code));
        result.put("mes", list);
        return result;
    }

    public String getFamilyMesListSql(String code) {
        StringBuffer sql = new StringBuffer("SELECT t.*,p.idcard,p.mobile,p.photo FROM wlyy_patient_family_temp t,wlyy_patient p WHERE t.patient = p.code AND t.dealer ='" + code+"'");
        return sql.toString();
    }

    /**
     * 通过用户名密码添加
     *
     * @param patient
     * @param member
     * @param password
     * @param relation
     * @return
     * @throws Exception
     */
    @Transactional
    public int addMemberByPw(String patient, String member, String password, int relation) throws Exception {

        if (patient.equals(member)) {
            return 0;
        }

        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);

        if (p == null) {
            return -1;
        }
        // 添加的成员是否注册判断
        if (m == null) {
            return -2;
        }

        if (StringUtils.isNotEmpty(password)) {
            String loginPassword = MD5.GetMD5Code(password + m.getSalt());
            if (!loginPassword.equals(m.getPassword())) {
                return -3;
            }
        }
        return addMemberFamily(p, m, patient, member, relation);
    }

    /**
     * 通过微信模板添加
     *
     * @param id
     * @param state
     * @return
     * @throws Exception
     */
    @Transactional
    public int addMenberByWXTemp(Long id, String state,String access_token) throws Exception {
        if (StringUtils.isNotBlank(state)) {
            //同意添加
            if ("1".equals(state)) {
                PatientFamilyTemp temp = patientFamilyTempDao.findOne(id);

                if (temp.getPatient().equals(temp.getFamilyMember())) {
                    return 0;
                }

                Patient p = patientDao.findByCode(temp.getPatient());
                Patient m = patientDao.findByCode(temp.getFamilyMember());

                System.out.println("----:openId "+p.getOpenid());
                if (p == null) {
                    return -1;
                }
                // 添加的成员是否注册判断
                if (m == null) {
                    return -2;
                }

                int st = addMemberFamily(p, m, temp.getPatient(), temp.getFamilyMember(), temp.getFamilyRelation());

                if(st==1){
                    //保存
                    temp.setState("1");
                    patientFamilyTempDao.save(temp);

                    if(StringUtils.isNotBlank(p.getOpenid())){
                        //发送添加成功消息模板
                        JSONObject json = new JSONObject();
                        json.put("first", p.getName() + ",您好！"+m.getName()+"已加入到您的家庭成员。");
                        json.put("keyword1", "添加家人申请成功");
                        json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
//                        json.put("keyword3", m.getName());
//                        json.put("keyword4", relations.get(temp.getFamilyRelation()));
                        json.put("remark",
                                "家人："+m.getName()+"\n"+
                                "家庭关系："+relations.get(temp.getFamilyRelation())+"\n"+
                                "点击查看家人。");
                        System.out.println("-----sendMes----:openId "+p.getOpenid()+"-----access_token-----:"+access_token+"--json--");
                        //此消息为定向推送,无需家人代收
                        PushMsgTask.getInstance().putWxMsg(access_token, 13, p.getOpenid(), p.getName(), json);
                    }
                }
                return st;
                //不同意添加
            } else if ("2".equals(state)) {
                PatientFamilyTemp temp = patientFamilyTempDao.findOne(id);
                temp.setState("2");
                patientFamilyTempDao.save(temp);

                Patient p = patientDao.findByCode(temp.getPatient());
                Patient m = patientDao.findByCode(temp.getFamilyMember());

                //发送添加成功消息模板
                JSONObject json = new JSONObject();
                json.put("first", p.getName() + ",您好！"+m.getName()+"拒绝了您的家人申请。");
                json.put("keyword1", "添加家人申请失败");
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark"," ");
                System.out.println("-----sendMes----:openId "+p.getOpenid()+"-----access_token-----:"+access_token+"--json--");
                //此消息为定向推送,无需家人代收
                PushMsgTask.getInstance().putWxMsg(access_token, 14, p.getOpenid(), p.getName(), json);
                return 2;
            }
        }

        return -1;
    }

    @Transactional
    public int addMemberByCaptcha(String patient, String member, String captcha, int relation) throws Exception {

        if (patient.equals(member)) {
            return 0;
        }

        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);
        if (p == null) {
            return -1;
        }
        // 添加的成员是否注册判断
        if (m == null) {
            return -2;
        }

        // 验证码验证
        if (StringUtils.isNotEmpty(captcha)) {
            int checkStatus = smsService.check(m.getMobile(), 10, captcha);
            if (checkStatus == -2) {
                return -6;  // 验证码过期
            } else if (checkStatus == -1) {
                return -3; // 验证码错误
            }
        }

        return addMemberFamily(p, m, patient, member, relation);
    }

    @Transactional
    public int addMemberFamily(Patient p, Patient m, String patient, String member, int relation) throws Exception {

        if (relation>0&&relation < 5) {
            List<PatientFamilyMember> familyMembers = memberDao.findByPatientAndFamilyRelation(patient, relation);

            if (familyMembers != null && familyMembers.size() > 0) {
                return -5;
            }
        }

        // 添加自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        // 家庭关系已存在时，不重复添加
        if (fm != null) {
            return -4;
        } else {
            fm = new PatientFamilyMember();
            fm.setPatient(patient);
            fm.setFamilyMember(member);
        }
        fm.setFamilyRelation(relation);
        fm.setCzrq(new Date());
        fm.setIsAuthorize(1);//默认授权

        // 添加对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);
        // 不存在则创建
        if (fmt == null) {
            fmt = new PatientFamilyMember();
            fmt.setPatient(member);
            fmt.setFamilyMember(patient);
        }

        // 对方与自己的关系转s
        //int relationTrans = familyRelationTrans(p, relation);
        int relationTrans = familyRelationTrans(p, relation);
        fmt.setFamilyRelation(relationTrans);
        fmt.setCzrq(new Date());
        fmt.setIsAuthorize(1);//默认授权

        memberDao.save(fm);
        memberDao.save(fmt);

        //设置家人openid
        if(StringUtils.isBlank(m.getOpenid())){
            m.setOpenid(p.getOpenid());
            patientDao.save(m);
        }

        return 1;
    }

    @Transactional
    public int sendWXTemp(String patient, String member, String access_token, int relation, String reAdd) {

        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);

        if (p == null) {
            return -1;
        }
        // 添加成员是否注册判断
        if (m == null) {
            return -2;
        }

        if(StringUtils.isEmpty(reAdd)){

            List<PatientFamilyTemp> temps =  patientFamilyTempDao.findByDealerAndPatientAndState(member,patient,"0");

            if(temps!=null&&temps.size()>0){
                return -3;
            }
            // 添加自己与对方的关系
            PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
            // 家庭关系已存在时，不重复添加
            if (fm != null) {
                return -4;
            }

            if (relation>0&&relation < 5) {
                List<PatientFamilyMember> familyMembers = memberDao.findByPatientAndFamilyRelation(patient, relation);

                if (familyMembers != null && familyMembers.size() > 0) {
                    return -5;
                }
            }

            PatientFamilyTemp temp = new PatientFamilyTemp();
            temp.setState("0");
            temp.setCzrq(new Date());
            temp.setDealer(member);
            temp.setPatient(patient);
            temp.setPatientName(p.getName());
            temp.setFamilyMember(member);
            temp.setFamilyRelation(relation);
            //
            patientFamilyTempDao.save(temp);

        }
        JSONObject json = new JSONObject();
        json.put("first", m.getName() + ",您好！" + p.getName() + "向您发起添加家人申请，添加成功后，对方可使用您的账号，为您处理各类健康服务。");
        json.put("keyword1", "添加家人申请");
        json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
//        json.put("keyword3", p.getName());
//        json.put("keyword4", relations.get(relation));
        json.put("remark", "申请人："+p.getName()+"\n"+
                "家庭关系："+relations.get(relation)+"\n"+
                "点击立即处理。");
        json.put("member", member);
        //此消息为定向推送,无需家人代收
        PushMsgTask.getInstance().putWxMsg(access_token, 12, m.getOpenid(), m.getName(), json);

        return 1;
    }

    /**
     * 获取subscribe
     *
     * @param openid
     * @return
     * @throws Exception
     */
    public String getIsSus(String openid) throws Exception {
        String userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getAccessToken() + "&openid=" + openid + "&lang=zh_CN";
        String params = "";
        String result = HttpUtil.sendGet(userInfo_url, params);
        JSONObject json = new JSONObject(result);
        if (json.has("subscribe")) {
            return json.get("subscribe").toString();
        } else {
            return null;
        }
    }

    public boolean isMobileNO(String number){
        Pattern pattern = Pattern.compile("^1(3|4|5|7|8)[0-9]\\d{8}$");
        Matcher m = pattern.matcher(number);
        return m.matches();
    }
}
