package com.yonge.cooleshow.admin.task;

import com.alibaba.fastjson.JSONObject;
import com.microsvc.toolkit.common.tools.ThreadPool;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.utils.date.DateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: liweifan
 * @Data: 2022/3/28 15:50
 */
@RestController
@RequestMapping("${app-config.url.admin:}/task")
@ApiIgnore
public class TaskController extends BaseController {
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private UserBindingTeacherService userBindingTeacherService;
    @Autowired
    private CourseScheduleService courseScheduleService;
    @Autowired
    private UserAccountRecordService userAccountRecordService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private PlatformCashAccountRecordService platformCashAccountRecordService;
    @Autowired
    private ActivityPlanService activityPlanService;
    @Autowired
    private ActivityPlanEvaluationService activityPlanEvaluationService;

    @Value("${app.blacklist:}")
    private String blacklistFilePath;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private MusicAlbumService musicAlbumService;

    @Autowired
    private TeacherStyleVideoService teacherStyleVideoService;

    @Autowired
    private CustomerServiceBatchSendingService customerServiceBatchSendingService;

    @Autowired
    private UserPaymentCoreService userPaymentCoreService;

    @Autowired
    private LiveRoomService liveRoomService;

    @Autowired
    private TenantUnbindRecordService tenantUnbindRecordService;

    @Autowired
    private ImGroupService imGroupService;

    @Autowired
    private UserTenantAlbumRecordService userTenantAlbumRecordService;

    @Autowired
    private UserMusicService userMusicService;
    /***
     * 轮询用户订单
     * @author liweifan
     * @updateTime 2022/4/29 19:12
     * @return: com.yonge.cooleshow.common.entity.HttpResponseResult
     */
    @GetMapping("/pollingOrder")
    public HttpResponseResult pollingOrder() {
        userOrderService.pollingOrder();
        userPaymentCoreService.scanPaymentTimeoutOrderRecord();
        return succeed();
    }

    /***
     * 一日一次，凌晨执行
     * @author liweifan
     * @updateTime 2022/4/29 19:12
     * @return: com.yonge.cooleshow.common.entity.HttpResponseResult<java.lang.Boolean>
     */
    @GetMapping("/daysTask")
    public HttpResponseResult<Boolean> daysTask() {
        //超过天数无琴房课的解除绑定关系
        userBindingTeacherService.unbindTask();
        //平台老师结算
        platformCashAccountRecordService.updateWaitRecord();
        return succeed(true);
    }

    // 老师作业布置
    @PostMapping(value = "/teacherSend")
    public HttpResponseResult<Object> sendTodayNotRepliedAndNotDecorateHomework() {
        courseScheduleService.sendTodayNotRepliedAndNotDecorateHomework();
        return HttpResponseResult.succeed();
    }

    //老师课酬
    @PostMapping(value = "/teacherEarning")
    public HttpResponseResult<Object> sendTeacherEarning() {
        userAccountRecordService.sendTeacherEarning();
        return HttpResponseResult.succeed();
    }

    //刷新黑名单
    @PostMapping(value = "/refreshBlackList")
    public HttpResponseResult refreshBlackList() {

        if (StringUtils.isEmpty(blacklistFilePath)) {
            blacklistFilePath = SysConfigConstant.BLACK_LIST_FILE_PATH;
        }

        RBucket<Long> bucket = redissonClient.getBucket(SysConfigConstant.BLACK_LIST_UPDATE_TIME);
        File file = new File(blacklistFilePath);
        bucket.set(file.lastModified());
        return HttpResponseResult.succeed();
    }

    //营销活动
    @PostMapping(value = "/activityState")
    public HttpResponseResult<Object> activityState() {
        activityPlanService.activityState();
        return HttpResponseResult.succeed();
    }

    //活动中定时轮询
    @PostMapping(value = "/activityIng")
    public HttpResponseResult<Object> activityIng() {
        activityPlanService.activityIng();
        return HttpResponseResult.succeed();
    }

    /**
     * 活动测试
     * @param activityId 活动ID
     * @return HttpResponseResult<Object>
     */
    @GetMapping("/test")
    public HttpResponseResult<Object> test(@RequestParam("activityId") Long activityId) {

        activityPlanEvaluationService.successActivity(activityId);
        return HttpResponseResult.succeed();
    }


    /**
     * 每日增加收藏/热度人数
     */
    @GetMapping("/virtualNumber")
    public HttpResponseResult<Object> virtualNumber() {

        // 曲目
        musicSheetService.setVirtualNumber();
        // 专辑
        musicAlbumService.setVirtualNumber();
        // 视频课 暂时不做课程数据
        // videoLessonGroupService.setVirtualNumber();
        // 个人风采
        teacherStyleVideoService.setVirtualNumber();

        return HttpResponseResult.succeed();
    }

    /**
     * 群发消息
     */
    @GetMapping("/batchSending")
    public HttpResponseResult<Object> batchSending() {

        // 群发消息定时
        customerServiceBatchSendingService.scheduleSendMessage();

        return HttpResponseResult.succeed();
    }


    /**
     * 直播间销毁
     */
    @GetMapping("/destroyLiveRoom")
    public HttpResponseResult<Object> destroyLiveRoom() {

        // 群发消息定时
        liveRoomService.destroyLiveRoom();

        return HttpResponseResult.succeed();
    }


    @GetMapping("/rongyunImport")
    public void rongyunImport() throws Exception {
        String currentDate = DateUtil.format(DateUtil.addHours(new Date(),-2), DateUtil.YEAR_MONTH_DAY_HOUR);
        Object o = imGroupService.historyGet(currentDate);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(o));
        if (jsonObject.get("code").equals(200)) {
            String url = jsonObject.getString("url");
            if (!StringUtils.isEmpty(url)) {
                File file = new File(FileUtils.getTempDirectoryPath() + url.substring(url.lastIndexOf("/")));
                URL url1 = new URL(url);
                FileUtils.copyURLToFile(url1, file);
                imGroupService.saveImHistoryMessage(new File(file.getAbsolutePath()));
            }

        }
    }
    /**
     * 定时发送平台审核短信 下午5点
     */
    @GetMapping("/sendPlatformAuditMessage")
    public HttpResponseResult<Object> sendPlatformAuditMessage() {

        // 群发消息定时
        tenantUnbindRecordService.sendPlatformAuditMessage();

        return HttpResponseResult.succeed();
    }


    /**
     * 机构学生训练教材过期
     */
    @GetMapping("/sendTenantAlbumMessage")
    public HttpResponseResult<Object> sendTenantAlbumMessage() {

        // 群发消息定时
        userTenantAlbumRecordService.sendTenantAlbumMessage();

        return HttpResponseResult.succeed();
    }


    /**
     * 作品过期设置
     */
    @GetMapping("/workOverdue")
    public void workOverdue(){
        userMusicService.workOverdue();
    }
}
