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.SignFamily;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
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.util.IdCardUtil;
import com.yihu.wlyy.util.MD5;
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.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 家庭成员服务
 * <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
    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, "女儿");
    }

    /**
     * 添加家庭成员
     *
     * @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 < 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.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());

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

        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;
        }

        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);
        }

        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;
    }

    /**
     * 获取居民的家庭成员
     *
     * @param patient 居民
     * @return
     */
    public JSONArray getPatientFamilyMembers(String patient, String doctorCode) {
        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;
                    }
                }

                obj.put("code", map.get("code"));
                obj.put("name", map.get("name"));
                obj.put("sex", map.get("sex"));
                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 (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 居民
     * @return
     */
    public JSONArray getPatientMembers(String patient, String doctorCode, boolean isContain, String current) {
        JSONArray resultArray = getPatientFamilyMembers(patient,doctorCode);

        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", "自己");

            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;
    }
}
