package cn.com.ctop.kuaishou.modules.ai.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaiShouBatchUpdateService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.service.IBatchService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class KuaiShouBatchUpdateServiceImpl implements IKuaiShouBatchUpdateService {
    @Autowired
    private IKuaiShouGroupService groupService;
    static ExecutorService executorService = Executors.newFixedThreadPool(20);
    @Autowired
    private IBatchService batchService;
    @Autowired
    private IKuaiShouUpdateService updateService;

    @Override
    public void updateBid(CtopOauthToken oauthToken, Long bid) {
        QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("account_id", oauthToken.getAccountId());
        List<KuaiShouGroup> groupList = groupService.list(groupQueryWrapper);
        if (Check.isNull(groupList)) {
            return;
        }
        for (KuaiShouGroup group : groupList) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject unitJson = new JSONObject();
                        unitJson.put("advertiser_id", oauthToken.getAccountId());
                        unitJson.put("unit_id", group.getUnitId());
                        unitJson.put("cpa_bid", bid);
                        updateService.updateUnit(oauthToken.getAccessToken(), unitJson);
                        Thread.sleep(1500);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
