package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.service.IBindAccountLoginService;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.crawler.modules.appium.entity.AppiumDevice;
import cn.com.ctop.crawler.modules.appium.entity.AppiumTaskLog;
import cn.com.ctop.crawler.modules.appium.mapper.AppiumTaskLogMapper;
import cn.com.ctop.crawler.modules.appium.service.IAppiumDeviceService;
import cn.com.ctop.crawler.modules.appium.service.IAppiumJobService;
import cn.com.ctop.crawler.modules.appium.service.IAppiumTaskService;
import org.jeecg.modules.ctop.service.ICrawlerService;
import org.jeecg.modules.ctop.vo.KuaishouAppiumJobVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class CrawlerServiceImpl implements ICrawlerService {
    static ExecutorService executorService = null;
    @Autowired
    private IBindAccountLoginService bindAccountLoginService;
    @Autowired
    private IAppiumJobService jobService;
    @Autowired
    private IAppiumTaskService taskService;
    @Autowired
    private IAppiumDeviceService deviceService;
    @Autowired
    private AppiumTaskLogMapper taskLogMapper;

    @Override
    public Map<String, Object> startJob(KuaishouAppiumJobVO jobVO) {
        Map<String, Object> result = new HashMap<>();
        //TODO 需要考虑多个任务并行的问题
        //1:根据id查询快手账号信息
        BindAccountLogin accountLogin = bindAccountLoginService.getById(jobVO.getAccountId());
        if (null == accountLogin) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR.getCode());
            return result;
        }
        if (jobVO.getJobId() == null || jobVO.getJobId() == 0 || jobVO.getNum() == null || jobVO.getNum() == 0 || jobVO.getCreativeName() == null || "".equals(jobVO.getCreativeName()) || jobVO.getPublishName() == null || "".equals(jobVO.getPublishName().trim())) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR.getCode());
            return result;
        }
        Long num = jobVO.getNum();
        //获取手机设备信息
        AppiumDevice device = deviceService.getEnabled();
        if (null == device || device.getStatus() != 1) {
            ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_CRAWLER_APP_NO_ENABLED_DEVICE.getCode());
            return result;
        }
        executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (i < num) {
                    if (i > num) {
                        break;
                    }
                    deviceService.updateById(device);
                    AppiumTaskLog log = new AppiumTaskLog();
                    log.setDeviceId(device.getId());
                    log.setDeviceIp(device.getIp());
                    log.setDevicePort(device.getPort());
                    log.setStatus(1 + "");
                    log.setTaskId(jobVO.getJobId());
                    log.setTaskName("快手刷量任务");
                    taskLogMapper.insert(log);
                    log.setId(log.getId());
                    try {
                        //一键新机
                        boolean success = jobService.refreshWebPhone();
                        if (!success) {
                            jobService.updateStatus(device, log, -4, 1);
                            continue;
                        }
                        Thread.sleep(10000L);
                        String ksId = jobService.loginTask(2L, device);
                        if (null == ksId) {
                            i++;
                            jobService.updateStatus(device, log, -1, 1);
                            continue;
                        }
                        boolean isBind = jobService.bindCreative(accountLogin.getAccountName(), accountLogin.getPassword(), jobVO.getPublishName(), ksId);
                        if (!isBind) {
                            i++;
                            jobService.updateStatus(device, log, -2, 1);
                            continue;
                        }
                        taskService.runTask(1L, device.getId(), jobVO.getPublishName());
                        jobService.updateStatus(device, log, 2, 1);
                        i++;
                    } catch (Exception e) {
                        jobService.updateStatus(device, log, -3, 1);
                        i++;
                        continue;
                    }
                }
            }
        });
        ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_CRAWLER_APP_JOB_StART.getCode());
        return result;
    }
}
