/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.gpsboot.controller.emergency;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.constant.ResponeStatus;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.emergency.EmergencyService;
import com.tofly.pojo.emergency.Emergency;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 应急事件记录表
 *
 * @author admin
 * @date Tue Feb 22 00:00:00 CST 2022
 */
@RestController
@AllArgsConstructor
@RequestMapping("/emergency")
@Api(tags="应急事件记录表接口")
public class EmergencyController {

    private final EmergencyService emergencyService;

    /**
    * 分页查询
    * @param page 分页对象
    * @param emergency 应急事件记录表
    * @return
    */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getEmergencyPage(Page page, @ModelAttribute Emergency emergency) {
        // 排序 发现时间倒序 处理状态正序
      return ResultRespone.success(emergencyService.page(page, Wrappers.query(emergency)
              .lambda().orderByDesc(Emergency::getFoundTime).orderByAsc(Emergency::getState)));
    }


    /**
     * 通过id查询应急事件记录表
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id" ) Long id) {
      return ResultRespone.success(emergencyService.getById(id));
    }

    /**
     * 新增应急事件记录表
     * @param emergency 应急事件记录表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增应急事件记录表" )
    @ApiOperation(value = "新增应急事件记录表")
    @PostMapping
    public ResultRespone save(@RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,@Validated Emergency emergency) {
        ResultRespone rest = new ResultRespone<>();
        try {
            rest = emergencyService.saveInfo(fileList,emergency);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e){
            rest.setCode(ResponeStatus.FAIL.getCode());
            e.printStackTrace();
        }
       return rest;
    }

    /**
     * 应急事件手动派工
     * @param emergency 应急事件记录表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="应急事件手动派工" )
    @ApiOperation(value = "应急事件手动派工")
    @PostMapping("/dispatchingInfo")
    public ResultRespone<Boolean> dispatchingInfo(@RequestBody Emergency emergency) {
        ResultRespone<Boolean> rest = new ResultRespone<>();
        try {
            boolean b = emergencyService.dispatchingInfo(emergency);
            rest.setResult(b);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        }
        return rest;
    }

    /**
     * 修改应急事件记录表
     * @param emergency 应急事件记录表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改应急事件记录表" )
    @ApiOperation(value = "修改应急事件记录表")
    @PutMapping
    public ResultRespone updateById(@RequestParam(value = "fileList", required = false) List<MultipartFile> fileList, Emergency emergency) {
        ResultRespone rest = new ResultRespone<>();
        // 当前对象状态若不为 0 未上报 则不允许修改
        Emergency service = emergencyService.getById(emergency.getId());
        String state = service.getState();
        try {
            if(!"0".equals(state)){
                throw new BusinessException(Constant.EMERGENCY_UPDATE_ERROR_CODE,Constant.EMERGENCY_UPDATE_ERROR);
            }else {
                boolean b = emergencyService.removeById(emergency.getId());
                if(b){
                    emergency.setId(null);
                    rest = emergencyService.saveInfo(fileList, emergency);

                }
            }
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e){
            rest.setCode(ResponeStatus.FAIL.getCode());
            e.printStackTrace();
        }
        return rest;
    }

    /**
     * 通过id批量删除应急事件记录表
     * @param ids id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id批量删除应急事件记录表" )
    @ApiOperation(value = "通过ID批量删除应急事件记录表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds" )
    public ResultRespone<Boolean> removeById(String ids) {
        ResultRespone<Boolean> rest = new ResultRespone<>();
        List<String> stringList = Arrays.asList(ids.split(","));
        // 判断当前删除列表中是否包含除未上报数据,若有则不允许删除
        Set<String> collect = emergencyService.list(new QueryWrapper<Emergency>().lambda().in(Emergency::getId, stringList))
                .stream().map(Emergency::getState).filter(state -> !"0".equals(state)).collect(Collectors.toSet());
        try {
            if(collect.size()>0){
                throw new BusinessException(Constant.EMERGENCY_DELETE_ERROR_CODE,Constant.EMERGENCY_DELETE_ERROR);
            }else {
                rest.setResult(emergencyService.removeByIds(stringList));
            }
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        }

      return rest;
    }
}
