package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysTaskCycleService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysTaskPlanService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysTaskService;
import cn.estsh.i3plus.icloud.wms.sdk.IWmsScheduleJobCloud;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysRefTaskCyclePlan;
import cn.estsh.i3plus.pojo.platform.bean.SysTask;
import cn.estsh.i3plus.pojo.platform.bean.SysTaskCycle;
import cn.estsh.i3plus.pojo.platform.bean.SysTaskPlan;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.quartz.IQuartzJobService;
import cn.estsh.impp.framework.boot.quartz.ScheduleTool;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description : 任务周期管理服务
 * @Reference   :
 * @Author      : yunhao
 * @Date        : 2018-12-27 15:54
 * @Modify      :
 **/
@RestController
@Api(description = "任务周期")
@RequestMapping(PlatformConstWords.BASE_URL +"/task-cycle")
public class SysTaskCycleController extends CoreBaseController{

    public static final Logger LOGGER = LoggerFactory.getLogger(SysTaskCycleController.class);

    @Autowired
    private ISysTaskCycleService sysTaskCycleService;

    @Autowired
    private ISysTaskPlanService sysTaskPlanService;

    @Autowired
    private ISysTaskService sysTaskService;

    /************ 微服定时任务 *********/
    @Autowired
    private ScheduleTool scheduleTool;

    @Autowired
    private IWmsScheduleJobCloud wmsScheduleJobCloud;

    /**
     * 根据来源切换定时任务服务
     * @param source CommonEnumUtil.SOFT_TYPE
     * @return
     */
    private IQuartzJobService getJobService(int source){
        IQuartzJobService quartzJobService = scheduleTool;

        if(source == CommonEnumUtil.SOFT_TYPE.CORE.getValue()){
            //平台定时任务
            quartzJobService = scheduleTool;
        }else if(source == CommonEnumUtil.SOFT_TYPE.WMS.getValue()){
            quartzJobService = wmsScheduleJobCloud;
        }
        return quartzJobService;
    }

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增任务周期", notes = "任务周期")
    public ResultBean insertSysTaskCycle(SysTaskCycle sysTaskCycle) {
        try {
            // 数据校验
            ValidatorBean.beginValid(sysTaskCycle)
                    .notNull("name", sysTaskCycle.getName())
                    .notNull("taskCycleExps", sysTaskCycle.getTaskCycleExps());

            sysTaskCycleService.insertSysTaskCycle(sysTaskCycle);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改任务周期", notes = "修改任务周期")
    public ResultBean updateSysTaskCycle(SysTaskCycle sysTaskCycle) {
        try {
            // 数据校验
            ValidatorBean.beginValid(sysTaskCycle)
                    .notNull("id", sysTaskCycle.getId())
                    .notNull("name", sysTaskCycle.getName())
                    .notNull("taskCycleExps", sysTaskCycle.getTaskCycleExps());

            sysTaskCycleService.updateSysTaskCycle(sysTaskCycle);

            // 查询关联任务计划信息，并进行修改
            List<SysRefTaskCyclePlan> taskCyclePlans = sysTaskCycleService.findRefTaskCyclePlanByCycleId(sysTaskCycle.getId());
            SysTaskPlan sysTaskPlan;
            SysTask sysTask;
            for (SysRefTaskCyclePlan item: taskCyclePlans) {
                sysTaskPlan = sysTaskPlanService.getSysTaskPlanByNameAndGroup(item.getTaskPlanName(),item.getTaskPlanGroupName());
                sysTask = sysTaskService.getSysTaskById(sysTaskPlan.getTaskId());

                sysTaskPlan.setTaskCycleNameRdd(sysTaskCycle.getName());
                sysTaskPlan.setTaskCycleExpsRdd(sysTaskCycle.getTaskCycleExps());
                sysTaskPlan.setTaskCycleStartDateTimeRdd(sysTaskCycle.getTaskCycleStartDatetime());
                sysTaskPlan.setTaskCycleEndDateTimeRdd(sysTaskCycle.getTaskCycleEndDatetime());

                // 更新关联模块的定时任务
                getJobService(sysTaskPlan.getTaskSoftTypeRdd()).editTask(sysTask.getTaskPackage(),sysTask.getTaskClass(),sysTaskPlan.getName()
                        ,sysTaskPlan.getGroupName(),sysTaskCycle.getTaskCycleExps(),sysTaskPlan.getTaskPlanDescription());
            }
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ApiOperation(value = "删除任务周期", notes = "删除任务周期")
    public ResultBean deleteSysTaskCycle(@PathVariable("id") String idStr) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(idStr, "时间表达式id 不能为空");
            if(sysTaskCycleService.getSysTaskCycleById(Long.parseLong(idStr)) == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("任务周期不存在")
                        .setErrorSolution("请重新选择")
                        .build();
            }

            sysTaskCycleService.deleteSysTaskCycleById(Long.parseLong(idStr));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询所有任务周期信息", notes = "查询所有任务周期信息")
    public ResultBean findSysTaskCycle() {
        try {
            List<SysTaskCycle> list = sysTaskCycleService.listSysTaskCycle();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "查询任务周期", notes = "查询根据ID查询任务周期")
    public ResultBean getSysTaskCycleById(@PathVariable("id") String id) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "定时任务id 不能为空");

            SysTaskCycle sysTaskCycle = sysTaskCycleService.getSysTaskCycleById(Long.parseLong(id));
            if (sysTaskCycle != null) {
                return ResultBean.success("操作成功").setResultObject(sysTaskCycle).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/query")
    @ApiOperation(value = "任务周期查询，分页，排序",notes = "任务周期查询，分页，排序")
    public ResultBean querySysTaskCycleByPager(SysTaskCycle taskTimeExpression, Pager pager){
        try {
            ListPager listPager = sysTaskCycleService.querySysTaskCycleByPager(taskTimeExpression,pager);
            return  ResultBean.success("操作成功").setListPager(listPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping("/batch-delete")
    @ApiOperation(value = "根据id批量删除任务周期",notes = "根据id批量删除任务周期")
    public ResultBean deleteSysTaskTimeExpressionByIds(String[] idsStr){
        try{
            if(idsStr.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }

            sysTaskCycleService.deleteSysTaskCycleByIds(StringTool.getArrayLong(idsStr));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
