package com.cftech.sys.controller;



import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.RamJob;
import com.cftech.accounts.model.SysJob;
import com.cftech.accounts.service.JobService;
import com.cftech.accounts.service.JobTask;
import com.cftech.base.codingrule.model.Codingrule;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.DateUtils;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;

/**
 * @author KangLiang Huang
 * <p>
 * 定时任务 controller
 */
@Controller
@RequestMapping("/a/job")
@Slf4j
public class JobController {

    @Autowired
    JobService jobService;

    @Autowired
    JobTask jobTask;

    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    JedisPool jedisPool;

    @GetMapping(value = "list")
    @RequiresPermissions("job:show")
    public String showUser(Model model)
    {
        return "/jobs/joblist";
    }

    @GetMapping(value = "listData")
    @ResponseBody
    @RequiresPermissions("job:show")
    public JSONObject showUser(SysJob job, int iDisplayStart, int iDisplayLength, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (com.cftech.core.util.StringUtils.isNotBlank(job.getJobName())) {
            conds.like("job_name", job.getJobName());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);
        List<SysJob> list = jobService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer userCounts = jobService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", userCounts);
        rtnJson.put("iTotalDisplayRecords", userCounts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    @RequiresPermissions("job:show")
    @GetMapping(value = "form")
    public String addJob(Model model, String id) {
        if (!org.springframework.util.StringUtils.isEmpty(id)) {
            SysJob eggs = jobService.fetchById(id);
            model.addAttribute("data", eggs);
        }
        return "/jobs/jobform";
    }


    @GetMapping(value = "ramJoblist")
    @RequiresPermissions("job:show")
    public String ramJoblist(Model model,HttpServletRequest request)
    {
        Long accountsId = UserUtils.getmpaccounts(request);
        Jedis jedis = jedisPool.getResource();
        JSONObject result = new JSONObject();
        JSONObject data =  new JSONObject();
        data.put("accountsId",accountsId);
        result.put("status","3");
        result.put("data",data);
        jedis.publish("job_listener",result.toJSONString());
        jedis.close();
        return "/jobs/ramjoblist";
    }

//    @GetMapping(value = "ramJoblistData")
//    @ResponseBody
//    @RequiresPermissions("job:show")
//    public JSONObject ramJoblistData(SysJob job,int iDisplayStart, int iDisplayLength, HttpServletRequest request) {
//        JSONObject rtnJson = new JSONObject();
//        Long accountsId = UserUtils.getmpaccounts(request);
//        Jedis jedis = jedisPool.getResource();
//        JSONObject result = new JSONObject();
//        JSONObject data =  new JSONObject();
//        data.put("accountsId",accountsId);
//        result.put("status","3");
//        result.put("data",data);
//        jedis.publish("job_listener",result.toJSONString());
//        jedis.close();
//        //使用REDIS 消息服务去查询数据
////        Conds conds = new Conds();
////        conds.equal("del_flag", Constants.DEL_FLAG_0);
////        Set<String> uuids = jobTask.getRAMJOBS();
////        Object [] objs = new Object[uuids.size()];
////        Iterator<String> itr =uuids.iterator();
////        int i=0;
////        while(itr.hasNext())
////        {
////            objs[i] = itr.next();
////            i++;
////        }
////        if(uuids.size()==0)
////        {
////            objs =  new Object[1];
////            objs[0] = '1';
////        }
////
////        conds.in("jobuid",objs);
////        Sort sort = new Sort("create_time", OrderType.DESC);
////        List<SysJob> list = jobService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
////        Integer userCounts = jobService.count(conds);
////        JSONObject rtnJson = new JSONObject();
////        rtnJson.put("iTotalRecords", userCounts);
////        rtnJson.put("iTotalDisplayRecords", userCounts);
////        rtnJson.put("aaData", list);
//        rtnJson.put("errorNo",0);
//        return rtnJson;
//    }

    @GetMapping(value = "ramJoblistData")
    @ResponseBody
    @RequiresPermissions("job:show")
    public JSONObject ramJoblistData(SysJob job, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        List<RamJob> ramJob = jobService.getRamJob();
        if(ramJob.size()>0)
        {
            RamJob rj = ramJob.get(0);
            rtnJson = JSONObject.parseObject(rj.getJobJSON());
//            rtnJson.put("iTotalRecords", userCounts);
//            rtnJson.put("iTotalDisplayRecords", userCounts);
//            rtnJson.put("aaData", list);
        }else
        {
            rtnJson.put("iTotalRecords", 0);
            rtnJson.put("iTotalDisplayRecords", 0);
            rtnJson.put("aaData", new ArrayList<RamJob>());
        }
        rtnJson.put("errorNo",0);
        return rtnJson;
    }


//    @RequiresPermissions("job:edit")
//    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
//    @ResponseBody
//    public JSONObject addJob(SysJob job,HttpServletRequest request) {
//        Long accountsId = UserUtils.getmpaccounts(request);
//        JSONObject j = new JSONObject();
//        job.setStatus("0");
//        job.setAccountsId(accountsId);
//        try {
//            jobService.save(job);
//        } catch (Exception e) {
//          log.error("保存定时任务失败",e);
//        }
//        return j;
//    }

    @RequiresPermissions("job:edit")
    @PostMapping(value = "formData")
    @ResponseBody
    public JSONObject updateJob(SysJob job,HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject j = new JSONObject();
        //查看是否是直接新增job
        if(job.getId()==null)
        {
            job.setStatus("0");
            job.setJobuid(UUID.randomUUID().toString());
            job.setAccountsId(accountsId);
            try {
                jobService.save(job);
                j.put("errorNo",2);
            } catch (Exception e) {
                j.put("errorNo",-1);
                j.put("errorMsg","保存定时任务失败");
                log.error("保存定时任务失败",e);
            }
        }else
        {
            if (jobTask.checkJob(job)) {
                j.put("errorNo",-1);
                j.put("errorMsg","已经启动任务无法更新,请停止后更新");
                return j;
            }
            try {
                jobService.update(job);
                j.put("errorNo",0);
            } catch (Exception e) {
                j.put("errorNo",-1);
                j.put("errorMsg","更新定时任务失败,任务ID："+job.getId());
                log.error("保存定时任务失败,任务ID："+job.getId(),e);
            }
        }
        return j;
    }


    @PostMapping(value = "delete")
    @ResponseBody
    @RequiresPermissions("job:edit")
    public JSONObject del(String id,HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject j = new JSONObject();
        if (StringUtils.isEmpty(id)) {
            j.put("errorNo",1);
            return j;
        }

        SysJob job = jobService.fetchById(id);
        if(job==null)
        {
            j.put("errorNo",-1);
            return j;
        }
//        boolean flag = jobTask.checkJob(job);
//        if (flag) {
//            j.put("errorNo",1);
//            j.put("errorMsg","任务正在进行中，请停止后进行删除！");
//                return j;
//        }
//        jobTask.remove(job);
//        jobService.delete(id);
        Jedis jedis = jedisPool.getResource();
        JSONObject result = new JSONObject();
        JSONObject data =  new JSONObject();
        data.put("uuid",job.getJobuid());
        data.put("accountsId",accountsId);
        result.put("status","0");
        result.put("data",data);
        jedis.publish("job_listener",result.toJSONString());
        jedis.close();
        j.put("errorNo",0);
        return j;
    }



    @PostMapping(value = "startJob")
    @ResponseBody
    @RequiresPermissions("job:edit")
    public JSONObject startJob(String id) {
        JSONObject j = new JSONObject();
        String msg = null;
        if (StringUtils.isEmpty(id)) {
            j.put("errorNo","1");
            return j;
        }
        SysJob job = jobService.fetchById(id);
        jobTask.startJob(job);
        job.setStatus("1");
        jobService.update(job);
        j.put("errorNo",0);
        return j;
    }

    @PostMapping(value = "endJob")
    @ResponseBody
    @RequiresPermissions("job:edit")
    public JSONObject endJob(String id) {
        JSONObject j = new JSONObject();
        String msg = null;
        if (StringUtils.isEmpty(id)) {
            j.put("errorNo",1);
            return j;
        }
        SysJob job = jobService.fetchById(id);
        jobTask.remove(job);
        job.setStatus("0");
        jobService.update(job);
        j.put("errorNo",0);
        return j;
    }

}
