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


import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
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 org.typroject.tyboot.core.foundation.context.RequestContext;

import com.yeejoin.amos.fas.business.action.CustomerAction;
import com.yeejoin.amos.fas.business.service.impl.RiskSourceServiceImpl;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyInstance;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyOriginalDataService;
import com.yeejoin.amos.fas.business.service.intfc.IEquipmentService;
import com.yeejoin.amos.fas.business.service.intfc.IRuleRunningSnapshotService;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.request.CommonRequest;
import com.yeejoin.amos.fas.core.enums.NumberEnum;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.core.util.DateUtil;
import com.yeejoin.amos.fas.dao.entity.Equipment;

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

@RestController
@RequestMapping(value = "/api/timeline")
@Api(tags="时间轴")
public class TimeLineController extends AbstractBaseController{

    private static final Logger log = LoggerFactory.getLogger(TimeLineController.class);
    @Autowired
    IContingencyInstance iContingencyInstance;
    @Qualifier("contingencyAction")
    @Autowired
    private  CustomerAction customerAction;
    @Autowired
    IContingencyOriginalDataService iContingencyOriginalDataService;

    @Autowired
    IRuleRunningSnapshotService iRuleRunningSnapshotService;

    @Autowired
    IEquipmentService equipmentService;

    static LinkedList<Map<String,String >> fireQueue  = new LinkedList<>();

	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private IRuleRunningSnapshotService ruleRunningSnapshotService;

    @Permission
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET",value = "根据批次号查询时间轴", notes = "根据批次号查询时间轴")
    @RequestMapping(value = "/{instanceNo}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPoint(@PathVariable String  instanceNo,@RequestParam("recordType") String recordType) throws Exception{

        return CommonResponseUtil.success(iContingencyInstance.queryForTimeLine(instanceNo,recordType));
    }

    @Permission
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "PUT",value = "点击按钮", notes = "点击按钮")
    @RequestMapping(value = "/fire", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse fire(@RequestParam("batchNo") String  batchNo,
                                     @RequestParam("stepCode") String stepCode,
                                     @RequestParam("buttonCode") String buttonCode,
                                     @RequestParam("confirm") String confirm,
                                     @RequestParam("contingencyPlanId") String contingencyPlanId,
                                     @RequestParam("stepState") String stepState) throws Exception{

        Map<String,String> map = new HashMap<>();
        map.put("batchNo",batchNo);
        map.put("stepCode",stepCode);
        map.put("buttonCode",buttonCode);
        map.put("confirm",confirm);
        map.put("contingencyPlanId",contingencyPlanId);
        map.put("stepState",stepState);
        map.put("token",getToken());
        map.put("product",getProduct());
        fireQueue.addLast(map);
        return CommonResponseUtil.success("SUCCESS");
    }

    @Permission
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "PUT",value = "点击按钮", notes = "点击按钮")
    @RequestMapping(value = "/fire/exit", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse fireExit(@RequestParam("batchNo") String  batchNo,
                                     @RequestParam("stepCode") String stepCode,
                                     @RequestParam("buttonCode") String buttonCode,
                                     @RequestParam("confirm") String confirm,
                                     @RequestParam("stepState") String stepState) throws Exception{

        Map<String,String> map = new HashMap<>();
        redisTemplate.delete(RiskSourceServiceImpl.cacheKeyForCanBeRunning());
        Optional<Equipment> equipment = iContingencyInstance.fire(batchNo,stepCode,"",buttonCode,confirm,stepState);
        //  结束预案，更新设备重点设备参数
        equipment.ifPresent(equip -> {
            equip.setStartTime(DateUtil.getDateNow());
            equip.setEndTime(null);
            equip.setReserveSource(NumberEnum.ONE.getValue());
            equip.setStatus(NumberEnum.ONE.getValue());
            equipmentService.save(equip);
        });
        customerAction.intreeuptPlan(batchNo);
        return CommonResponseUtil.success("SUCCESS");
    }

    @Permission
    @ApiOperation(httpMethod = "GET",value = "预案回放", notes = "预案回放")
    @RequestMapping(value = "/fire/replay", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse replay(@RequestParam("batchNo") String  batchNo,
                                     @RequestParam("randomNumber") String randomNumber) throws Exception{
    	ruleRunningSnapshotService.replayPlan(batchNo, randomNumber);
        return CommonResponseUtil.success("SUCCESS");
    }

    @Permission
    @ApiOperation(httpMethod = "GET",value = "预案回放退出", notes = "预案回放退出")
    @RequestMapping(value = "/fire/replay/exit", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse replayExit(@RequestParam("batchNo") String  batchNo,
                                     @RequestParam("randomNumber") String randomNumber) throws Exception{
    	ruleRunningSnapshotService.exitReplayPlan(batchNo, randomNumber);
        return CommonResponseUtil.success("SUCCESS");
    }

    @Scheduled(cron = "*/2 * * * * ?")
    public void runFireQueue()  throws Exception
    {

        if(fireQueue.size() == 0)
            return;

        Map<String,String>  map = fireQueue.getFirst();
        String batchNo = map.get("batchNo");
        String stepCode = map.get("stepCode");
        String buttonCode = map.get("buttonCode");
        String confirm = map.get("confirm");
        String contingencyPlanId = map.get("contingencyPlanId");
        String  stepState = map.get("stepState");
        String  token = map.get("token");
        String  product = map.get("product");
        try
        {
            log.info("fireQueue-size:"+fireQueue.size());
            log.info("stepCode:" + map.get("stepCode"));
            log.info("buttonCode:" + map.get("buttonCode"));
            log.info("confirm:" + map.get("confirm"));
            log.info("stepState:" + map.get("stepState"));
            RequestContext.setToken(token);
            RequestContext.setProduct(product);
            iContingencyInstance.setButtonExecuted(batchNo,contingencyPlanId,buttonCode,confirm);
            iContingencyInstance.fire(batchNo,stepCode,contingencyPlanId,buttonCode,confirm,stepState);
        }catch (Exception e)
        {
            throw  e;
        }finally {
            fireQueue.removeFirst();
        }
    }


    @Permission
   // @Authorization(ingore = true)
    @ApiOperation(httpMethod = "POST",value = "查询预案记录", notes = "查询预案记录")
    @RequestMapping(value = "/contingency/page", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse contingencyRecord(
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable
    ) {
        //CommonPageable commonPageable = new CommonPageable(pageNumber,pageSize);

        String  contingencyName = null;
        String  equipmentId = null;
        String  createTime = null;
        if(!CollectionUtils.isEmpty(queryRequests))
        {
            for(CommonRequest request:queryRequests)
            {
                if("contingencyName".equals(request.getName()))
                {
                    contingencyName = String.valueOf(request.getValue());
                }
                if("equipmentId".equals(request.getName()))
                {
                    equipmentId = String.valueOf(request.getValue());
                }
                if("createTime".equals(request.getName()))
                {
                    createTime = String.valueOf(request.getValue());
                }
            }
        }

        return CommonResponseUtil.success(iContingencyOriginalDataService.queryForPage(contingencyName,equipmentId,createTime,commonPageable));
    }


    String operate = "{" +
            "    \"type\": \"button\"," +
            "    \"operate\": [" +
            "        {" +
            "            \"title\": \"确认着火\"," +
            "            \"paramName\": \"batchNo\"," +
            "            \"paramValue\": \"11\"," +
            "            \"requestUrl\": \"url\"," +
            "            \"icon\": \"querenzhuohuo\"," +
            "            \"confirm\": true," +
            "            \"state\": \"executed\"" +
            "        }," +
            "        {" +
            "            \"title\": \"消除误报\"," +
            "            \"paramName\": \"batchNo\"," +
            "            \"paramValue\": \"11\"," +
            "            \"requestUrl\": \"url\"," +
            "            \"icon\": \"xiaochuwubao\"," +
            "            \"confirm\": true," +
            "            \"state\": \"wait\"" +
            "        }" +
            "    ]" +
            "}";

    @Permission
    @ApiOperation(httpMethod = "GET",value = "根据批次号查询时间轴", notes = "根据批次号查询时间轴")
    @RequestMapping(value = "/replay", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPoint(@RequestParam("batchNo") String batchNo) throws Exception{
    	iRuleRunningSnapshotService.replay(batchNo);
        return CommonResponseUtil.success();
    }


}
