package com.weaver.seconddev.chapanda.esign.esb;

import com.alibaba.fastjson.JSONObject;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.seconddev.chapanda.esign.entity.OkHttpDto;
import com.weaver.seconddev.chapanda.esign.util.Esb2EsignCreateUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service("Esb2EsignCreateUserAction")
public class Esb2EsignCreateUserAction implements EsbServerlessRpcRemoteInterface {
    private final static Logger log = LoggerFactory.getLogger(Esb2EsignCreateUserAction.class);

    @Autowired
    Esb2EsignCreateUserUtil esb2EsignCreateUserUtil;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> params) {

        String mobile = String.valueOf(params.get("mobile"));
        String name = String.valueOf(params.get("name"));

        log.error("mobile:{}",mobile);
        log.error("name:{}",name);

        if(StringUtils.isBlank(mobile)){
            return WeaResult.fail(500,"入参手机号为空");
        }
        if(StringUtils.isBlank(name)){
            return WeaResult.fail(500,"入参姓名为空");
        }

        String esignAccountId = "";
        String uniqueId = "";
        if(StringUtils.isNotBlank(mobile) && StringUtils.isNotBlank(name)){
            OkHttpDto okHttpDto = esb2EsignCreateUserUtil.createUser(name,mobile);
            if(okHttpDto.getResponseCode() == 200){
                if(okHttpDto.getDataCode() == 0){
                    JSONObject dataJson = okHttpDto.getDataJson();
                    if(dataJson.containsKey("esignAccountId")){
                        esignAccountId = dataJson.getString("esignAccountId");
                    }
                    if(dataJson.containsKey("uniqueId")){
                        uniqueId = dataJson.getString("uniqueId");
                    }
                }else{
                    return WeaResult.fail(500,"E签宝用户创建异常,"+okHttpDto.getDataMsg());
                }
            }else{
                return WeaResult.fail(500,"E签宝用户创建接口异常,"+okHttpDto.getDataMsg());
            }
        }

        if(StringUtils.isBlank(esignAccountId)){
            return WeaResult.fail(500,"e签宝创建用户失败");
        }

        Map<String, Object> actionMap = new HashMap<String, Object>();
        actionMap.put("code",200);
        actionMap.put("esignAccountId",esignAccountId);
        actionMap.put("mobile",mobile);
        actionMap.put("uniqueId",uniqueId);
        return WeaResult.success(actionMap);
    }
}
