package cn.com.ctop.toutiao.modules.material.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.toutiao.modules.material.mapper.ByteDanceTransferBalanceMapper;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceTransferBalanceService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class ByteDanceTransferBalanceServiceImpl implements IByteDanceTransferBalanceService {

    @Autowired
    private ByteDanceTransferBalanceMapper balanceMapper;

    @Autowired
    IUserAllocationService userAllocationService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    @Override
    public Result getTransferBalance(List<Long> accountIdList) {
        String adid = PropertiesUtils.getValue("bytedance_config", "admin_account_id");
        CtopOauthToken token = oauthTokenService.getTokenByAccountId(Long.valueOf(adid));
        //转账-查询账户转账余额（代理）
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_rapi_url")
                + PropertiesUtils.getValue("bytedance_config", "bytedance_v3_query_transfer_balance");
        Map<String, Object> param = new HashMap<>();
        param.put("biz_request_no", UUID.randomUUID().toString());
        param.put("agent_id", 73970348172L);
        param.put("account_id_list", accountIdList);
        Map<String, String> header = new HashMap<>();
        header.put("Access-Token", token.getAccessToken());
        JSONObject result = JSONObject.parseObject(HttpUtils.httpGet(url, param, header));
        System.out.println("结果result：" + result);
        if (!Check.isNull(result)) {
            String code = result.getString("code");
            if ("0".equals(code)) {
                //违规信息入库
                JSONObject data = result.getJSONObject("data");
                JSONArray accontAmountDetailList = data.getJSONArray("accont_amount_detail_list");
                List<JSONObject> list = new ArrayList<>();
                for (int i = 0; i < accontAmountDetailList.size(); i++) {
                    JSONObject obj = accontAmountDetailList.getJSONObject(i);
                    JSONArray capitalDetailList = obj.getJSONArray("capital_detail_list");
                    JSONObject cdl = new JSONObject();
                    capitalDetailList.stream().forEach(cap -> {
                        JSONObject capObj = (JSONObject) cap;
                        cdl.put(capObj.getString("capital_type"), capObj.getLong("transfer_balance"));
                    });
                    obj.put("capitalDetailList", cdl.toJSONString());
                    JSONObject project = userAllocationService.getAccountInfoByAccountId(obj.getLong("account_id"));
                    if (!Check.isNull(project)) {
                        obj.put("projectId", project.getLong("projectId"));
                        obj.put("projectName", project.getString("projectName"));
                        obj.put("accountName", project.getString("accountName"));
                    }
                    list.add(obj);
                }
                if (!Check.isNull(list)) {
                    balanceMapper.replaceBatch(list);
                }
                return Result.successMsg("success", null);
            } else {
                log.error("查询账户转账余额失败，原因：" + result.getString("message"));
            }
        }
        return Result.error(result.getString("message"));

    }

    @Override
    public Result getCanTransferBalance(JSONObject data) {
        String adid = PropertiesUtils.getValue("bytedance_config", "admin_account_id");
        CtopOauthToken token = oauthTokenService.getTokenByAccountId(Long.valueOf(adid));
        //转账-获取最大可转余额（代理）
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_rapi_url")
                + PropertiesUtils.getValue("bytedance_config", "bytedance_v3_query_can_transfer_balance");
        Map<String, Object> param = new HashMap<>();
        param.put("biz_request_no", UUID.randomUUID().toString());
        param.put("agent_id", 73970348172L);
        param.put("target_account_id_list", data.getJSONArray("target_account_id_list"));
        param.put("account_id", data.getLong("account_id"));
        param.put("transfer_direction", data.getString("transfer_direction"));
        Map<String, String> header = new HashMap<>();
        header.put("Access-Token", token.getAccessToken());
        JSONObject result = JSONObject.parseObject(HttpUtils.httpGet(url, param, header));
        System.out.println("结果result：" + result);
        if (!Check.isNull(result)) {
            String code = result.getString("code");
            if ("0".equals(code)) {
                //违规信息入库
                JSONObject restdata = result.getJSONObject("data");
                JSONArray accontAmountDetailList = restdata.getJSONArray("can_transfer_detail_list");
                return Result.successMsg(result.getString("message"), accontAmountDetailList);

            } else {
                log.error("获取最大可转余额失败，原因：" + result.getString("message"));
            }
        }
        return Result.error(result.getString("message"));
    }

    @Override
    public Result createTransfer(JSONObject data) {
        String adid = PropertiesUtils.getValue("bytedance_config", "admin_account_id");
        CtopOauthToken token = oauthTokenService.getTokenByAccountId(Long.valueOf(adid));
        //转账-发起转账（代理）
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_rapi_url")
                + PropertiesUtils.getValue("bytedance_config", "bytedance_v3_create_transfer");
        Map<String, Object> param = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        param.put("biz_request_no", uuid);
        param.put("agent_id", 73970348172L);
        param.put("target_account_id_list", data.getJSONArray("target_account_detail_list"));
        param.put("account_id", data.getLong("account_id"));
        param.put("transfer_direction", data.getString("transfer_direction"));
        Map<String, String> header = new HashMap<>();
        String accessToken = token.getAccessToken();
        header.put("Access-Token", accessToken);
        JSONObject result = JSONObject.parseObject(HttpUtils.httpPostRequest(url, param, header));
        System.out.println("结果result：" + result);
        if (!Check.isNull(result)) {
            String code = result.getString("code");
            if ("0".equals(code)) {
                JSONObject restData = result.getJSONObject("data");
                String transferSerial = restData.getString("transfer_serial");
                System.out.println(transferSerial);
                return Result.successMsg(result.getString("message"), transferSerial);
            } else {
                log.error("发起转账失败，原因：" + result.getString("message"));
            }
        }
        return Result.error(result.getString("message"));
    }

    @Override
    public Result queryTransferDetail(String transferNo) {
        String adid = PropertiesUtils.getValue("bytedance_config", "admin_account_id");
        CtopOauthToken token = oauthTokenService.getTokenByAccountId(Long.valueOf(adid));
        //转账-查询转账单信息（代理）
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_rapi_url")
                + PropertiesUtils.getValue("bytedance_config", "bytedance_v3_create_transfer");
        Map<String, Object> param = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        param.put("biz_request_no", uuid);
        param.put("agent_id", 73970348172L);
        param.put("transfer_serial", transferNo);//转账单号，与transfer_biz_request_no两者传其一即可
//      param.put("transfer_biz_request_no", "");//发起转账的幂等id
        Map<String, String> header = new HashMap<>();
        header.put("Access-Token", token.getAccessToken());
        JSONObject result = JSONObject.parseObject(HttpUtils.httpGet(url, param, header));
        System.out.println("结果result：" + result);
        if (!Check.isNull(result)) {
            String code = result.getString("code");
            if ("0".equals(code)) {
                JSONObject restData = result.getJSONObject("data");
                System.out.println(restData);
                return Result.successMsg(result.getString("message"), restData);
            } else {
                log.error("查询转账单信息失败，原因：" + result.getString("message"));
            }
        }
        return Result.error(result.getString("message"));
    }

}
