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

import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.service.app.family.FamilyMemberService;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 家庭关系成员控制器
 * <p>
 * Created by lyr-pc on 2016/10/18.
 */
@RestController
@RequestMapping(value = "/patient/family")
@Api(description = "家庭成员")
public class FamilyMemberController extends WeixinBaseController {

    @Autowired
    FamilyMemberService familyMemberService;
    @Autowired
    PatientFamilyMemberDao familyMemberDao;
    @Autowired
    PatientDao patientDao;

    /**
     * 添加成员
     *
     * @param member   成员code
     * @param captcha  验证码
     * @param relation 关系
     * @return
     */
    @RequestMapping(value = "/member_add", method = RequestMethod.POST)
    @ApiOperation(value = "添加成员")
    public String addFamilyMember(@RequestParam("member") String member,
                                  @RequestParam(value = "captcha", required = false) String captcha,
                                  @RequestParam(value = "password", required = false) String password,
                                  @RequestParam("relation") int relation) {
        try {
            if (StringUtils.isEmpty(member)) {
                return error(-1, "添加成员不能为空");
            }
            if (StringUtils.isEmpty(captcha) && StringUtils.isEmpty(password)) {
                return error(-1, "验证码或密码不能为空");
            }
            if (relation < 0 || relation > 6) {
                return error(-1, "家庭关系无效");
            }

            int result = familyMemberService.addMember(getUID(), member, captcha, password, relation);

            if (result == -1) {
                return error(-1, "居民信息查询失败");
            } else if (result == -2) {
                return error(-1, "该成员未注册");
            } else if (result == -3) {
                return error(-1, StringUtils.isNotEmpty(captcha) ? "请输入正确的验证码" : "密码错误");
            } else if (result == -4) {
                return error(-1, "该家庭成员已存在");
            } else if (result == -5) {
                return error(-1, "该家庭关系已存在成员");
            } else if (result == -6) {
                return error(-1, "验证码已过期，请重新获取验证码");
            } else if (result == 0) {
                return error(-1, "不能添加自己");
            } else {
                return write(200, "添加成功");
            }
        } catch (Exception e) {
            return error(-1, "添加失败");
        }
    }

    /**
     * 更新家庭关系
     *
     * @param member   成员code
     * @param relation 家庭关系
     * @return
     */
    @RequestMapping(value = "/relation_update", method = RequestMethod.POST)
    @ApiOperation(value = "家庭成员关系修改")
    public String modifyFamilyRelation(@RequestParam("member") String member, @RequestParam("relation") int relation) {
        try {
            if (StringUtils.isEmpty(member)) {
                return error(-1, "添加成员不能为空");
            }
            if (relation < 0 || relation > 6) {
                return error(-1, "家庭关系无效");
            }

            int result = familyMemberService.modifyFamilyRelation(getUID(), member, relation);

            if (result == -1) {
                return error(-1, "居民信息查询失败");
            } else if (result == -2) {
                return error(-1, "该成员未注册");
            } else if (result == -3) {
                return error(-1, "与该成员的关系不存在");
            } else if(result==-5){
                return error(-1, "该家庭关系已存在成员");
            } else {
                return write(200, "更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }

    @RequestMapping(value = "/member_revoke", method = RequestMethod.POST)
    @ApiOperation(value = "撤销添加家庭成员")
    @ResponseBody
    public String revokeAddFamily(@ApiParam(name = "id", value = "关系", defaultValue = "1")
                                  @RequestParam(value = "id", required = true) Long id){
        try {

            int result = familyMemberService.revokeAddMember(id);
            if(result==1){
                return error(-1, "已同意，撤销失败");
            }else if(result == 2){
                return error(-1, "已拒绝，撤销失败");
            }else if(result == 3){
                return error(-1, "已撤销，请不要重复操作");
            }

            return write(200, "撤销成功");
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "撤销失败");
        }
    }

    /**
     * 删除成员
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "/member_delete", method = RequestMethod.POST)
    @ApiOperation(value = "家庭成员删除")
    public String deleteMember(@RequestParam("member") String member) {
        try {
            if (StringUtils.isEmpty(member)) {
                return error(-1, "成员不能为空");
            }

            int result = familyMemberService.deleteMember(getUID(), member);

            if (result == -1) {
                return error(-1, "与该成员的关系不存在");
            } else {
                return write(200, "删除成功");
            }
        } catch (Exception e) {
            return error(-1, "删除失败");
        }
    }

    @RequestMapping(value = "/member_authorize", method = RequestMethod.POST)
    @ApiOperation(value = "家庭成员授权")
    public String authorizeMember(@ApiParam(name = "familyMember", value = "家人code", defaultValue ="1555c32c626343e7aaa62e9cf76c97f2")
                                  @RequestParam(value = "familyMember", required = true) String familyMember,
                                  @ApiParam(name = "isAuthorize", value = "是否授权（0:未授权,1:已授权）", defaultValue ="1")
                                  @RequestParam(value = "isAuthorize", required = true) Integer isAuthorize){
        try {

            int result = familyMemberService.authorizeMember(getUID(),familyMember,isAuthorize);
            if(result==0){
                return error(-1, "与该成员的关系不存在");
            }
            return write(200, "授权成功");
        }catch (Exception e){
            return error(-1,"授权失败");
        }
    }


    /**
     * 家庭成员查询
     * @param patient
     * @param isAgree (任意值已同意（只查询家人关系表），null不同意)
     * @return
     */
    @RequestMapping(value = "/members", method = RequestMethod.GET)
    @ApiOperation(value = "家庭成员查询")
    public String getPatientFamilyMembers(@RequestParam(required = false) String patient,
                                          @RequestParam(required = false) Integer isAgree) {
        try {
            JSONArray result = new JSONArray();
            if (StringUtils.isNotEmpty(patient)) {
                result = familyMemberService.getPatientMembers(patient, "", true, getUID(),isAgree);
            } else  {
                result = familyMemberService.getPatientFamilyMembers(getUID(), "",null);
            }
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    @RequestMapping(value = "/authorize_members", method = RequestMethod.GET)
    @ApiOperation(value = "家庭成员(有授权)查询")
    public String getAuthorizeFamilyMembers(){
        try {
            JSONArray result = familyMemberService.getAuthorizeMembers(getUID());

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    @RequestMapping(value = "/is_authorize", method = RequestMethod.GET)
    @ApiOperation(value = "是否授权查询")
    public String isAuthorize(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                              @RequestParam(value = "patient", required = true) String patient,
                              @ApiParam(name = "familyMember", value = "家人code", defaultValue = "")
                              @RequestParam(value = "familyMember", required = true) String familyMember){
        try {
            Patient p = patientDao.findByCode(patient);
            JSONObject json = new JSONObject();
            json.put("code", p.getCode());
            json.put("name", p.getName());

            if(patient.equals(familyMember)){
                return write(200,"自己","data", json);
            }
            PatientFamilyMember member = familyMemberDao.findByPatientAndFamilyMember(patient,familyMember);
            if(member==null){
                return write(1,"不是家人","data", json);
            }
            if(1==member.getIsAuthorize()){
                return write(200, "查询成功", "data", json);
            }

            return write(1,"未授权","data", json);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 根据身份证号查询居民是否注册
     *
     * @param idcard 身份证号
     * @return
     */
    @RequestMapping(value = "/is_register", method = RequestMethod.GET)
    @ApiOperation(value = "家庭成员查询")
    public String isRegister(@RequestParam("idcard") String idcard) {
        try {
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不能为空");
            }

            JSONObject result = familyMemberService.isRegister(idcard, getUID());

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 验证家庭成员微信及手机绑定情况
     * @param memberCode
     * @return
     */
    @RequestMapping(value = "/check_member", method = RequestMethod.GET)
    @ApiOperation(value = "验证家庭成员微信及手机绑定情况")
    public String checkFamilyMember(@RequestParam("memberCode")String memberCode){
        try {
            JSONObject result = familyMemberService.checkFamilyMember(memberCode);
            return write(200, "验证成功", "data", result);
        }catch (Exception e){
            return error(-1, "验证失败");
        }
    }

    /**
     * 获取用户消息列表
     * @param code 业务主键
     * @return
     */
    @RequestMapping(value = "/getFamilyMesList", method = RequestMethod.POST)
    @ApiOperation(value = "获取用户消息列表")
    public String getFamilyMesList(@RequestParam("code") String code){
        try {
            JSONObject result = familyMemberService.getFamilyMesList(code);
            return write(200, "查询成功", "data", result);
        }catch (Exception e){
            return error(-1, "验证失败");
        }
    }

    @RequestMapping(value = "/addMemberByPw", method = RequestMethod.POST)
    @ApiOperation(value = "通过登录验证新增家庭成员")
    public String addMemberByPw(@RequestParam("member") String member,
                                @RequestParam("password")String password,
                                @RequestParam("relation")int relation){
        try {
            if (StringUtils.isEmpty(member)) {
                return error(-1, "添加成员不能为空");
            }
            if (relation < 0 || relation > 6) {
                return error(-1, "家庭关系无效");
            }

            int result = familyMemberService.addMemberByPw(getUID(),member,password,relation);

            if(result==0){
                return error(-1, "不能添加自己");
            }else if(result==-1){
                return error(-1, "居民信息查询失败");
            }else if(result==-2){
                return error(-1, "该成员未注册");
            }else if(result==-3){
                return error(-1, "密码错误");
            }else if (result == -4) {
                return error(-1, "该家庭成员已存在");
            }else if(result==-5){
                return error(-1, "该家庭关系已存在成员");
            } else {
                return write(200, "添加成功");
            }
        } catch (Exception e) {
            return error(-1, "添加失败");
        }
    }

    @RequestMapping(value = "/addMemberByCaptcha", method = RequestMethod.POST)
    @ApiOperation(value = "通过手机验证码新增家庭成员")
    public String addMemberByCaptcha(@RequestParam("member") String member,
                                     @RequestParam("captcha") String captcha,
                                     @RequestParam("relation") int relation){
        try {
            if (StringUtils.isEmpty(member)) {
                return error(-1, "添加成员不能为空");
            }
            if (StringUtils.isEmpty(captcha)) {
                return error(-1, "验证码不能为空");
            }
            if (relation < 0 || relation > 6) {
                return error(-1, "家庭关系无效");
            }

            int result = familyMemberService.addMemberByCaptcha(getUID(),member,captcha,relation);

            if(result==0){
                return error(-1, "不能添加自己");
            }else if(result==-1){
                return error(-1, "居民信息查询失败");
            }else if(result==-2){
                return error(-1, "该成员未注册");
            }else if(result==-3){
                return error(-1, "验证码错误");
            }else if (result == -4) {
                return error(-1, "该家庭成员已存在");
            }else if(result==-5){
                return error(-1, "该家庭关系已存在成员");
            }else if(result==-6){
                return error(-1, "验证码已过期，请重新获取验证码");
            } else {
                return write(200, "添加成功");
            }
        } catch (Exception e) {
            return error(-1, "添加失败");
        }
    }

    @RequestMapping(value = "/addMenberByWXTemp", method = RequestMethod.POST)
    @ApiOperation(value = "通过微信模板新增家庭成员")
    public String addMenberByWXTemp(@RequestParam("id") Long id,
                                    @RequestParam("state") String state){
        try {

            int result = familyMemberService.addMenberByWXTemp(id,state,getAccessToken());

            if(result==0){
                return error(-1, "不能添加自己");
            }else if(result==-1){
                return error(-1, "居民信息查询失败");
            }else if(result==-2){
                return error(-1, "该成员未注册");
            }else if (result == -4) {
                return error(-1, "该家庭成员已存在");
            }else if(result==-5){
                return error(-1, "该家庭关系已存在成员");
            }else if(result ==2) {
                return write(200, "拒绝成功");
            }else{
                return write(200, "添加成功");
            }
        } catch (Exception e) {
            return error(-1, "添加失败");
        }
    }

    /**
     *
     * @param member
     * @param relation
     * @param reAdd 重新添加标志
     * @return
     */
    @RequestMapping(value = "/sendWXTemp", method = RequestMethod.POST)
    @ApiOperation(value = "发送微信模板")
    public String sendWXTemp(@RequestParam("member")String member,@RequestParam("relation")int relation
                ,@RequestParam(value = "reAdd", required = false) String reAdd){
        try {
            int result = familyMemberService.sendWXTemp(getUID(),member,getAccessToken(),relation,reAdd);
            //int result = familyMemberService.sendWXTemp("d682497b7552459797145b6cd63f0ef5",member,getAccessToken(),relation);
            if(result==-1){
                return error(-1, "居民信息查询失败");
            }else if(result==-2){
                return error(-1, "该成员未注册");
            }else if(result ==-3){
                return error(-1, "申请已经提交");
            }else if (result == -4) {
                return error(-1, "该家庭成员已存在");
            }else if(result==-5){
                return error(-1, "该家庭关系已存在成员");
            }else {
                return write(200, "发送成功");
            }
        } catch (Exception e) {
            return error(-1, "发送失败");
        }
    }

    @RequestMapping(value = "/getOpenIdByCode", method = RequestMethod.POST)
    @ApiOperation(value = "获取openId")
    public String getOpenId(@RequestParam("code")String code){
        String openId = getOpenidByCode(code);
        return write(200, openId);
    }

    @RequestMapping(value = "/getPw", method = RequestMethod.POST)
    @ApiOperation(value = "获取密码")
    public String getPw(@RequestParam("pw")String pw){
        String loginPassword = MD5.GetMD5Code(pw + "1");
        return write(200,loginPassword);
    }
}
