package org.jeecg.modules.ctop.job;

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.service.IBindAccountLoginService;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

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

@Slf4j
public class KuaishouCommentAutoDelete implements Job {
    @Value("${chrome.script.clean}")
    private String cleanUrl;
    @Autowired
    private IKuaishouWebInterfaceService kuaishouWebInterfaceService;
    @Autowired
    private IBindAccountLoginService bindAccountLoginService;
    static ExecutorService executorService = null;
    //线程计数器
    static CountDownLatch countDownLatch = null;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Long start = System.currentTimeMillis();
        List<BindAccountLogin>loginList = bindAccountLoginService.getListByParams(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_PY,1);
        if (loginList != null && !loginList.isEmpty()) {
            executorService = Executors.newFixedThreadPool(5);
            countDownLatch = new CountDownLatch(loginList.size());
            loginList.forEach(login -> executorService.submit(()->{
                try {
                    kuaishouWebInterfaceService.deleteAllComment(new HashMap<>(),login);
                    Runtime runtime = Runtime.getRuntime();
                    Process pro = runtime.exec(cleanUrl);
                    int status = pro.waitFor();
                    if (status == 0) {
                        log.info("success，删除评论调用shell脚本执行成功");
                    } else {
                        log.info("error，删除评论调用shell脚本执行失败");
                    }
                    Thread.sleep(3 * 1000L);
                }catch (Exception e){
                    log.error(e.getMessage(),e);
                }finally {
                    countDownLatch.countDown();
                }
            }));
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Long end = System.currentTimeMillis();
            log.info("快手删评论所用时长：{}毫秒",end-start);
        }
    }
}
