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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouProjectVideoGet;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouCreativeMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouVideoGetMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouProjectVideoGetMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouProjectVideoGetService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxl.job.core.enums.NoEn;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 快手-项目下视频信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-05-21
 */
@Slf4j
@Service
public class KuaishouProjectVideoGetServiceImpl extends ServiceImpl<KuaishouProjectVideoGetMapper, KuaishouProjectVideoGet> implements IKuaishouProjectVideoGetService {
    static ExecutorService kuaiShouExecutorService = Executors.newFixedThreadPool(5);
    @Autowired
    private KuaishouProjectVideoGetMapper projectVideoGetMapper;
    @Autowired
    private KuaiShouVideoGetMapper videoGetMapper;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Resource
    private KuaiShouCreativeMapper kuaiShouCreativeMapper;
    @Autowired
    private IKuaiShouUpdateService kuaiShouUpdateService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;

    @Override
    public void clearProjectVideo(Long projectId, Integer pageNo, String updateTime) {
        try {
            if (Check.isNull(updateTime) && pageNo == 1) {
                updateTime = projectVideoGetMapper.queryLatestUpdateTime(projectId);
            }
            PageHelper.startPage(pageNo, 1000, false);
            List<KuaishouProjectVideoGet> list = videoGetMapper.selectProjectVideo(projectId, updateTime);
            if (Check.isNull(list)) {
                return;
            }
            log.info("清洗快手项目素材数据，projectId:{}，pageNo:{}，size:{}", projectId, pageNo, list.size());
            projectVideoGetMapper.replaceBatch(list);
            Thread.sleep(500);
            clearProjectVideo(projectId, pageNo + 1, updateTime);
        } catch (Exception e) {
            log.error("清洗项目数据异常", e);
        }
    }

    @Override
    public Result<Object> queryPageList(KuaishouProjectVideoGet kuaishouProjectVideoGet, Integer pageNo, Integer pageSize) {
        Long total = projectVideoGetMapper.queryPageListTotal(kuaishouProjectVideoGet);
        PageHelper.startPage(pageNo, pageSize, false);
        PageInfo pageInfo = new PageInfo(projectVideoGetMapper.queryPageList(kuaishouProjectVideoGet));
        pageInfo.setTotal(total);
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> getVideoTotalNumber(Long projectId) {
        //本周一
        String monday = DateUtils.getdateFromWeek(1);
        //当天日期
        String today = DateUtils.formatDate(new Date());
        //上周一日期
        String lastStartDate = DateUtils.getLastDay(monday, 7);
        //上周当天日期
        String lastEndDate = DateUtils.getLastDay(today, 7);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("lastStartDate", lastStartDate);
        paramsMap.put("lastEndDate", lastEndDate);
        paramsMap.put("monday", monday);
        paramsMap.put("today", today);
        paramsMap.put("projectId", projectId);
        return Result.ok(projectVideoGetMapper.getVideoTotalNumber(paramsMap));
    }

    @Override
    public Result<Object> getVideoDetails(String signature, String id) {
        return Result.ok(projectVideoGetMapper.getVideoDetails(signature, id));
    }

    @Override
    public Result<Object> getAccountVideos(String signature, Long projectId, Integer pageNo, Integer pageSize) {
        Long total = projectVideoGetMapper.getAccountVideosTotal(signature, projectId);
        PageHelper.startPage(pageNo, pageSize, false);
        PageInfo<JSONObject> list = new PageInfo<>(projectVideoGetMapper.getAccountVideos(signature, projectId));
        list.setTotal(total);
        return Result.ok(list);
    }

    @Override
    public Result<Object> queryCreativeBySignature(List<String> photoIds, Long accountId, Integer pageNo, Integer pageSize) {
        Long total = kuaiShouCreativeMapper.queryCreativeByPhotoIdTotal(photoIds, accountId);
        PageHelper.startPage(pageNo, pageSize, false);
        PageInfo<JSONObject> list = new PageInfo<>(kuaiShouCreativeMapper.queryCreativeByPhotoIds(photoIds, accountId));
        list.setTotal(total);
        return Result.ok(list);

    }

    @Override
    public void deleteCreativesByPhotoId(Object photoId) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = "";
        if (!Check.isNull(user)) {
            userId = user.getId();
        }
        List<JSONObject> list = kuaiShouCreativeMapper.queryCreativeByPhotoId(String.valueOf(photoId));
        if (!Check.isNull(list)) {
            for (JSONObject data : list) {
                Long accountId = data.getLong("accountId");
                Long creativeId = data.getLong("creativeId");
                CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
                if (!Check.isNull(token)) {
                    String finalUserId = userId;
                    kuaiShouExecutorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            kuaiShouUpdateService.updateCreativeStatus(token.getAccessToken(), accountId, creativeId, NoEn.NO3.valueInt(), finalUserId);
                        }
                    });
                }
            }
        }
    }

    @Override
    public List<KuaiShouVideoGet> getNewVideoBetweenTime(Long accountId, String startTime, String endTime, Integer channelType) {
        return projectVideoGetMapper.getNewVideoBetweenTime(accountId, startTime, endTime, channelType);
    }

    @Override
    public List<KuaiShouVideoGet> getZeroVideoByParams(Long accountId, String startTime, String endTime, Long videoCnt, String appVersion, Integer channelType, Integer relativeCnt) {
        return projectVideoGetMapper.getZeroVideoByParams(accountId, startTime, endTime, videoCnt, appVersion, channelType, relativeCnt);
    }

    @Override
    public List<KuaiShouVideoGet> getHistoryTopVideoByParams(Long accountId, String startTime, String endTime, Long videoCnt, String appVersion, Integer channelType) {
        return projectVideoGetMapper.getHistoryTopVideoByParams(accountId, startTime, endTime, videoCnt, appVersion, channelType);
    }
}
