package com.elephant.framework.galaxy.aroad.module.roadcondition.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.roadcondition.entity.RoadConditionEvent;
import com.elephant.framework.galaxy.aroad.module.roadcondition.service.RoadConditionEventService;
import com.elephant.framework.galaxy.aroad.response.R;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

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

/**
 * 路况事件统计
 *
 * @author Xingyuyang
 * @date 2019-04-23 16:41:06
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/roadconditionevent")
public class RoadConditionEventController extends BaseController {

  private final RoadConditionEventService roadConditionEventService;

  /**
   * 分页查询
   *
   * @param page 分页对象
   * @param roadConditionEvent 路况事件统计
   * @return
   */
  @PostMapping("/page")
  public R getRoadConditionEventPage(
      Page page, @RequestBody RoadConditionEvent roadConditionEvent) {
    //        log.error("接收实体：{}", roadConditionEvent);
    page.setCurrent(roadConditionEvent.getCurrent());
    page.setSize(roadConditionEvent.getSize());
    return new R<>(roadConditionEventService.getRoadConditionEventPage(page, roadConditionEvent));
  }

  @GetMapping("/unitTree")
  public R getUnitTree() {
    return new R<>(roadConditionEventService.getUnitTree());
  }

  /**
   * 分页查询
   *
   * @return
   */
  @GetMapping("/mobilepage")
  public R getRoadConditionEventMobilePage() {
    return new R<>(roadConditionEventService.getRoadConditionEventMobilePage());
  }
  /**
   * @description : 根据事件类型统计
   * @author : Xingyuyang
   * @date : 2019/4/23 0023 17:33
   * @param
   * @return : null
   */
  @GetMapping("/eventtype")
  public R staticByEventType() {
    return new R<>(roadConditionEventService.staticByEventType());
  }

  /**
   * @description : 根据事件类型统计
   * @author : Xingyuyang
   * @date : 2019/4/23 0023 17:33
   * @param
   * @return : null
   */
  //  @GetMapping("/location")
  //  public R locatioinOnMap() {
  //    return new R<>(roadConditionEventService.locatioinOnMap());
  //  }

  /**
   * @description : 根据影响程度统计
   * @author : Xingyuyang
   * @date : 2019/4/23 0023 17:33
   * @param
   * @return : null
   */
  @GetMapping("/influence")
  public R staticByInfluence() {
    return new R<>(roadConditionEventService.staticByInfluence());
  }

  /**
   * @description : 根据月份统计
   * @author : Xingyuyang
   * @date : 2019-4-24 10:26:49
   * @param
   * @return : null
   */
  @GetMapping("/month")
  public R staticByMonth() {
    return new R<>(roadConditionEventService.staticByMonth());
  }

  /**
   * @description : 根据路段编码统计
   * @author : Xingyuyang
   * @date : 2019-4-24 10:26:49
   * @param
   * @return : null
   */
  @GetMapping("/roadcode")
  public R staticByRoadCode() {
    return new R<>(roadConditionEventService.staticByRoadCode());
  }

  /**
   * @description : 根据路段编码统计
   * @author : Xingyuyang
   * @date : 2019-4-24 10:26:49
   * @param
   * @return : null
   */
  @GetMapping("/city")
  public R staticByCity() {
    return new R<>(roadConditionEventService.staticByCity());
  }

  /**
   * @description : 根据路段编码统计
   * @author : Xingyuyang
   * @date : 2019-4-24 10:26:49
   * @param
   * @return : null
   */
  @GetMapping("/yhcity")
  public R staticByYHCity() {
    return new R<>(roadConditionEventService.staticByYHCity());
  }

  /**
   * @Description: 查询市/局树 @Param: []
   *
   * @return: com.elephant.framework.galaxy.travel.response.R @Author: XingYuyang @Date: 2019/4/10
   */
  @GetMapping("/tree")
  public R getTree() {
    return new R<>(roadConditionEventService.getTree());
  }

  /**
   * 查询坐标
   *
   * @param
   * @return R
   */
  @GetMapping("/coordinates/{deptId}")
  public R getCoordinates(@PathVariable("deptId") String deptId) {
    return new R<>(roadConditionEventService.getCoordinates(deptId));
  }

  @GetMapping("/getunitbydept/{deptId}")
  public R getUnitByDept(@PathVariable("deptId") String deptId) {
    return new R<>(roadConditionEventService.getUnitByDept(deptId));
  }

  @GetMapping("/tqcoordinates")
  public R getTQCoordinates() {
    return new R<>(roadConditionEventService.getTQCoordinates());
  }

  @GetMapping("/yhcoordinates")
  public R getYHCoordinates() {
    return new R<>(roadConditionEventService.getYHCoordinates());
  }

  @GetMapping("/tfcoordinates")
  public R getTFCoordinates() {
    return new R<>(roadConditionEventService.getTFCoordinates());
  }

  @GetMapping("/sfzcoordinates")
  public R getSFZCoordinates() {
    return new R<>(roadConditionEventService.getSFZCoordinates());
  }

  /**
   * @description : 部门和管理单位权限管理
   * @author : Xingyuyang
   * @date : 2019/5/21 0021 11:28
   * @param params :
   * @return : com.elephant.framework.galaxy.aroad.response.R
   */
  @GetMapping("/saveunitwithdept/{params}")
  public R saveUnitWithDept(@PathVariable("params") String params) {
    return new R<>(roadConditionEventService.saveUnitWithDept(params));
  }

  /**
   * @description : 部门和管理单位权限管理
   * @author : Xingyuyang
   * @date : 2019/5/21 0021 11:28
   * @param params :
   * @return : com.elephant.framework.galaxy.aroad.response.R
   */
  @GetMapping("/saveemergencyunit/{params}")
  public R saveEmergencyUnit(@PathVariable("params") String params) {
    return new R<>(roadConditionEventService.saveEmergencyUnit(params));
  }

  @DeleteMapping("/deleteemergencyunit/{eventId}")
  public R deleteEmergencyUnit(@PathVariable("eventId") String eventId) {
    return new R<>(roadConditionEventService.deleteEmergencyUnit(eventId));
  }

  @DeleteMapping("/deleteemergencyevent/{eventId}")
  public R deleteEmergencyEvent(@PathVariable("eventId")  String eventId) {
    return new R<>(roadConditionEventService.deleteEmergencyEvent(eventId));
  }

  /**
   * 通过id查询路况事件统计
   *
   * @param eventId eventId
   * @return R
   */
  @GetMapping("/{eventId}")
  public R getById(@PathVariable("eventId") String eventId) {
    //    Integer idi = Integer.parseInt(id);
    return new R<>(roadConditionEventService.getById(eventId));
  }

  /**
   * 新增路况事件统计
   *
   * @param roadConditionEvent 路况事件统计
   * @return R
   */
  @SysLog("新增路况事件统计")
  @PostMapping
  public R save(@RequestBody RoadConditionEvent roadConditionEvent) {
    return new R<>(roadConditionEventService.save(roadConditionEvent));
  }

  /**
   * 修改路况事件统计
   *
   * @param roadConditionEvent 路况事件统计
   * @return R
   */
  @SysLog("修改路况事件统计")
  @PutMapping
  public R updateById(@RequestBody RoadConditionEvent roadConditionEvent) {
    return new R<>(roadConditionEventService.updateById(roadConditionEvent));
  }

  /**
   * 通过id删除路况事件统计
   *
   * @param eventId eventId
   * @return R
   */
  @SysLog("删除路况事件统计")
  @DeleteMapping("/{id}")
  public R removeById(@PathVariable String eventId) {
    return new R<>(roadConditionEventService.removeById(eventId));
  }

  /**
   * 新增养护施工事件
   *
   * @param
   * @return List<String>
   */
  @SysLog("新增养护施工事件")
  @PostMapping("/saveRoadMaintainEvent")
  @ApiOperation(value = "新增养护施工事件")
  @ApiImplicitParam(
      name = "jsonString",
      value = "养护施工事件JSON格式字符串",
      required = true,
      dataType = "String")
  public R saveRoadMaintainEvent(@RequestBody String jsonString) {
    String msg = "";
    Integer code = 0;
    List<MultiValueMap<String, String>> errorEventIds =
        new ArrayList<MultiValueMap<String, String>>();
    List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
    JSONArray jsonArray = JSONArray.fromObject(jsonString);
    String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"};
    JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
    List<RoadConditionEvent> roadConditionEvents =
        (List<RoadConditionEvent>) JSONArray.toCollection(jsonArray, RoadConditionEvent.class);
    try {
      for (RoadConditionEvent event : roadConditionEvents) {
        if (getRoadMaintainEventByEventID(event.getEventId()) > 0) {
          Map<String, Object> map = new HashMap<String, Object>();
          map.put("eventId", event.getEventId());
          listMap.add(map);
          msg = "该路况事件ID已存在，请调用路况事件更新接口，更新路况事件";
          code = 203;
          continue;
        } else {
          roadConditionEventService.save(event);
          if (code != 203) {
            msg = "success";
            code = 200;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new R<>(code, msg, listMap);
  }

  /**
   * 根据事件ID查询该路况事件是否已经存在（大于0表示已存在）
   *
   * @return
   */
  public Integer getRoadMaintainEventByEventID(String eventID) {
    return roadConditionEventService.getRoadMaintainEventByEventID(eventID);
  }

  /**
   * 更新养护施工事件 保存历史数据
   *
   * @param
   * @return void
   */
  @SysLog("更新养护施工事件")
  @PostMapping("/updateRoadMaintainEvent")
  @ApiOperation(value = "更新养护施工事件")
  @ApiImplicitParam(
      name = "jsonString",
      value = "养护施工事件JSON格式字符串",
      required = true,
      dataType = "String")
  public R updateRoadMaintainEvent(@RequestBody String jsonString) throws Exception {
    List<Object> infoList = new ArrayList<Object>();
    String msg = "";
    Integer code = 0;
    JSONArray jsonArray = JSONArray.fromObject(jsonString);
    String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"};
    JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
    List<RoadConditionEvent> roadConditionEvents =
        (List<RoadConditionEvent>) JSONArray.toCollection(jsonArray, RoadConditionEvent.class);
    try {
      for (int i = 0; i < roadConditionEvents.size(); i++) {
        RoadConditionEvent event = (RoadConditionEvent) roadConditionEvents.get(i);
        RoadConditionEvent result = getRoadMaintainEvent(event);
        if (result != null) {
          infoList.add(jsonArray.get(i));
          msg = "存在重复数据，请核实";
          code = 204;
          continue;
        } else {
          roadConditionEventService.save(event);
          if (code != 204) {
            msg = "success";
            code = 200;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new R<>(code, msg, infoList);
  }
  /**
   * 查询该路况事件是否已经存在（大于0表示已存在） *
   *
   * @return
   */
  public RoadConditionEvent getRoadMaintainEvent(RoadConditionEvent event) {
    return roadConditionEventService.selectRoadMaintainEvent(event);
  }

  /**
   * 删除养护施工事件(通过主键id) flag(删除：1)
   *
   * @param
   * @return R
   */
  @SysLog("删除养护施工事件，假删除")
  @DeleteMapping("/deleteRoadMaintainEvent")
  @ApiOperation(value = "删除养护施工事件")
  @ApiImplicitParam(
      name = "jsonString",
      value = "养护施工事件JSON格式字符串",
      required = true,
      dataType = "String")
  public R deleteRoadMaintainEvent(@RequestBody String jsonString) {
    JSONArray jsonArray = JSONArray.fromObject(jsonString);
    String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"};
    JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
    List<RoadConditionEvent> roadConditionEvents =
        (List<RoadConditionEvent>) JSONArray.toCollection(jsonArray, RoadConditionEvent.class);
    try {
      for (RoadConditionEvent event : roadConditionEvents) {
        roadConditionEventService.deleteBatchByEvent(event);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new R<>(200, "success");
  }

  /**
   * 撤销养护施工事件(通过eventId) flag(撤销：0)
   *
   * @param
   * @return R
   */
  @SysLog("撤销养护施工事件")
  @PutMapping("/revokeRoadMaintainEventByEventId")
  @ApiOperation(value = "撤销养护施工事件")
  @ApiImplicitParam(
      name = "jsonString",
      value = "养护施工事件JSON格式字符串",
      required = true,
      dataType = "String")
  public R revokeRoadMaintainEventByEventId(@RequestBody String jsonString) {
    JSONArray jsonArray = JSONArray.fromObject(jsonString);
    List<RoadConditionEvent> roadMaintainEvents =
        (List<RoadConditionEvent>) JSONArray.toCollection(jsonArray, RoadConditionEvent.class);
    List<Object> eventIdList = new ArrayList<Object>();
    try {
      for (RoadConditionEvent event : roadMaintainEvents) {
        eventIdList.add(event.getEventId());
      }
      Integer rowNumber = roadConditionEventService.updateBatchByEventId(eventIdList);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new R<>(200, "success");
  }
}
