package com.fdkankan.ucenter.task;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fdkankan.common.util.DateUtil;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.ucenter.common.RedisKeyUtil;
import com.fdkankan.ucenter.common.StatisticsUtil;
import com.fdkankan.ucenter.common.constants.NacosProperty;
import com.fdkankan.ucenter.common.utils.AuthLicenseUtil;
import com.fdkankan.ucenter.constant.QrCodeFilePath;
import com.fdkankan.ucenter.entity.IncrementAutoOrder;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.util.DateUserUtil;
import com.fdkankan.ucenter.vo.response.AuthLicenseEntityVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;

@Component
public class TaskService {

    public static final Logger log = LoggerFactory.getLogger("timeLogger");

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private ISceneProService sceneProService;

    @Autowired
    private ISceneCleanService sceneCleanService;


    @Scheduled(cron = "${task.cron.del_qrCode:0 */10 * * * ?}")
    public void delLoginQrCode(){
        if("local".equals(NacosProperty.uploadType)){
            AuthLicenseUtil.checkAuthLicense();
            this.updateSceneViewCount();
            return;
        }
        try {
            long startTime = new Date().getTime();
            String qrCodePath = QrCodeFilePath.LOGIN_QR_CODE_PATH;
            String aliQrCodePath = QrCodeFilePath.ALI_QRCODE_FOLDER;
            String wxCodePath = QrCodeFilePath.WEIXIN_QRCODE_FOLDER;
            File file = new File(qrCodePath);
            File file2 = new File(wxCodePath);
            File file3 = new File(aliQrCodePath);
            File[] files = file.listFiles();
            File[] files1 = file2.listFiles();
            File[] files2 = file3.listFiles();
            delFile(files);
            delFile(files1);
            delFile(files2);
            //log.info("delLoginQrCode:结束定时清理本地登录二维码:耗时{}秒",(new Date().getTime() - startTime)/1000 );
            this.updateSceneViewCount();
        }catch (Exception e){
            log.error("delLoginQrCode错误",e);
        }

    }




    private void updateSceneViewCount() {
        String redisKey = RedisKeyUtil.V4_SCENE_VISIT_CNT;
        Map<String,String> hmget = redisUtil.hmget(redisKey);
        for (String key : hmget.keySet()) {
            //log.info("定时更新场景viewCount--num:{},viewCount:{}",key,hmget.get(key));
            sceneProService.updateDbViewCount(key,hmget.get(key));
        }
    }

    private void delFile(File[] files){
        if(Objects.isNull(files) || files.length == 0){
            return;
        }
        for (File f : files) {
            if(files == null && files.length >0){
                return;
            }
            if(f==null || !f.getName().contains(".")){
                continue;
            }
            String name = f.getName().substring(0,f.getName().lastIndexOf("."));
            if(!redisUtil.hasKey(RedisKeyUtil.QRCODE + name)){
                //log.info("删除文件:{}",f.getPath());
                FileUtils.delFile(f.getPath());
            }
        }
    }

    @Autowired
    IUserIncrementService userIncrementService;

    @Scheduled(cron = "${task.cron.increment_sendMsg:0 0 12 * * ?}")
    public void job11() {
        if("local".equals(NacosProperty.uploadType)){
            return;
        }
        log.info("每天12:00开始执行定时任务：短信提醒增值权益准备到期");
        try {
            userIncrementService.incrementExpireSendSms();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }



    @Scheduled(cron = "${task.cron.update_order_status:0 0 0 * * ?}")
    public void checkIncrementExpire() {
        if("local".equals(NacosProperty.uploadType)){
            return;
        }
        log.info("每天00:00开始执行定时任务：增值权益到期检查");
        try {
            userIncrementService.incrementExpire();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    @Autowired
    IOrderService orderService;

    @Scheduled(cron = "${task.cron.update_order_status:0 0 1 * * ?}")
    public void updateOrderStatus() {
        if("local".equals(NacosProperty.uploadType)){
            return;
        }
        log.info("每天01:00开始执行定时任务：更新收货状态");
        try {
            //更新收货状态，发货后15天，默认用户已经收到货物
            orderService.autoUpdateOrderStatus();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    @Autowired
    ISceneStatisticsService sceneStatisticsService;
    @Scheduled(cron = "${task.cron.add_baidu_data:0 0 2 * * ?}")
    public void addBaiduData() {
        if("local".equals(NacosProperty.uploadType)){
            return;
        }
        log.info("每天02:00开始执行定时任务：获取百度统计的数据入库");
        try {
            String dateStr = DateUtil.date2String(DateUtil.daysCalculate(new Date(), -1), DateUtil.YYYYMMDD_DATA_FORMAT);
            Map<String, Map<String, Double>> map = StatisticsUtil.findStatisticsData(dateStr);
            sceneStatisticsService.addData(map, dateStr);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 清理场景nas资源
     * 执行时间：每天凌晨
     * 删除条件：场景计算时间大于6个月且未删除过资源
     */
    @Scheduled(cron = "${task.cron.scene_clean_resource:0 0 0/2 * * ?}")
    public void sceneCleanResource() {
        log.info("每天凌晨12:00开始执行定时任务：清除场景计算目录");
        try {
            sceneCleanService.sceneCleanResource();
        } catch (Exception e) {
            log.error("清除失败", e);
            log.error(e.getMessage());
        }
        log.info("清除场景计算目录任务执行完成");
    }

    /**
     * 清除订阅信息
     */
    @Autowired
    IIncrementAutoOrderService incrementAutoOrderService;

    @Scheduled(cron = "${task.cron.del_subscription:0 */1 * * * ?}")
    public void delSub(){
        LambdaQueryWrapper<IncrementAutoOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(IncrementAutoOrder::getSubscriptionId);
        List<IncrementAutoOrder> list = incrementAutoOrderService.list(wrapper);
        List<Integer> delList = new ArrayList<>();
        for (IncrementAutoOrder autoOrder : list) {
            Long time = autoOrder.getCreateTime().getTime() + 1000 * 60 * 10;
            if(new Date().getTime() > time){
                delList.add(autoOrder.getId());
            }
        }
        if(delList.size() >0){
            log.info("超过十分钟未付款删除订阅信息：{}",delList.size());
            incrementAutoOrderService.removeByIds(delList);
        }
    }
}
