package cn.quantgroup.xyqb.controller.external;

import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.controller.internal.user.InnerController;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.IdCardInfo;
import cn.quantgroup.xyqb.model.IdType;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.util.ValidationUtil;
import cn.quantgroup.xyqb.validator.ChineseName;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.Objects;

/**
 * Created by Miraculous on 2017/1/3.
 */
@Slf4j
@RestController
@RequestMapping("/user_detail")
@Validated
public class UserDetailController implements IBaseController {

    @Autowired
    private IUserDetailService userDetailService;
    @Autowired
    private IIdCardService idCardService;

    /**
     * 保存/更新用户实名信息
     * 注：
     * 本接口会验证用户登录状态，仅用于用户个人补全实名信息操作
     * 产品逻辑是不允许用户重复设置实名信息的，但历史存在导流数据创建不完整实名信息的场景（可理解为和渠道有关）
     * 故此本处保留修改逻辑，仍依赖业务端控制产品行为
     *
     * @param idNo
     * @param name
     * @return
     * @yapi unknown
     * @Deprecated 20210318
     * @see cn.quantgroup.xyqb.controller.internal.user.InnerController#saveUserDetail(Long, String, String, String, String, String)
     */
    @Deprecated
    @RequestMapping("/save")
    @ApiOperation(httpMethod = "POST", value = "保存/更新用户实名信息")
    public JsonResult saveUserDetail(String idNo,
                                     @ChineseName @RequestParam String name) {
        if (!ValidationUtil.validateChinese(name)) {
            log.error("姓名错误,name:{}", name);
            return JsonResult.buildErrorStateResult("姓名错误", null);
        }
        User user = getCurrentUserFromRedis();
        if (user == null) {
            return JsonResult.buildErrorStateResult("系统错误", null);
        }
        IdCardInfo info = idCardService.getIdCardInfo(idNo);
        if (info == null || !info.isValid()) {
            log.error("身份证号错误,userId:{}, idNo: {}", user.getId(), idNo);
            return JsonResult.buildErrorStateResult("身份证号码错误", null);
        }
        /* 保存或更新 */
        UserDetail userDetail = userDetailService.findByUserId(user.getId());
        if (Objects.isNull(userDetail)) {
            userDetail = new UserDetail();
        }
        userDetail.setIdNo(idNo);
        userDetail.setPhoneNo(user.getPhoneNo());
        userDetail.setUserId(user.getId());
        userDetail.setName(name);
        userDetail.setGender(info.getGender());
        userDetail.setIdType(IdType.ID_CARD);
        userDetail.setIsAuthenticated(false);
        log.info("UserDetailController saveUserDetail, userId:{}, phoneNo:{}, name:{}", user.getId(), user.getPhoneNo(), name);
        try {
            userDetailService.saveUserDetail(userDetail);
        } catch (DataIntegrityViolationException ex) {
            return JsonResult.buildSuccessResult("", null);
        }
        return JsonResult.buildSuccessResult("", null);
    }

}
