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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.RuleDataAccount;
import cn.com.ctop.common.module.mapper.RuleDataAccountMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IRuleDataAccountService;
import cn.com.ctop.toutiao.modules.report.service.IRuleByteDanceAccountService;
import cn.com.ctop.toutiao.modules.tool.service.IByteDanceGetAccountFundService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RuleByteDanceAccountServiceImpl extends ServiceImpl<RuleDataAccountMapper, RuleDataAccount> implements IRuleByteDanceAccountService {

    @Autowired
    IByteDanceGetAccountFundService byteDanceGetAccountFundService;
    @Autowired
    ICtopOauthTokenService oauthTokenService;
    @Autowired
    IRuleDataAccountService ruleDataAccountService;

    @Override
    public void cleanRuleDataAccount(Long accountId) {
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        //查询账户实时数据
        JSONObject dataAccount = byteDanceGetAccountFundService.getAccountReportBy(oauthToken, accountId);
        if (!dataAccount.isEmpty()) {
            JSONObject fundData = byteDanceGetAccountFundService.getAccountFundBy(oauthToken, accountId);
            RuleDataAccount ruleDataAccount = new RuleDataAccount();
            ruleDataAccount.setId(accountId);
            ruleDataAccount.setAccountId(accountId);
            ruleDataAccount.setAccountName(fundData.getString("name"));
            ruleDataAccount.setCost(dataAccount.getBigDecimal("cost"));
            ruleDataAccount.setValidBalance(fundData.getBigDecimal("valid_balance"));
            ruleDataAccount.setConvertNum(dataAccount.getLong("convert"));
            ruleDataAccount.setConvertCost(dataAccount.getBigDecimal("convert_cost"));
            ruleDataAccount.setNextDayOpenNum(dataAccount.getLong("next_day_open"));
            ruleDataAccount.setNextDayOpenCost(dataAccount.getBigDecimal("next_day_open_cost"));
            ruleDataAccount.setNextDayOpenRate(dataAccount.getBigDecimal("next_day_open_rate"));

            ruleDataAccountService.saveOrUpdate(ruleDataAccount);
        }
    }

    @Override
    public void getBytedanceAccountBalance(CtopOauthToken token) {
        JSONObject fundData = byteDanceGetAccountFundService.getAccountFundBy(token, token.getAccountId());
        ruleDataAccountService.replaceBytedanceAccountBalance(fundData);
    }
}
