package com.rf.psychological.plan.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.plan.dao.model.TestPlanUserEntity;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.plan.dao.model.HisTestPlanEntry;
import com.rf.psychological.plan.dao.model.PlanMessageEntity;
import com.rf.psychological.plan.dao.model.TestPlanEntity;
import com.rf.psychological.plan.service.PlanMessageService;
import com.rf.psychological.plan.service.TestPlanService;
import com.rf.psychological.plan.service.HisTestPlanService;
import com.rf.psychological.plan.service.TestPlanUserService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.threadpool.ThreadPool;
import com.rf.psychological.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:zzf
 * @Date:2022/7/1:16:30
 * @Description:测试计划相关的定时任务信息
 */
@Configuration
@EnableScheduling
@Slf4j
public class StaticScheduleTask {

    @Autowired
    private UserService userService;
    @Autowired
    private PlanMessageService planMessageService;

    @Autowired
    private TestPlanService planService;

    @Autowired
    private TestPlanUserService planUserService;

    @Autowired
    private HisTestPlanService hisTestPlanService;

    //@Scheduled(initialDelay = 60000,fixedDelay = 60000)
    @Profile({"dev","test","prod"})
    private void sendMessage (){
        //log.info(new Date()+"执行静态任务----发送测试计划短信提醒");
        List<PlanMessageEntity> planMessageEntityList = this.planMessageService.findToSendMessage();
        JSONArray jsonArray = new JSONArray();
        if(planMessageEntityList != null && planMessageEntityList.size() > 0){
            planMessageEntityList.forEach(planMessageEntity -> {
                planMessageEntity.setStatus(Constant.MAGIC_NUM_1);
                this.planMessageService.save(planMessageEntity);
                TestPlanEntity planEntity = this.planService.findById(planMessageEntity.getPlanId());
                if(planEntity != null &&(planEntity.getStatus() == Constant.TEST_PLAN_STATUS_RUNNING|| planEntity.getStatus() == Constant.TEST_PLAN_STATUS_UNSTART)){
                    //用户信息
                    List<String> userIdList = this.planUserService.findUserIdByPlanId(planEntity.getId());
                    List<UserEntity> userEntityList = this.userService.getUserByIds(userIdList);
                    if(userEntityList != null && userEntityList.size() > 0){
                        userEntityList.forEach(userEntity -> {
                            if(userEntity.getModelPhone()==null && userEntity.getModelPhone().trim().length()<=0)return;
                            if(userEntity.getModelPhone().equals(Constant.MAGIC_NUM_0)||userEntity.getModelPhone().equals(Constant.MAGIC_NUM_1)) return;
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("userName",userEntity.getPetName());
                            jsonObject.put("beginTime",planEntity.getTestBeginTime());
                            jsonObject.put("endTime",planEntity.getTestEndTime());
                            jsonObject.put("phone",userEntity.getModelPhone());
                            jsonArray.add(jsonObject);
                        });
                    }
                }
            });
        }
        if(jsonArray.size()>0){
            ThreadPool.run(Math.min(jsonArray.size(), 2), jsonArray.size(), jsonArray);
        }
    }
    /**
     * 修改未修改的状态：
     * 到达开始时间未开始的测试计划
     * 到达结束时间未结束的测试计划
     * 20230918更新，测试计划下所有用户都完成测试任务，视为完成状态
     */
    //@Scheduled(initialDelay = 60000,fixedDelay = 60000)
    public void updatePlanStatus(){
        //log.info(new Date()+"执行静态任务修改测试计划状态");
        List<TestPlanEntity> planEntityList = this.planService.findPlan();
        //更新
        List<TestPlanEntity> updateList = new ArrayList<>();
        //从测试计划表删除，插入历史计划表
        List<TestPlanEntity> deleteEntryList = new ArrayList<>();
        List<HisTestPlanEntry> hisTestPlanEntryList = new ArrayList<>();
        if(planEntityList != null && planEntityList.size()>0){
            planEntityList.forEach(testPlanEntity -> {
                if (testPlanEntity.getStatus() == Constant.TEST_PLAN_STATUS_RUNNING && testPlanEntity.getTestEndTime().before(new Date())) {
                    deleteEntryList.add(testPlanEntity);
                    testPlanEntity.setStatus(Constant.TEST_PLAN_STATUS_END);
                    HisTestPlanEntry hisTestPlanEntry = new HisTestPlanEntry(testPlanEntity);
                    hisTestPlanEntryList.add(hisTestPlanEntry);
                }else if(testPlanEntity.getStatus()==Constant.TEST_PLAN_STATUS_UNSTART && testPlanEntity.getTestBeginTime().before(new Date())){
                    testPlanEntity.setStatus(Constant.TEST_PLAN_STATUS_RUNNING);
                    updateList.add(testPlanEntity);
                }
            });
            if(updateList.size() >0){
                this.planService.saveInBatch(updateList);
            }
            if(deleteEntryList.size()>0){
                this.planService.deleteInBatch(deleteEntryList);
            }
            if(hisTestPlanEntryList.size()>0){
                this.hisTestPlanService.saveInBatch(hisTestPlanEntryList);
            }
        }
    }

    /**
     * 若测试计划下所有用户均已完成测试任务，测试计划标记为完成状态
     */
    //@Scheduled(initialDelay = 15000,fixedDelay = 10000)
    public void completeTestPlan(){
        //log.info(new Date()+"修改所有用户已完成所有任务的测试计划状态");
        List<TestPlanEntity> planEntityList = this.planService.findall();
        //更新
        List<TestPlanEntity> updateList = new ArrayList<>();
        //从测试计划表删除，插入历史计划表
        List<TestPlanEntity> deleteEntryList = new ArrayList<>();
        List<HisTestPlanEntry> hisTestPlanEntryList = new ArrayList<>();
        if(planEntityList != null && planEntityList.size()>0){
            planEntityList.forEach(testPlanEntity -> {
                if (testPlanEntity.getStatus() == Constant.TEST_PLAN_STATUS_RUNNING ) {
                    List<TestPlanUserEntity> planUserEntityList =this.planUserService.findUncompletedUser(testPlanEntity.getId());
                    if(planUserEntityList == null || planUserEntityList.size()==0){
                        deleteEntryList.add(testPlanEntity);
                        testPlanEntity.setStatus(Constant.TEST_PLAN_STATUS_END);
                        HisTestPlanEntry hisTestPlanEntry = new HisTestPlanEntry(testPlanEntity);
                        hisTestPlanEntryList.add(hisTestPlanEntry);
                    }
                }
            });
            if(deleteEntryList.size()>0){
                this.planService.deleteInBatch(deleteEntryList);
            }
            if(hisTestPlanEntryList.size()>0){
                this.hisTestPlanService.saveInBatch(hisTestPlanEntryList);
            }
        }
    }
}
