package io.renren.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.renren.common.constant.LLianPayConstant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.HttpClientUtil;
import io.renren.common.vo.agree.AgreeApplyReq;
import io.renren.common.vo.agree.AgreeApplyResp;
import io.renren.common.vo.agree.AgreePageQueryResp;
import io.renren.common.vo.agree.AgreePageQueryResp.PapSignInfo;
import io.renren.common.vo.agree.AgreeQueryResp;
import io.renren.dao.LAgreeDao;
import io.renren.entity.LAgreeEntity;
import io.renren.service.AgreeService;
import io.renren.vo.AgreeApplyParams;
import io.renren.vo.AgreePageQueryParams;
import io.renren.vo.AgreeQueryParams;

@Service
public class AgreeServiceImpl implements AgreeService {
	
	@Autowired
	private LAgreeDao agreeDao;
	
	@Autowired
	private LLianPayConstant constant;
	
	@Override
	public AgreeApplyResp agreeApply(AgreeApplyReq agreeSignInfo) throws Exception {
		AgreeApplyParams params = new AgreeApplyParams();
        String timestamp = DateUtils.getTimestamp();
        params.setTimestamp(timestamp);
        params.setOid_partner(constant.getOidPartner());
        params.setTxn_seqno(DateUtils.getCurrentTime());
        params.setTxn_time(timestamp);
        params.setUser_id(agreeSignInfo.getUserId());
        params.setFlag_chnl("H5");
        params.setNotify_url(constant.getNotifyUrl());
        params.setReturn_url(constant.getReturnUrl());

        // 设置签约信息
        AgreeApplyParams.AgreeSignInfoParam papAgreeSignInfo = params.new AgreeSignInfoParam();
        papAgreeSignInfo.setSign_start_time(agreeSignInfo.getSignStartTime());
        papAgreeSignInfo.setSign_invalid_time(agreeSignInfo.getSignInvalidTime());
        papAgreeSignInfo.setSingle_limit(agreeSignInfo.getSingleLimit());
        papAgreeSignInfo.setDaily_limit(agreeSignInfo.getDailyLimit());
        papAgreeSignInfo.setMonthly_limit(agreeSignInfo.getMonthlyLimit());
        papAgreeSignInfo.setAgreement_type(agreeSignInfo.getAgreementType());
        params.setPapSignInfo(papAgreeSignInfo);

        String resultJsonStr = HttpClientUtil.sendRequest(constant.getPapAgreeApply(), JSON.toJSONString(params),constant.getPrivateKey(),constant.getPublicKey());
        AgreeApplyResp result = JSON.parseObject(resultJsonStr, AgreeApplyResp.class);
        if(!LLianPayConstant.RET_CODE.equals(result.getRetCode())) {
        	throw new Exception("调用连连接【协议申请】接口失败："+result.getRetMsg());
        }
		return result;
	}


	@Override
	public AgreeQueryResp agreeQuery(String userId,String agreeNo) throws Exception {
		AgreeQueryParams params = new AgreeQueryParams();
        params.setTimestamp(DateUtils.getTimestamp());
        params.setOid_partner(constant.getOidPartner());
        params.setUser_id(userId);
        params.setPap_agree_no(agreeNo);

        String resultJsonStr = HttpClientUtil.sendRequest(constant.getPapAgreeQuery(), JSON.toJSONString(params),constant.getPrivateKey(),constant.getPublicKey());
        AgreeQueryResp result = JSON.parseObject(resultJsonStr, AgreeQueryResp.class);
        if(!LLianPayConstant.RET_CODE.equals(result.getRetCode())) {
        	throw new Exception("调用连连接【协议单条查询】接口失败："+result.getRetMsg());
        }
		return result;
		
	}


	@Override
	public AgreePageQueryResp agreePageQuery(String userId) throws Exception {
		AgreePageQueryParams params = new AgreePageQueryParams();
        params.setTimestamp(DateUtils.getTimestamp());
        params.setOid_partner(constant.getOidPartner());
        params.setUser_id(userId);
        params.setStatus("Enabled");
        params.setPage_no("1");
        params.setPage_size("10");
        
        String resultJsonStr = HttpClientUtil.sendRequest(constant.getPapAgreePagequery(), JSON.toJSONString(params),constant.getPrivateKey(),constant.getPublicKey());
        AgreePageQueryResp result = JSON.parseObject(resultJsonStr, AgreePageQueryResp.class);
        if(!LLianPayConstant.RET_CODE.equals(result.getRetCode())) {
        	throw new Exception("调用连连接【协议分页查询】接口失败："+result.getRetMsg());
        }
        
        agreeDao.delete(new QueryWrapper<LAgreeEntity>().lambda().eq(LAgreeEntity::getUserId, userId));
        
        List<PapSignInfo> papSignInfo = result.getPapSignInfo();
        papSignInfo.forEach(info->{
        	LAgreeEntity agree = new LAgreeEntity();
        	agree.setUserId(userId);
        	agree.setOidPartner(result.getOidPartner());
        	BeanUtils.copyProperties(info, agree);
			agreeDao.insert(agree);
        });
        
		return result;
	}
	
	

}




/**
 * 
协议申请
{
    "accp_txno":"2022102900281016",
    "gateway_url":"https://test.lianlianpay-inc.com/accp-user-auth-web/apply?token=5ad86b1d671e5d2f221d63471d5c7921",
    "oid_partner":"2020042200284052",
    "ret_code":"0000",
    "ret_msg":"交易成功",
    "txn_seqno":"LLianPayTest20221029190816",
    "user_id":"LLianPayTest-En-User-123"
}


协议单条查询
{
    "oid_partner":"2020042200284052",
    "papSignInfo":{
        "agreement_type":"WITH_HOLD",
        "daily_limit":"100000.00",
        "monthly_limit":"500000.00",
        "pap_agree_no":"2022102300275010",
        "sign_invalid_time":"20331001",
        "sign_start_time":"20221023",
        "single_limit":"50000.00",
        "status":"Enabled"
    },
    "ret_code":"0000",
    "ret_msg":"交易成功",
    "user_id":"LLianPayTest-En-User-123"
}




协议分页查询
{
    "oid_partner":"2020042200284052",
    "papSignInfo":[
        {
            "agreement_type":"WITH_HOLD",
            "daily_limit":"100000.00",
            "monthly_limit":"500000.00",
            "pap_agree_no":"2022102300275016",
            "sign_invalid_time":"20331001",
            "sign_start_time":"20221023",
            "single_limit":"50000.00",
            "status":"Enabled"
        },
        {
            "agreement_type":"WITH_HOLD",
            "daily_limit":"100000.00",
            "monthly_limit":"500000.00",
            "pap_agree_no":"2022102300275010",
            "sign_invalid_time":"20331001",
            "sign_start_time":"20221023",
            "single_limit":"50000.00",
            "status":"Enabled"
        },
        {
            "agreement_type":"WITH_HOLD",
            "daily_limit":"100000.00",
            "monthly_limit":"500000.00",
            "pap_agree_no":"2022101500272010",
            "sign_invalid_time":"20331001",
            "sign_start_time":"20321001",
            "single_limit":"50000.00",
            "status":"Enabled"
        }
    ],
    "ret_code":"0000",
    "ret_msg":"交易成功",
    "total_num":"3",
    "total_page":"1",
    "user_id":"LLianPayTest-En-User-123"
}
 */
