package cn.quantgroup.xyqb.service.user.impl;

import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.util.JsonUtil;
import cn.quantgroup.xyqb.util.PasswordUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;


/**
 * @author mengfan.feng
 * @time 2015-08-19 18:20
 */
@Service
@Slf4j
public class LkbUserviceImpl implements ILkbUserService {

    private static final String TOKEN_PATTERN = "timeunit=%sappkey=lkb010203#$%%";
    private static final String LKB_CODE = "0002";

    @Autowired
    private IHttpService httpService;

    @Value("${lkb.client.url}")
    private String clientUrl;

    @Override
    public boolean pushUser(String uuid, String phoneNo, String name, String idNo) {
        String timeunit = System.currentTimeMillis() + "";
        String token = PasswordUtil.MD5(String.format(TOKEN_PATTERN, timeunit));
        Map<String, String> parameters = Maps.newHashMap();
        parameters.put("appId", LKB_CODE);
        parameters.put("timeunit", timeunit);
        parameters.put("token", token);
        parameters.put("userId", uuid);
        parameters.put("loginName", phoneNo);
        if (StringUtils.isNotBlank(name)) {
            parameters.put("realName", name);
        }
        if (StringUtils.isNotBlank(idNo)) {
            parameters.put("idCardNo", idNo);
        }
        String response = httpService.post(clientUrl + "/user/push.json", parameters);
        Optional<Map> resultOptional = JsonUtil.fromJson(response, Map.class);
        if (!resultOptional.isPresent() || !Constants.SUCCESS_CODE.equals(resultOptional.get().get(Constants.RESULT_CODE))) {
            log.error("[lkb_user_push]向LKB同步用户失败,phoneNo:{},response={}", phoneNo, response);
            return false;
        }
        return true;
    }
}
