package com.yeejoin.amos.fas.business.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyPlanService;
import com.yeejoin.amos.fas.business.vo.ContingencyPlanParamVo;
import com.yeejoin.amos.fas.business.vo.ContingencyPlanResponseVo;
import com.yeejoin.amos.fas.business.vo.PlanDetailVo;
import com.yeejoin.amos.fas.business.vo.Toke;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil2;
import com.yeejoin.amos.fas.core.util.ResponseModel;
import com.yeejoin.amos.fas.exception.YeeException;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api/contingencyPlan")
@Api(tags = "预案api")
public class ContingencyPlanController extends AbstractBaseController {

    @Autowired
    private IContingencyPlanService contingencyPlanService;

    /**
     * 创建数字预案
     */
    @Permission
    @ApiOperation(value = "创建数字预案", notes = "创建数字预案")
    @PostMapping(value = "", produces = "application/json;charset=UTF-8")
    public ResponseModel createPlan(@RequestBody PlanDetailVo planDetail) {
        if (null == planDetail) {
            return CommonResponseUtil2.failure("参数有误");
        }
        AgencyUserModel curUser = getUserInfo();
        planDetail.setCreator(curUser.getUserId());
        planDetail.setOrgCode(getOrgCode(getSelectedOrgInfo()));
        return CommonResponseUtil2.success(contingencyPlanService.createPlan(planDetail));
    }

    /**
     * 修改数字预案
     */
    @Permission
    @ApiOperation(value = "修改数字预案", notes = "修改数字预案")
    @PutMapping(value = "", produces = "application/json;charset=UTF-8")
    public ResponseModel editPlan(@RequestBody PlanDetailVo planDetail) {
        if (null == planDetail) {
            return CommonResponseUtil2.failure("参数有误");
        }
        AgencyUserModel curUser = getUserInfo();
        planDetail.setReviser(curUser.getUserId());
        planDetail.setUpdateTime(new Date());
        return CommonResponseUtil2.success(contingencyPlanService.editPlan(planDetail));
    }

    /**
     * 查看数字预案详情
     */
    @Permission
    @ApiOperation(value = "查看数字预案详情", notes = "查看数字预案详情")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public ResponseModel createPlan(@PathVariable(value = "id") Long id) {
        if (null == id) {
            return CommonResponseUtil2.failure("参数有误");
        }
        return CommonResponseUtil2.success(contingencyPlanService.detail(id));
    }

    /**
     * 数字预案分页查询
     */
    @Permission
    @ApiOperation(value = "数字预案分页查询", notes = "数字预案分页查询")
    @GetMapping(value = "/page", produces = "application/json;charset=UTF-8")
    public ResponseModel pageFilter(@RequestParam(value = "current") int current,
                                    @RequestParam(value = "planName", required = false) String planName,
                                    @RequestParam(value = "classifyId", required = false) Long classifyId,
                                    @RequestParam(value = "planRange", required = false) List<String> planRange,
                                    @RequestParam(value = "editOrgName", required = false) String editOrgName,
                                    @RequestParam(value = "implementationTimeLeft", required = false) Long implementationTimeLeftStamp,
                                    @RequestParam(value = "implementationTimeRight", required = false) Long implementationTimeRightStamp,
                                    @RequestParam(value = "size") int size) {
        if (current < 1 || size < 1) {
            throw new YeeException("分页参数有误");
        }
        Date implementationTimeLeft = implementationTimeLeftStamp == null ? null : new Date(implementationTimeLeftStamp);
        Date implementationTimeRight = implementationTimeRightStamp == null ? null : new Date(implementationTimeRightStamp);
        Page page = new Page(current, size);
        return CommonResponseUtil2.success(contingencyPlanService.pageFilter(page, planName, classifyId, planRange, editOrgName, implementationTimeLeft, implementationTimeRight));
    }

    /**
     * 启用预案
     */
    @Permission
    @ApiOperation(value = "启用预案", notes = "启用预案")
    @PutMapping(value = "/activate", produces = "application/json;charset=UTF-8")
    public ResponseModel activatePlan(@RequestBody List<Long> idList) {
        if (null == idList || idList.isEmpty()) {
            return CommonResponseUtil2.failure("参数有误");
        }
        return CommonResponseUtil2.success(contingencyPlanService.activatePlan(idList));
    }

    /**
     * 停用预案
     */
    @Permission
    @ApiOperation(value = "停用预案", notes = "停用预案")
    @PutMapping(value = "/deactivate", produces = "application/json;charset=UTF-8")
    public ResponseModel deactivatePlan(@RequestBody List<Long> idList) {
        if (null == idList || idList.isEmpty()) {
            return CommonResponseUtil2.failure("参数有误");
        }
        return CommonResponseUtil2.success(contingencyPlanService.deactivatePlan(idList));
    }


    /**
     * 删除预案
     */
    @Permission
    @ApiOperation(value = "删除预案", notes = "删除预案")
    @DeleteMapping(value = "/{ids}", produces = "application/json;charset=UTF-8")
    public ResponseModel deletePlan(@PathVariable(value = "ids") String idStr) {
        if (StringUtils.isBlank(idStr)) {
            return CommonResponseUtil2.failure("参数有误");
        }
        String[] idArr = idStr.split(",");
        List<Long> idList = new ArrayList();
        for (String id : idArr) {
            if (id.trim().length() > 0 && StringUtils.isNumeric(id.trim())) {
                idList.add(Long.valueOf(id.trim()));
            }
        }
        return CommonResponseUtil2.success(contingencyPlanService.delete(idList));
    }

    @Permission
    @ApiOperation(value = "获取数字预案绑定的资源Id", notes = "查看数字预案详情")
    @GetMapping(value = "/bind-source/{type}", produces = "application/json;charset=UTF-8")
    public ResponseModel getPlanBindSource(@PathVariable(value = "type") String type) {
        switch (type) {
            case "doc":
                return CommonResponseUtil2.success(contingencyPlanService.getPlanUsedDocs());
            case "rule":
                return CommonResponseUtil2.success(contingencyPlanService.getPlanUsedRules());
            case "equipment":
                return CommonResponseUtil2.success(contingencyPlanService.getPlanUsedEquipments());
            default:
                throw new YeeException("无效的类型参数");
        }
    }

    @ApiOperation(value = "启动")
    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public ResponseModel start(@RequestBody ContingencyPlanParamVo vo) {
        Toke toke = new Toke();
        toke.setAppKey(getAppKey());
        toke.setProduct(getProduct());
        toke.setToke(getToken());
        AgencyUserModel user = getUserInfo();
        vo.setUserId(user.getUserId());
        vo.setUserName(user.getRealName());
        ContingencyPlanResponseVo result= null;
        try {
             result = contingencyPlanService.planStart(vo,toke);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResponseUtil2.failure();
        }

        return CommonResponseUtil2.success(result);
    }

    @ApiOperation(value = "装备确景")
    @RequestMapping(value = "/scene", method = RequestMethod.GET)
    public ResponseModel scene(@ApiParam(value = "装备Id", required = true) String equipmentId,
                               @ApiParam(value = "告警类型", required = true)  String riskType) {
        ContingencyPlanParamVo vo =  contingencyPlanService.equipmentScene(Long.parseLong(equipmentId),riskType);
        if(vo==null){
            return CommonResponseUtil2.success(vo,"该装备没有预案");
        }else {
            return CommonResponseUtil2.success(vo,"该装备可以启动预案");
        }
    }

    @ApiOperation(value = "预案启动记录分页列表")
    @RequestMapping(value = "/record/page", method = RequestMethod.GET)
    public ResponseModel recordList(
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size")  int pageSize,
            @ApiParam(value = "预案类型") @RequestParam(value = "classifyId", required = false) List<Long> classifyId,
            @ApiParam(value = "启动时间左边界") @RequestParam(value = "startTimeLeft", required = false) Long startTimeLeftStamp,
            @ApiParam(value = "启动时间右边界") @RequestParam(value = "startTimeRight", required = false) Long startTimeRightStamp,
            @ApiParam(value = "执行方式") @RequestParam(value = "executionType", required = false) Integer executionType,
            @ApiParam(value = "运行模式") @RequestParam(value = "planPattern", required = false) Integer planPattern,
            @ApiParam(value = "预案id") @RequestParam(value = "planId", required = false) Long planId,
            @ApiParam(value = "预案名称") @RequestParam(value = "planName", required = false) String planName) {
        Date startTimeLeft = startTimeLeftStamp == null ? null : new Date(startTimeLeftStamp);
        Date startTimeRight = startTimeRightStamp == null ? null : new Date(startTimeRightStamp);
        if (current < 1 || pageSize < 1) {
            throw new YeeException("分页参数有误");
        }
        Page page = new Page(current, pageSize);
        return CommonResponseUtil2.success(contingencyPlanService.recordListByPage(page, planId, planName, classifyId, startTimeLeft, startTimeRight, executionType, planPattern));
    }

    @ApiOperation(value = "第一次查看预案记录")
    @RequestMapping(value = "/frist/getRecord/{batchNo}", method = RequestMethod.GET)
    public ResponseModel firstGetRecord( @PathVariable(value = "batchNo") String batchNo) {
        Map<String, Object> map =  contingencyPlanService.firstGetRecord(batchNo);
        return CommonResponseUtil2.success(map);
    }

    @ApiOperation(value = "查看预案记录列表")
    @RequestMapping(value = "/getRecordList/{batchNo}", method = RequestMethod.GET)
    public ResponseModel getRecordList( @PathVariable(value = "batchNo") String batchNo) {
       List<HashMap<String, Object>> List =  contingencyPlanService.getRecordList(batchNo);
        return CommonResponseUtil2.success(List);
    }

}
