package com.yihu.wlyy.web.patient.sign;

import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatientGroupInfo;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.doctor.DoctorPatientGroupInfoDao;
import com.yihu.wlyy.service.app.family.FamilyService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.account.*;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdcardValidator;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLDecoder;
import java.util.List;

/**
 * 患者端：家庭签约控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/patient/family_contract", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-家庭签约")
public class FamilyContractController extends BaseController {

    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private FamilyService familyService;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;

    /**
     * 得到患者的签约的医生的信息
     *
     * @param patientCode 患者标识
     * @return
     */
    @RequestMapping(value = "getSignMessage")
    @ResponseBody
    public String getSignDoctorMessage(String patientCode) {
        try {

            JSONArray array = familyContractService.getSignDoctorMessage(patientCode);

            return write(200, "获取列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取列表失败！");
        }
    }


    /**
     * 社区医院列表查询接口
     *
     * @param type     医院类型：0全部，1大医院，2社区医院
     * @param province 患标识
     * @param city     城市标识
     * @param key      搜索关键字，用于搜索医院名称
     * @return
     */
    @RequestMapping(value = "hospitals")
    @ResponseBody
    public String hospitals(
            int type,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String town,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Hospital> list = familyContractService.findHospitals(type, province, city, town, key, id, pagesize);
            if (list != null) {
                for (Hospital hospital : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    // 医院标识
                    json.put("code", hospital.getCode());
                    // 医院名称
                    json.put("name", hospital.getName());
                    // 省名
                    json.put("province_name", hospital.getProvinceName());
                    // 城市名
                    json.put("city_name", hospital.getCityName());
                    // 区县名
                    json.put("town_name", hospital.getTownName());
                    // 详细地址
                    json.put("address", hospital.getAddress());
                    // 简介
                    json.put("intro", hospital.getIntro());
                    // 医院图片
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "获取医院列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院列表失败！");
        }
    }

    /**
     * 社区医院下医生列表查询接口
     *
     * @param hospital 医院标识
     * @return
     */
    @RequestMapping(value = "doctors")
    @ResponseBody
    public String hospitalList(String hospital, long id, int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = familyContractService.findDoctors(hospital, 2, id, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    // 医生标识
                    json.put("code", doctor.getCode());
                    // 医生姓名
                    json.put("name", doctor.getName());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHospitalName());
                    // 科室名称
                    json.put("dept_name", doctor.getDeptName());
                    // 职称名称
                    json.put("job_name", doctor.getJobName());
                    // 头像
                    json.put("photo", doctor.getPhoto());
                    // 简介
                    json.put("introduce", doctor.getIntroduce());
                    // 专长
                    json.put("expertise", doctor.getExpertise());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败！");
        }
    }

    /**
     * 医生主页信息查询接口
     *
     * @param doctor 医生标识
     * @return
     */
    @RequestMapping(value = "homepage")
    @ResponseBody
    public String homepage(String doctor) {
        try {
            JSONObject json = familyContractService.findDoctorMainPage(getUID(), doctor);

            if (json == null) {
                return error(-1, "医生主页查询失败！");
            }
            return write(200, "医生主页查询成功！", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, "医生主页查询失败！");
        }
    }

    /**
     * 与指定医生的签约状态查询接口
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "status")
    @ResponseBody
    public String signStatus(String doctor) {
        try {
            // -1未签约，0待签约，1已签约，2患者申请取消签约，3医生申请取消签约
            int status = familyContractService.findSignStatus(getUID(), doctor);
            return write(200, "数据加载成功！", "data", status);
        } catch (Exception e) {
            error(e);
            return error(-1, "数据加载失败！");
        }
    }

    /**
     * 得到患者的签约信息
     * homePageDoctor,//主页医生code
     * invitePatientCode //邀请患者
     *
     * @return
     */
    @RequestMapping(value = "getPatientSign")
    @ResponseBody
    public String getPatientSign(
            String homePageDoctorCode,//主页医生code
            String invitePatientCode //邀请患者
    ) {
        try {
            JSONObject json = new JSONObject();
            //得到主页医生
            Doctor homePageDoctor = doctorService.findDoctorByCode(homePageDoctorCode);
            //得到邀请患者
            PatientInvitationLog w = familyService.getPatientInviteLog(invitePatientCode);
            //得到被邀请的患者的家庭签约
            SignFamily signFamily = familyContractService.getPatientSign(w.getInvitePatientCode());
            SignFamily ssSignFamily = familyContractService.getssPatientSign(w.getInvitePatientCode());
            json.put("homepage_doctor", homePageDoctor.getCode());
            json.put("homepage_doctorName", homePageDoctor.getName());
            json.put("homepage_photo", homePageDoctor.getPhoto());
            json.put("homepage_sex", homePageDoctor.getSex());
            json.put("homepage_job", homePageDoctor.getJob());
            json.put("homepage_jobName", homePageDoctor.getJobName());
            json.put("homepage_hospital", homePageDoctor.getHospitalName());
            json.put("homepage_dept", homePageDoctor.getDeptName());
            json.put("homepage_intro", homePageDoctor.getIntroduce());
            json.put("homepage_expertise", homePageDoctor.getExpertise());
            json.put("patient_code", w.getInvitePatientCode());//被邀请code
            json.put("patient_name", w.getInvitePatientName());//被邀请人名
            //设置查看病人所在分组
            List<DoctorPatientGroupInfo> dctorPatientGroupInfo = doctorPatientGroupInfoDao.findByMorenPatient(w.getInvitePatientCode());
            if (dctorPatientGroupInfo != null && dctorPatientGroupInfo.size() > 0) {
                json.put("group", dctorPatientGroupInfo.get(0).getGroup());
            } else {
                json.put("group", "0");
            }
            if (signFamily != null) {
                json.put("type", "1");//签约类型 家庭
                json.put("sign_code", signFamily.getCode());// 消息code
                json.put("sign_type", signFamily.getStatus());// -1未签约，0待签约，1已签约，2患者申请取消签约，3医生申请取消签约
                json.put("sign_doctor", signFamily.getDoctor());// 全科医生
                json.put("sign_doctorName", signFamily.getDoctorName());// 全科医生
                json.put("sign_code", signFamily.getCode());// 签约code
            } else if (ssSignFamily != null) {
                json.put("type", "2");//签约类型 三师
                json.put("sign_code", ssSignFamily.getCode());// 消息code
                json.put("sign_type", ssSignFamily.getStatus());// -1未签约，0待签约，1已签约，2患者申请取消签约，3医生申请取消签约
                json.put("sign_doctor", ssSignFamily.getDoctor());// 全科医生
                json.put("sign_doctorName", ssSignFamily.getDoctorName());// 全科医生
                json.put("sign_code", ssSignFamily.getCode());// 签约code
            } else {
                json.put("sign_type", -1);//-1未签约
            }


            return write(200, "数据加载成功！", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, "数据加载失败！");
        }
    }

    /**
     * 校验openid是否有签约信息
     *
     * @return
     */
    @RequestMapping(value = "checkOpenid")
    @ResponseBody
    public String checkOpenid() {
        try {
            if (StringUtils.isEmpty(getOpenid())) {
                return error(-1, "无效的Openid！");
            }
            String doctor = familyContractService.checkPatient(getUID());
            return write(200, "签约验证成功！", "data", doctor);
        } catch (Exception e) {
            error(e);
            return error(-1, "签约验证异常！");
        }
    }

    /**
     * 校验是否有签约信息
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "check")
    @ResponseBody
    public String checkSign(String idcard) {
        try {
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "请输入身份证号！");
            }
            // 解密身份证号
            idcard = RSAUtils.getInstance(familyContractService).decryptString(idcard);
            idcard = URLDecoder.decode(idcard, "UTF-8");
            idcard = StringUtils.reverse(idcard);
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号！");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号！");
            }

            Patient patient = patientService.findByCode(getUID());
            if (!StringUtils.equals(patient.getIdcard(), idcard)) {
                return error(-1, "身份证号错误，请输入注册的身份证号！");
            }
            JSONObject json = familyContractService.checkSign(patient);
            if (json == null) {
                return error(-1, "签约验证异常！");
            }
            return write(200, "签约验证成功！", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, "签约验证异常！");
        }
    }

//    /**
//     * 发送签约申请
//     *
//     * @param province     省代码
//     * @param provinceName 省名称
//     * @param city         城市代码
//     * @param cityName     城市名称
//     * @param town         区县代码
//     * @param townName     区县名称
//     * @param address      详细地址
//     * @param name         患者姓名
//     * @param doctor       医生标识
//     * @param idcard       患者身份证号
//     * @param ssc          患者社保卡号
//     * @param mobile       患者手机号
//     * @param emerMobile   患者紧急联系人
//     */
//    @RequestMapping(value = "sign")
//    @ResponseBody
//    public String sign(
//            @RequestParam(required = false) String province,
//            @RequestParam(required = false) String provinceName,
//            @RequestParam(required = false) String city,
//            @RequestParam(required = false) String cityName,
//            @RequestParam(required = false) String town,
//            @RequestParam(required = false) String townName,
//            @RequestParam(required = false) String address,
//            String name,
//            String doctor,
//            String doctorName,
//            @RequestParam(required = false) String patientCode,
//            @RequestParam(required = false) String idcard,
//            String ssc,
//            @RequestParam(required = false) String mobile,
//            @RequestParam(required = false) String emerMobile) {
//        try {
//            // String openid = getOpenid();
//            // String uid = getUID();
//            // if (StringUtils.isEmpty(openid) && StringUtils.isEmpty(uid)) {
//            // return error(-1, "无效的用户请求！");
//            // }
//            // if (StringUtils.isEmpty(idcard)) {
//            // return error(-1, "身份证号不允许为空！");
//            // }
//            // // 解密身份证号
////			 idcard = RSAUtils.getInstance(familyContractService).decryptString(idcard);
////			 idcard = URLDecoder.decode(idcard, "UTF-8");
////			 idcard = StringUtils.reverse(idcard);
//            if (StringUtils.isEmpty(patientCode)) {
//                patientCode = getUID();
//            }
//            Patient patient = patientService.findByCode(patientCode);
//            int amount = familyContractService.hasSingStatus(patient.getIdcard());
//            if (amount > 0) {
//                return error(-1, "只可以签约一个家庭医生！");
//            }
//            JSONObject json = familyContractService.sign(patient.getProvince(), patient.getProvinceName(),
//                    patient.getCity(), patient.getCityName(), patient.getTown(), patient.getTownName(), patient.getAddress(),
//                    patient.getName(), doctor, patient.getOpenid(), patient.getCode(), patient.getIdcard(), patient.getSsc(), patient.getMobile(), emerMobile);
//            int res = json.getInt("res");
//            if (res == -2) {
//                return error(-1, "身份证号与当前登录用户的身份证号不匹配！");
//            } else if (res == -3) {
//                return error(-1, "身份证号已经注册！");
//            }
//            //更新患者信息
////			if (StringUtils.isEmpty(name) ) {
////				patient.setName(name);
////			}
////			if (StringUtils.isEmpty(idcard) ) {
////				patient.setIdcard(idcard);
////			}
//            if (StringUtils.isEmpty(ssc)) {
//                patient.setSsc(ssc);
//            }
////			if (StringUtils.isEmpty(mobile) ) {
////				patient.setMobile(mobile);
////			}
//            patientService.updatePatientInfo(patient);
//            return write(200, "签约申请已发送！", "data", json);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "签约申请发送失败！");
//        }
//    }

    /**
     * 签约申请
     *
     * @param doctor     医生code
     * @param doctorType 医生类型  2:全科 3:健管
     * @return
     */
    @RequestMapping(value = "sign")
    @ResponseBody
    public String sign(String doctor, int doctorType) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                return error(-1, "签约医生不能为空");
            }
            if (doctorType != 2 && doctorType != 3) {
                return error(-1, "医生类型参数错误");
            }

            int result = familyContractService.sign(doctor, getUID(), doctorType);

            if (result == -1) {
                return error(-1, "用户信息查询失败");
            } else if (result == -2) {
                return error(-1, "用户已存在签约");
            } else if (result == -3) {
                return error(-1, "医生信息查询失败");
            } else {
                return write(200, "签约申请成功");
            }
        } catch (Exception e) {
            return error(-1, "签约申请失败");
        }
    }

    /**
     * 取消签约申请
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "unsign")
    @ResponseBody
    public String unsign(
            String doctor,
            @RequestParam(required = false) String patientCode
    ) {
        try {
            // String openid = getOpenid();
            // String uid = getUID();
            // if (StringUtils.isEmpty(openid) && StringUtils.isEmpty(uid)) {
            // return error(-1, "无效的用户请求！");
            // }
            // -1申请失败， 200申请成功，其他为状态已变化无法取消申请
            patientCode = StringUtils.isNoneBlank(patientCode) ? patientCode : getUID();
            int res = familyContractService.unsign(patientCode, doctor);
            if (res == -1) {
                return error(-1, "取消签约失败！");
            } else if (res == 200) {
                return success("签约申请已取消！");
            } else {
                return error(-1, "签约状态已变化，无法申请取消签约！");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "取消签约失败！");
        }
    }

    /**
     * 申请解约
     *
     * @param doctor     医生标识
     * @param doctorName 医生姓名
     * @return
     */
    @RequestMapping(value = "surrender")
    @ResponseBody
    public String surrender(String doctor, String doctorName, String reason,
                            @RequestParam(required = false) String patientCode) {
        try {
            patientCode = StringUtils.isNoneBlank(patientCode) ? patientCode : getUID();
            Patient patient = patientService.findByCode(patientCode);
            int res = familyContractService.surrender(patient.getCode(), patient.getName(), patient.getPhoto(), doctor, doctorName, patient.getOpenid(), reason, patient.getSex());
            if (res == 0) {
                return error(-1, "解约申请发送失败！");
            } else {
                return success("解约申请已发送！");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "解约申请发送失败！");
        }
    }

    /**
     * 查询患者相关的签约消息
     *
     * @return
     */
    @RequestMapping(value = "messages")
    @ResponseBody
    public String messages(long id, int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Message> list = familyContractService.findMessageByPatient(getUID(), id, pagesize);
            if (list != null) {
                for (Message msg : list) {
                    if (msg == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // 消息ID
                    json.put("id", msg.getId());
                    // 消息标题
                    json.put("title", msg.getTitle());
                    // 消息内容
                    json.put("message", msg.getContent());
                    // 消息类型
                    json.put("type", msg.getType());
                    // 发送人标识
                    json.put("sender", msg.getSender());
                    // 发送人姓名
                    json.put("senderName", msg.getSenderName());
                    // 发送人头像
                    json.put("senderPhoto", msg.getSenderPhoto());
                    // 是否已读：1未读，0已读
                    json.put("read", msg.getRead());
                    // 是否已处理，1为未处理，0为已处理
                    json.put("status", msg.getOver());
                    // 性别
                    json.put("sex", msg.getSex());
                    // 发送时间
                    json.put("czrq", DateUtil.dateToStrLong(msg.getCzrq()));
                    array.put(json);
                }
            }
            return write(200, "获取消息列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取消息列表失败！");
        }
    }

    /**
     * 查询居民是否与某个医生存在签约关系
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_sign_exist",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatientAndDoctorExistSign(@RequestParam(required = true) String doctor){
        try{
            if(StringUtils.isEmpty(doctor)){
                return error(-1,"医生不能为空");
            }
            JSONObject result = familyContractService.isPatientAndDoctorExistSign(getUID(),doctor);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }

    /**
     * 查询居民与某个医生是否可签约
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_can_sign",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatientAndDoctorCanSign(@RequestParam(required = true) String doctor){
        try{
            if(StringUtils.isEmpty(doctor)){
                return error(-1,"医生不能为空");
            }
            JSONObject result = familyContractService.isPatientAndDoctorCanSign(getUID(),doctor);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            return error(-1,"查询失败");
        }
    }
}
