package com.yihu.hos.datacollect.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.yihu.hos.common.Services;
import com.yihu.hos.core.datatype.CollectionUtil;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.datacollect.model.RsJobConfig;
import com.yihu.hos.datacollect.service.DatacollectManager;
import com.yihu.hos.resource.service.StdService;
import com.yihu.hos.standard.service.adapter.AdapterSchemeService;
import com.yihu.hos.system.service.DatasourceManager;
import com.yihu.hos.web.framework.constant.DateConvert;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据采集配置页面
 * Created by hzp on 2015/8/12.
 */
@RequestMapping("/datacollect")
@Controller("dataCollectController")
public class DataCollectController extends BaseController {

    @Resource(name = Services.Datacollect)
    DatacollectManager datacollect;

    @Resource(name = StdService.BEAN_ID)
    StdService stdService;

    @Resource(name = Services.Datasource)
    DatasourceManager datasource;

    @Resource(name = AdapterSchemeService.BEAN_ID)
    private AdapterSchemeService adapterSchemeService;

    @Autowired
    private ObjectMapper objectMapper;


    /****************************
     * 任务管理
     ************************************************/
    /*
    任务配置
     */
    @RequestMapping("configJob")
    public String configJob(Model model) {
        model.addAttribute("contentPage", "/datacollect/configJob");
        return "partView";
    }

    /*
    任务新增/编辑
     */
    @RequestMapping("editorJob")
    public String editorJob(Model model, String jobId) {
        try {
            //是否编辑
            if (jobId != null && jobId.length() > 0) {
                //获取任务信息
                RsJobConfig job = datacollect.getJobById(jobId);
                model.addAttribute("model", job);
                //String cron = datacollect.getCronByJobId(jobId);
                //model.addAttribute("cronExpression", cron);
            }

            //获取方案列表
            List data = stdService.getSchemeVersion();
            String jsonlist = objectMapper.writeValueAsString(data);
            ArrayNode jsonArray = objectMapper.readValue(jsonlist, ArrayNode.class);
            model.addAttribute("schemeList", "{\"detailModelList\":" + (CollectionUtil.isEmpty(data) ? "[]" : jsonArray) + "}");

            model.addAttribute("contentPage", "/datacollect/editorJob");
            return "pageView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "/datacollect/editorJob");
            return "pageView";
        }
    }

    /*
    获取任务列表
    */
    @RequestMapping("getJob")
    @ResponseBody
    public Result getJob(String name, int page, int rows) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            return datacollect.getJobList(map, page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    @RequestMapping("compareServeTime")
    @ResponseBody
    public Result getJob(String time) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (df.parse(time).before(new Date())) {

                return Result.success("beforeServeTime");
            } else
                return Result.error("afterServeTime");
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 根据适配方案获取数据集列表
     */
    @RequestMapping("getSchemeDataset")
    @ResponseBody
    public Result getSchemeDataset(String schemeId, String schemeVersion, String jobId) {
        try {
            return datacollect.getSchemeDataset(schemeId, schemeVersion, jobId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 根据适配方案+数据集获取字段列表
     */
    @RequestMapping("getSchemeDatasetCol")
    @ResponseBody
    public Result getSchemeDatasetCol(String schemeId, String schemeVersion, String datasetId) {
        try {
            return datacollect.getSchemeDatasetCol(schemeId, schemeVersion, datasetId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /*
       新增任务
    */
    @RequestMapping("addJob")
    @ResponseBody
    public Result addJob(HttpServletRequest request) {
        try {
            String cron = request.getParameter("cronExpression");
            String jobDataset = request.getParameter("jobDataset");
            RsJobConfig obj = new RsJobConfig();
            BeanUtils.populate(obj, request.getParameterMap());
            obj.setValid("1");
            obj.setJobCron(cron);
            String time = request.getParameter("jobNextTime");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (df.parse(time).before(new Date())) {
                return Result.error("任务开始时间不能小于当前时间");
            }

            return datacollect.addJob(obj, cron, jobDataset);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("新增任务失败！");
        }
    }

    /*
       修改任务
    */
    @RequestMapping("updateJob")
    @ResponseBody
    public Result updateJob(HttpServletRequest request) {

        try {
            String cron = request.getParameter("cronExpression");
            String jobDataset = request.getParameter("jobDataset");
            RsJobConfig obj = new RsJobConfig();
            obj.setJobCron(cron);
//            ConvertUtils.register(new DateLocaleConverter(), Date.class);
            BeanUtils.populate(obj, request.getParameterMap());
            String time = request.getParameter("jobNextTime");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (df.parse(time).before(new Date())) {
                return Result.error("任务开始时间不能小于当前时间");
            }

            String delayTime = request.getParameter("delayTime");//延迟时间
            String startTime = request.getParameter("repeatStartTime");
            String endTime = request.getParameter("repeatEndTime");

            if ("1".equals(obj.getJobType()) && !StringUtil.isBlank(startTime)) {//开时时间为空则为采集
                if (StringUtil.isBlank(endTime)) {
                    endTime = DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
                }

                Date beginDate = DateUtil.parseDate(startTime, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
                Date endDate = DateUtil.parseDate(endTime, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
                Calendar   calendar   =   new   GregorianCalendar();
                calendar.setTime(beginDate);
                calendar.add(calendar.DATE, Integer.valueOf(delayTime));//把日期往后增加一天.整数往后推,负数往前移动
                beginDate=calendar.getTime();
                if (beginDate.after(endDate)) {
                    return Result.error("任务开始时间加延迟时间不能大于结束时间");
                }
            }

            return datacollect.updateJob(obj, cron, jobDataset);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("修改任务失败！");
        }
    }

    /*
      修改任务状态
   */
    @RequestMapping("validJob")
    @ResponseBody
    public Result validJob(String jobId, String valid) {
        try {
            return datacollect.validJob(jobId, valid);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /*
      删除任务
   */
    @RequestMapping("deleteJob")
    @ResponseBody
    public Result deleteJob(String jobId) {
        try {
            return datacollect.deleteJob(jobId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 获取任务信息
     *
     * @return
     */
    @RequestMapping("getJobInfo")
    @ResponseBody
    public Result getJobInfo(String jobId) {
        try {
            RsJobConfig job = datacollect.getJobById(jobId);
            if (job != null) {
                ActionResult re = new ActionResult(true, "");
                re.setData(job.getValid());
                return re;
            } else {
                return new ActionResult(false, "非法操作！");
            }
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 根据任务Id获取相关数据集下拉数据
     *
     * @return
     */
    @RequestMapping("getJobDatasetByJobId")
    @ResponseBody
    public Result getJobDatasetByJobId(String jobId) {
        try {
            return datacollect.getJobDatasetByJobId(jobId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /*************************
     * 数据集--数据源管理
     ******************************************/
    /*
    数据集配置
     */
    @RequestMapping("configDataset")
    public String configDataset(Model model) {

        try {
            model.addAttribute("stdVersion", "569e19522e3d");

            //获取数据源数据
            model.addAttribute("datasourceList", datasource.getDatasourceByOrg("").toJson());

            model.addAttribute("contentPage", "/datacollect/configDataset");
            return "partView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "error");
            return "partView";
        }
    }

    /**
     * 数据集数据源管理列表（包含全部数据集）
     *
     * @return
     */
    @RequestMapping("getDatasetSource")
    @ResponseBody
    public Result getDatasetSource(String stdVersion) {
        try {
            return datacollect.getDatasetSource(stdVersion);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 更新数据集数据源
     *
     * @return
     */
    @RequestMapping("saveDatasetSource")
    @ResponseBody
    public Result saveDatasetSource(String stdVersion, String json) {
        try {

            return datacollect.saveDatasetSource(json);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }


    /*************************** 任务执行 ************************************************/
    /**
     * 执行任务
     *
     * @return
     */
    @RequestMapping("executeJob")
    @ResponseBody
    public Result executeJob(String jobId) {
        try {
            //获取任务详细信息
            RsJobConfig job = datacollect.getJobById(jobId);
            String content = job.getJobContent();
            Class<?> classType = Class.forName(content);
            Method method = classType.getMethod("execute", new Class[]{String.class});
            method.invoke(classType.newInstance(), jobId);

            return Result.success("处理完成！");
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }


    /*
    任务补采界面
     */
    @RequestMapping("repeatDatacollect")
    public String repeatDatacollect(Model model, String jobId, String jobDatasetId, String jobStatus, String jobTimeFrom, String jobTimeTo) {
        try {

            model.addAttribute("jobId", jobId == null ? "" : jobId);
            model.addAttribute("jobDatasetId", jobDatasetId == null ? "" : jobDatasetId);
            model.addAttribute("jobStatus", jobStatus == null ? "" : jobStatus);
            if (jobTimeFrom != null && jobTimeFrom.length() > 0) {
                Date timeFrom = DateConvert.toDate(jobTimeFrom);
                model.addAttribute("jobTimeFrom", DateConvert.toString(timeFrom));
            } else {
                GregorianCalendar gc = new GregorianCalendar();
                gc.setTime(new Date());
                gc.add(5, -1);
                model.addAttribute("jobTimeFrom", DateConvert.toString(gc.getTime()));
            }
            if (jobTimeTo != null && jobTimeTo.length() > 0) {
                Date timeTo = DateConvert.toDate(jobTimeTo);
                model.addAttribute("jobTimeTo", DateConvert.toString(timeTo));
            } else {
                model.addAttribute("jobTimeTo", DateConvert.toString(new Date()));
            }
            model.addAttribute("contentPage", "/datacollect/repeatDatacollect");
            return "partView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "error");
            return "partView";
        }
    }

    /**
     * 任务详细日志列表
     *
     * @return
     */
    @RequestMapping("getJobLogDetail")
    @ResponseBody
    public Result getJobLogDetail(String jobId, String jobDatasetId, String jobStatus, String jobTimeFrom, String jobTimeTo, int page, int rows) {
        try {
            Map<String, Object> conditionMap = new HashMap<String, Object>();
            conditionMap.put("jobId", jobId);
            conditionMap.put("jobDatasetId", jobDatasetId);
            conditionMap.put("jobStatus", jobStatus);
            conditionMap.put("jobTimeFrom", jobTimeFrom);
            conditionMap.put("jobTimeTo", jobTimeTo);
            return datacollect.getJobLogDetail(conditionMap, page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 补采数据
     *
     * @return
     */
    @RequestMapping("repeat")
    @ResponseBody
    public Result repeat(String ids) {
        return Result.error("非法操作！");
    }

    /*************************** 任务跟踪 ***********************************/
    /**
     * 任务跟踪界面
     *
     * @return
     */
    @RequestMapping("trackJob")
    public String trackJob(Model model, String jobId) {
        try {
            model.addAttribute("contentPage", "/datacollect/trackJob");
            return "pageView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "error");
            return "partView";
        }
    }

    /**
     * 任务日志列表
     *
     * @return
     */
    @RequestMapping("getJobLog")
    @ResponseBody
    public Result getJobLog(String jobId, int page, int rows) {
        try {
            Map<String, Object> conditionMap = new HashMap<String, Object>();
            conditionMap.put("jobId", jobId);
            return datacollect.getJobLog(conditionMap, page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 任务详细根据数据集分组
     *
     * @return
     */
    @RequestMapping("getJobLogDataset")
    @ResponseBody
    public Result getJobLogDataset(String logId) {
        try {
            return datacollect.getJobLogDataset(logId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
}
