package cn.quantgroup.xyqb.controller.internal.user;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import cn.quantgroup.xyqb.aspect.accessable.IpValidator;
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.model.UserModel;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.ValidationUtil;
import cn.quantgroup.xyqb.validator.ChineseName;

/**
 * 同步用户数据，第三方模块访问时
 * Created by Miraculous on 15/12/29.
 */
@Slf4j
@RestController
@RequestMapping("/api/sync")
public class SyncUserController {
    private static final String KEY = "abc1234";
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserDetailService userDetailService;
    @Autowired
    private IIdCardService idCardService;

    @RequestMapping("/save_detail")
    @ApiOperation(httpMethod = "POST", value = "保存/更新用户实名信息")
    public JsonResult saveUserDetail(String key, String phoneNo, String idNo,
                                     @ChineseName @RequestParam String name) {
        if (!Objects.equals(KEY, key)) {
            return JsonResult.buildErrorStateResult(null, null);
        }
        if (!ValidationUtil.validatePhoneNo(phoneNo)) {
            log.error("手机号错误,phoneNo:{}", phoneNo);
            return JsonResult.buildErrorStateResult("手机号错误", phoneNo);
        }
        if (!ValidationUtil.validateChinese(name)) {
            log.error("姓名错误,name:{}", name);
            return JsonResult.buildErrorStateResult("姓名错误", name);
        }
        IdCardInfo info = idCardService.getIdCardInfo(idNo);
        if (Objects.isNull(info) || !info.isValid()) {
            log.error("身份证号错误,idNo:{}", idNo);
            return JsonResult.buildErrorStateResult("身份证号码错误", idNo);
        }
        User user = userService.findByPhoneWithCache(phoneNo);
        if (Objects.isNull(user)) {
            log.error("用户不存在,phoneNo:{}", phoneNo);
            return JsonResult.buildErrorStateResult("用户不存在", phoneNo);
        }
        /* 保存或更新 */
        UserDetail userDetail = userDetailService.findByUserId(user.getId());
        if (Objects.isNull(userDetail)) {
            userDetail = new UserDetail();
        }
        userDetail.setUserId(user.getId());
        userDetail.setIdNo(idNo);
        userDetail.setPhoneNo(phoneNo);
        userDetail.setName(name);
        userDetail.setGender(info.getGender());
        userDetail.setIdType(IdType.ID_CARD);
        userDetail.setIsAuthenticated(false);
        log.info("SyncUserController saveUserDetail, userId:{}, phoneNo:{}, name:{}", user.getId(), phoneNo, name);
        try {
            userDetailService.saveUserDetail(userDetail);
        } catch (DataIntegrityViolationException ex) {
            return JsonResult.buildSuccessResult("", null);
        }

        /*
         * 如果已存在记录，则更新
         */
        UserDetail theUserDetail = userDetailService.findByUserId(user.getId());
        if (Objects.isNull(theUserDetail)) {
            userDetail.setId(null);
        } else {
            userDetail.setId(theUserDetail.getId());
        }
        userDetailService.saveUserDetail(userDetail);
        return JsonResult.buildSuccessResult(null, null);
    }

    @RequestMapping("/user")
    @ApiOperation(httpMethod = "POST", value = "查询用户详情")
    public JsonResult fetchUser(String key, String phoneNo) {
        if (!Objects.equals(KEY, key) || !ValidationUtil.validatePhoneNo(phoneNo)) {
            return JsonResult.buildErrorStateResult(null, null);
        }
        User user = userService.findByPhoneInDb(phoneNo);
        if (Objects.isNull(user)) {
            return JsonResult.buildErrorStateResult(null, null);
        }
        UserDetail detail = userDetailService.findByUserId(user.getId());
        UserModel userModel = new UserModel(user, detail);
        return JsonResult.buildSuccessResult(null, userModel);
    }

    @RequestMapping("/user_uuid")
    public JsonResult fetchUserByUuid(String key, String uuid) {
        if (StringUtils.isEmpty(key) || !KEY.equals(key)) {
            return JsonResult.buildErrorStateResult(null, null);
        }
        if (StringUtils.isEmpty(uuid)) {
            return JsonResult.buildErrorStateResult(null, null);
        }
        User user = userService.findByUuidWithCache(uuid);
        if (null == user) {
            return JsonResult.buildErrorStateResult(null, null);
        }
        UserDetail detail = userDetailService.findByUserId(user.getId());
        UserModel userModel = new UserModel(user, detail);
        return JsonResult.buildSuccessResult(null, userModel);
    }

    /**
     * 根据用户主键批量获取用户实名信息
     * @param userIds - 多个之间用英文,分隔
     * @return List<UserDetail>
     */
    @IpValidator
    @RequestMapping("/listByUserIds")
    @ApiOperation(httpMethod = "POST", value = "根据用户主键批量获取用户实名信息")
    public JsonResult listByUserIds(String userIds) {
        // 过滤掉合法的多个数值串间的空白值
        userIds = ValidationUtil.filterNumbers(userIds);
        if (!ValidationUtil.validateNumbers(userIds)) {
            return JsonResult.buildErrorStateResult("参数不正确", null);
        }
        List<Long> userIdList = Arrays.asList(userIds.split(",|;")).stream().map(userId -> Long.valueOf(userId)).collect(Collectors.toList());
        List<UserDetail> userDetailList = userDetailService.findByUserIdIn(userIdList);
        return JsonResult.buildSuccessResult(null, userDetailList);
    }
}
