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

import com.yihu.wlyy.entity.address.City;
import com.yihu.wlyy.entity.address.Province;
import com.yihu.wlyy.entity.address.Street;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.demographic.DemographicInfo;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.login.LoginLog;
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.SocialSecurityInfo;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.repository.address.CityDao;
import com.yihu.wlyy.repository.address.ProvinceDao;
import com.yihu.wlyy.repository.address.StreetDao;
import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.repository.demographic.TblBasicDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientInvitationLogDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.service.app.family.FamilyMemberService;
import com.yihu.wlyy.service.app.family.FamilyService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.service.common.login.LoginLogService;
import com.yihu.wlyy.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.EncodesUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 患者基本信息类.
 *
 * @author George
 */
@Component
@Transactional
public class PatientInfoService extends BaseService {

    @Autowired
    private PatientDao patientDao;
    @Autowired
    private ProvinceDao provinceDao;
    @Autowired
    private CityDao cityDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private StreetDao streetDao;
    @Autowired
    private PatientInvitationLogDao patientInviteLogDao;
    @Autowired
    private TblBasicDao tblBasicDao;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    SMSService smsService;
    @Autowired
    SignFamilyDao signFamilyDao;
    @Autowired
    FamilyMemberService familyMemberService;
    @Autowired
    TokenService tokenService;
    @Autowired
    FamilyService familyService;
    @Autowired
    LoginLogService loginLogService;
    @Autowired
    PatientService patientService;


    /**
     * 患者更换手机号
     *
     * @param patient 患者code
     * @param mobile  新手机号
     * @param captcha 验证码
     * @return
     */
    public int changeMobile(String patient, String mobile, String captcha, int type) {
        Patient p = patientDao.findByCode(patient);

        if (p == null) {
            return -1;
        }

        Patient pMobile = patientDao.findByMobile(mobile);

        if (pMobile != null && !pMobile.getCode().equals(patient)) {
            return -2;
        }

        // 验证码验证
        int smsCheck = smsService.check(mobile, type == 1 ? 8 : 9, captcha);
        // 验证失败，不允许变更
        if (smsCheck != 1) {
            return -3;
        }

        p.setMobile(mobile);
        signFamilyDao.updatePatientMobile(p.getCode(), mobile);

        return 1;
    }

    /**
     * 手机号是否注册
     *
     * @param mobile
     * @return
     */
    public int isMobileRegister(String mobile) {
        Patient p = patientDao.findByMobile(mobile);

        if (p != null) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 切换家人账号
     *
     * @param patient 当前居民
     * @param family  待切换家人
     * @return
     */
    public JSONObject switchFamilyAccount(String patient, String family, String openid) throws Exception {
        JSONObject result = new JSONObject();

        Patient fp = patientDao.findByCode(family);
        // 家庭成员信息查询失败
        if (fp == null) {
            result.put("status", -1);
            return result;
        }

        if(!patient.equals(family)) {
            PatientFamilyMember member = familyMemberService.getPatientFamilyMember(patient, family);
            // 家庭成员中不存在该人
            if (member == null) {
                result.put("status", -2);
                return result;
            }
        }

        LoginLog loginLog = new LoginLog();
        loginLog.setCreateTime(new Date());
        loginLog.setPhone(fp.getMobile());
        loginLog.setUserType("1");
        loginLog.setType("3");

        // 用户校验通过，生成token
        Token token = tokenService.newTxToken(fp.getCode(), openid);
        JSONObject map = new JSONObject();

        map.put("id", fp.getId());
        map.put("uid", fp.getCode());
        map.put("name", fp.getName());
        map.put("token", token.getToken());
        map.put("photo", fp.getPhoto());

        // 绑定用户手机号和openid
        if (!StringUtils.equals(fp.getOpenid(), openid)) {
            //fp.setOpenid(openid);
            patientService.updatePatient(fp, openid);
        }

        if (StringUtils.isNoneEmpty(openid)) {
            //发送微信模板
            familyService.sendWXMessage(fp);
        }

        loginLogService.saveLog(loginLog);

        result.put("status", 1); // 切换账号成功
        result.put("data", map);

        return result;
    }

    /**
     * 根据患者标识查询患者信息
     *
     * @param code
     * @return
     */
    public Patient findByCode(String code) {
        return patientDao.findByCode(code);
    }

    /**
     * 根据患者身份证号码查询患者信息
     *
     * @param idcard
     * @return
     */
    public Patient findByIdcard(String idcard) {
        return patientDao.findByIdcard(idcard);
    }

    // 根據病情等级获取患者信息
    public Iterable<Patient> findInfoByLevel(int level) {
        return patientDao.findInfoByLevel(level);
    }

    /**
     * 更新患者基本信息
     *
     * @param patient
     */
    public Patient updatePatient(Patient patient) {
        if (StringUtils.isNotEmpty(patient.getStreet())) {
            Street street = streetDao.findByCode(patient.getStreet());
            patient.setStreetName(street.getName());
        } else {
            patient.setStreetName("");
        }
        Province province = provinceDao.findByCode(patient.getProvince());
        if (province != null) {
            patient.setProvinceName(province.getName());
        } else {
            patient.setProvinceName("");
        }
        City city = cityDao.findByCode(patient.getCity());
        if (city != null) {
            patient.setCityName(city.getName());
        } else {
            patient.setCityName("");
        }
        Town town = townDao.findByCode(patient.getTown());
        if (town != null) {
            patient.setTownName(town.getName());
        } else {
            patient.setTownName("");
        }
        return patientDao.save(patient);
    }

    public Patient updateUser(Patient patient) {
        return patientDao.save(patient);
    }

    /**
     * 修改患者密码
     *
     * @param patient
     */
    public void updatePatientPwd(Patient patient) {
        EncodesUtil.entryptPassword(patient);
        patientDao.save(patient);
    }

    public Patient invilogCode(String invilogCode) {
        PatientInvitationLog patientInviteLog = patientInviteLogDao.findOne(invilogCode);
        String patientCode = patientInviteLog.getInvitePatientCode();
        Patient patient = patientDao.findByCode(patientCode);
        return patient;
    }

    public boolean validatePatient(String name, String idCard, String ssc) {
        DemographicInfo demographicInfo = tblBasicDao.findByIdCard(idCard);
        SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18(idCard);
        if (demographicInfo != null && socialSecurityInfo != null) {
            String nameTemp = demographicInfo.getName();

        }
        return false;
    }

    public void checkMobile(String mobile) throws Exception {
        Patient p = patientDao.findByMobile(mobile);
        if (p != null) {
            throw new Exception("手机号已经被注册");
        }
    }

    @Transactional
    public void updatePassword(String newPassword1, String newPassword2, String oldPassword, String patientCode) throws Exception {
        if (!newPassword1.equals(newPassword2)) {
            throw new Exception("新密码不一致");
        }
        if (newPassword1.equals(oldPassword)) {
            throw new Exception("新旧密码一致");
        }
        Patient patient = patientDao.findByCode(patientCode);
        String oldPasswordTemp = MD5.GetMD5Code(oldPassword + patient.getSalt());
        if (!oldPasswordTemp.equals(patient.getPassword())) {
            throw new Exception("旧密码错误");
        }
        String newPassword1Temp = MD5.GetMD5Code(newPassword1 + patient.getSalt());
        patient.setPassword(newPassword1Temp);
    }
}
