/**
 * 文件：TaskController.java
 * 版本：1.0.0
 * 日期：
 * Copyright &reg;
 * All right reserved.
 */
package com.mortals.xhx.base.system.task.web;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.task.model.TaskEntity;
import com.mortals.xhx.base.system.task.service.TaskService;
import com.mortals.xhx.common.code.DataSatusEnum;
import com.mortals.xhx.common.code.TaskExcuteStatusEnum;
import com.mortals.xhx.common.code.TaskExcuteStrategyEnum;
import com.mortals.xhx.common.code.TaskInterimExcuteStatusEnum;

/**
 * <p>Title: 任务信息</p>
 * <p>Description: TaskController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("task")
public class TaskController extends BaseCRUDJsonMappingController<TaskService, TaskForm, TaskEntity, Long> {

    public TaskController() {
        super.setFormClass(TaskForm.class);
        super.setModuleDesc("任务信息");
    }


    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, TaskForm form,
                        Map<String, Object> model, Context context) {
        Map<String, Object> status = new HashMap<String, Object>();
        status.put("status", TaskExcuteStatusEnum.getEnumMap());
        status.put("excuteStrategy", TaskExcuteStrategyEnum.getEnumMap());
        status.put("interimExcuteStatus", TaskInterimExcuteStatusEnum.getEnumMap());
        Map<String, ITaskExcuteService> serviceMap = GlobalSysInfo.getBeansByType(ITaskExcuteService.class);
        Map<String, Object> serviceList = new HashMap<String, Object>();
        if (serviceMap != null) {
            try {
                serviceMap.forEach((k, v) -> {
                    if (null != v) {
                        serviceList.put(k, k);
                    }
                });
            } catch (Exception ex) {
                log.error("", ex);
            }
        }
        model.put("excuteService", serviceList);
        model.put(KEY_RESULT_DICT, status);
        super.init(request, response, form, model, context);
    }

    /**
     * @param request
     * @param response
     * @param form
     * @param model
     * @param context
     * @throws AppException
     * @Description: TODO
     */

    @Override
    protected void saveBefore(HttpServletRequest request, HttpServletResponse response, TaskForm form,
                              Map<String, Object> model, Context context) throws AppException {
        if (null == form.getEntity().getExcuteService()) {

        }
//		TaskEntity condition = new TaskEntity();
//		condition.setExcuteService(form.getEntity().getExcuteService());
//		List<TaskEntity> datas = this.service.find(condition, context);
//		if (null != datas && datas.size() > 0) {
//			for (TaskEntity entity : datas) {
//				if (entity.getId().longValue() != form.getEntity().getId().longValue()) {
//					throw new AppException("任务已存在，请勿重复配置");
//				}
//			}
//		}
        super.saveBefore(request, response, form, model, context);
    }

    /**
     * 改变状态
     */
    @RequestMapping(value = "change/status")
    public String changeStatus(HttpServletRequest request, HttpServletResponse response, TaskForm form) {
        JSONObject ret = new JSONObject();
        Context context = getContext();
        try {
            TaskEntity entity = this.service.get(form.getEntity().getId(), context);// .doSubmitAudit(form.getEntity(),
            // context);
            if (null == entity) {
                throw new AppException("任务不存在!");
            }
            if (null == form.getEntity().getStatus()) {
                throw new AppException("任务状态不能为空!");
            }
            if (form.getEntity().getStatus() != DataSatusEnum.ENABLE.getValue()
                    && form.getEntity().getStatus() != DataSatusEnum.DISENABLE.getValue()) {
                throw new AppException("非法任务状态!");
            }
            String busiDesc = DataSatusEnum.getByValue(form.getEntity().getStatus()).getDesc();
            entity.setStatus(form.getEntity().getStatus());
            this.service.update(entity, context);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, busiDesc + "成功");
            recordSysLog(request, busiDesc + " 【成功】 [id:" + entity.getId() + "]");

        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return ret.toJSONString();
    }

}