package com.liquidnet.service.adam.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.constant.AdamEnum;
import com.liquidnet.service.adam.dto.vo.AdamRealInfoVo;
import com.liquidnet.service.adam.dto.vo.AdamUserBizAcctVo;
import com.liquidnet.service.adam.service.AdamRdmService;
import com.liquidnet.service.adam.service.IAdamUserBusiAcctService;
import com.liquidnet.service.adam.service.IAdamUserService;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class AdamUserBusiAcctServiceImpl implements IAdamUserBusiAcctService {
    @Autowired
    AdamRdmService adamRdmService;
    @Autowired
    IAdamUserService adamUserService;


    @Autowired
    Environment env;
//    @Value("${liquidnet.service.galaxy.url}")// TODO: 2022/3/29 ==zhanggb
//    private String sevGalaxyUrl;

    @Override
    public ResponseDto<AdamUserBizAcctVo> openAccount(String uid, String bizCode, String name, String idCard, String mobile) {
        List<AdamUserBizAcctVo> userBizAcctVoList = adamRdmService.getBizAcctVosByUid(uid);
        if (!CollectionUtils.isEmpty(userBizAcctVoList)) {
            Optional<AdamUserBizAcctVo> optional = userBizAcctVoList.stream().filter(r -> r.getBizCode().equals(bizCode)).findAny();
            if (optional.isPresent()) return ResponseDto.success(optional.get());
        }

        if (AdamEnum.BizAcct.NFT_ZX.name().equals(bizCode)) {
            ResponseDto<AdamUserBizAcctVo> responseDto = this.openAccountForNftZXin(uid, name, idCard, mobile);
            if (responseDto.isSuccess()) {
                adamRdmService.addBizAcctVoByUid(uid, userBizAcctVoList, responseDto.getData());
            }
            return responseDto;
        }
        log.error("#开通业务账号:无效的业务码[UID={},bizCode={}]", bizCode, uid);
        return ResponseDto.failure();
    }

    /**
     * 数字藏品账号开通-至信链
     *
     * @param uid
     * @param name
     * @param idCard
     * @param mobile
     * @return ResponseDto<AdamUserBizAcctVo>
     */
    private ResponseDto<AdamUserBizAcctVo> openAccountForNftZXin(String uid, String name, String idCard, String mobile) {
        AdamRealInfoVo realInfoVo = adamRdmService.getRealInfoVoByUid(uid);
        if (StringUtils.isBlank(name) || name.contains("*")) {
            if (null == realInfoVo) {
                return ResponseDto.failure(ErrorMapping.get("10102"));
            }
            name = realInfoVo.getName();
            idCard = realInfoVo.getIdCard();
            if (realInfoVo.getNode() != 3) {// 非三要素认证先做认证
                adamUserService.identityForUpsert(uid, name, idCard, mobile, true);
            }
        } else {
            if (null == realInfoVo || (3 != realInfoVo.getNode() && !realInfoVo.getName().equals(name) && !realInfoVo.getIdCard().equals(idCard))) {
                adamUserService.identityForUpsert(uid, name, idCard, mobile, true);
            }
        }

        LinkedMultiValueMap<String, String> paramsMap = CollectionUtil.linkedMultiValueMapStringString();
        paramsMap.add("routerType", "zxinchain");// TODO: 2022/3/29 ==zhanggb
        paramsMap.add("userId", uid);
        paramsMap.add("idCardType", "1");
        paramsMap.add("idCard", idCard);
        paramsMap.add("userName", name);
        paramsMap.add("mobile", mobile);

//        String postUrl = sevGalaxyUrl + "/user/register", blockChainAddress;// TODO: 2022/3/29 ==zhanggb
        String postUrl = "https://ENVgalaxy.zhengzai.tv/galaxy/user/register".replace("ENV", env.getProperty(CurrentUtil.CK_ENV_ACTIVE)), blockChainAddress;
        try {
            LinkedMultiValueMap<String, String> headerMap = CollectionUtil.linkedMultiValueMapStringString();
            headerMap.add("Accept", MediaType.APPLICATION_JSON_VALUE);
            String postRespStr = HttpUtil.post(postUrl, paramsMap, headerMap);
            JsonNode postRespJNode = JsonUtils.fromJson(postRespStr, JsonNode.class);
            if (null == postRespJNode || !postRespJNode.get("code").asText().equals("0")) {
                log.warn("#开通业务账号:至信数字藏品账号开通失败[paramsMap={},postRespStr={}]", paramsMap, postRespStr);
                return ResponseDto.failure(ErrorMapping.get("10113"));
            }
            JsonNode postRespDataJNode = postRespJNode.get("data");
            blockChainAddress = postRespDataJNode.get("blockChainAddress").asText();
        } catch (Exception e) {
            log.error("Ex.开通业务账号:至信数字藏品账号开通请求异常[UID={},url={},paramsMap={}],ex:{}", uid, postUrl, paramsMap, e.getMessage());
            return ResponseDto.failure(ErrorMapping.get("10113"));
        }

        AdamUserBizAcctVo userBizAcctVo = AdamUserBizAcctVo.getNew();
        userBizAcctVo.setBizCode(AdamEnum.BizAcct.NFT_ZX.name());
        userBizAcctVo.setState(AdamEnum.BizAcctStatus.OPENED.getVal());
        userBizAcctVo.setUuid(blockChainAddress);
        return ResponseDto.success(userBizAcctVo);
    }
}
