package cn.sh.stc.sict.theme.hphy.controller.mp;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.sh.stc.sict.cloud.common.core.util.R;
import cn.sh.stc.sict.cloud.common.security.util.SecurityUtils;
import cn.sh.stc.sict.cloud.upms.dto.CurrentUser;
import cn.sh.stc.sict.cloud.upms.model.SysUserBase;
import cn.sh.stc.sict.theme.hphy.constant.PatientConstant;
import cn.sh.stc.sict.theme.hphy.model.HphyPatientBase;
import cn.sh.stc.sict.theme.hphy.service.HphyPatientBaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


/**
 * 患者基本信息
 *
 * @author F_xh。
 * @date 2020-09-29 15:05:29
 */
@RestController
@RequestMapping("/hphy/c/patientbase")
@AllArgsConstructor
@Slf4j
@Api(tags = "[D]患者基本信息")
public class HphyPatientBaseController {

    private HphyPatientBaseService hphyPatientBaseService;

    /**
     * 注册并关联登录信息
     *
     * @param patient
     * @return
     */
    @ApiOperation("注册")
    @PostMapping("/register")
    public R register(@RequestBody HphyPatientBase patient) {
        CurrentUser current = SecurityUtils.getCurrentUser();
        HphyPatientBase base = hphyPatientBaseService.getByOpenId(current.getOpenId());
        patient.setOpenId(current.getOpenId());
        if (base != null) {
            patient.setId(base.getId());
        }
        // 身份证验证
        if (StrUtil.isBlank(patient.getCertId())) {
            return new R().error("身份证号不可为空！");
        }
        if (!IdcardUtil.isValidCard(patient.getCertId())) {
            return new R().error("身份证号验证失败！");
        }
        // 获取性别，年龄
        patient.setAge(String.valueOf(IdcardUtil.getAgeByIdCard(patient.getCertId())));
        patient.setGender(IdcardUtil.getGenderByIdCard(patient.getCertId()) == 1 ? "男" : "女");
        // 手机号redis验证
        // 根据手机号去重
        hphyPatientBaseService.saveOrUpdate(patient);

        return new R(patient.getId());
    }

    /**
     * 1. 发送注册短信验证码[调用黄埔webservice接口]
     */

    /**
     * F_xh
     * 获取患者信息
     *
     * @return
     */
    @GetMapping
    public R getInfo() {
        CurrentUser current = SecurityUtils.getCurrentUser();

        if (StrUtil.isBlank(current.getOpenId())) {
            log.error("openId 为空");
        }
        // 获取患者信息
        HphyPatientBase base = hphyPatientBaseService.getByOpenId(current.getOpenId());

        if (base != null && StrUtil.isNotBlank(base.getGender())) {
            current.setGender(PatientConstant.getGender(base.getGender()));
            SecurityUtils.updateCurrent(current);
        }

        return new R(base);
    }
}
