package com.yeejoin.amos.boot.module.ymt.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.ymt.api.dto.RescueStationDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.Elevator;
import com.yeejoin.amos.boot.module.ymt.api.entity.RescueStation;
import com.yeejoin.amos.boot.module.ymt.api.mapper.RescueStationMapper;
import com.yeejoin.amos.boot.module.ymt.api.service.IRescueStationService;
import com.yeejoin.amos.boot.module.ymt.biz.service.impl.ElevatorServiceImpl;
import com.yeejoin.amos.boot.module.ymt.biz.service.impl.RescueStationServiceImpl;
import com.yeejoin.amos.boot.module.ymt.biz.utils.BeanDtoVoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * 救援站
 *
 * @author tb
 * @date 2021-06-01
 */
@RestController
@Api(tags = "救援站Api")
@RequestMapping(value = "/rescue-station")
public class RescueStationController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(RescueStationController.class);

    @Autowired
    IRescueStationService iRescueStationService;

    @Autowired
    ElevatorServiceImpl elevatorServiceImpl;
     @Autowired
    RescueStationMapper rescueStationMapper;
     @Autowired
     RescueStationServiceImpl rescueStationServiceImpl;
    /**
     * 新增救援站
     *
     * @param rescueStationDto 救援站
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增救援站", notes = "新增救援站")
    public ResponseModel<Boolean> saveRescueStation(@RequestBody RescueStationDto rescueStationDto) {

        return ResponseHelper.buildResponse(rescueStationServiceImpl.saveRescueStation(rescueStationDto));
    }

    /**
     * 根据id删除
     *
     * @param ids id,id,id,...
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    @Transactional
    public ResponseModel<Boolean> deleteById(@PathVariable String ids) {
        String[] id = ids.split(",");
        boolean remove = true;
        for(int i = 0 ; i < id.length ; i++) {
            if(remove) {
                RescueStation rescueStation = iRescueStationService.getById(id[i]);
                rescueStation.setIsDelete(true);
                rescueStation.setRecUserId(RequestContext.getExeUserId());
                rescueStation.setRecDate(new Date());
                remove = iRescueStationService.updateById(rescueStation);
                if (!remove) {
                    return CommonResponseUtil.failure("应急救援机构名称："+rescueStation.getName()+"删除失败！");
                }
            }
        }
        return ResponseHelper.buildResponse(remove);
    }

    /**
     * 修改救援站
     *
     * @param rescueStationDto 救援站
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改救援站", notes = "修改救援站")
    public ResponseModel<Boolean> updateByIdRescueStation(@RequestBody RescueStationDto rescueStationDto) {

        RescueStation rescueStation = BeanDtoVoUtils.convert(rescueStationDto, RescueStation.class);
        rescueStation.setRecUserId(RequestContext.getExeUserId());
        rescueStation.setRecDate(new Date());
        boolean update = iRescueStationService.updateById(rescueStation);
        return ResponseHelper.buildResponse(update);
    }

    /**
     * 根据id查询
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<RescueStationDto> selectById(@PathVariable Long id) {
        RescueStation rescueStation = iRescueStationService.getById(id);
        RescueStationDto rescueStationDto = BeanDtoVoUtils.convert(rescueStation, RescueStationDto.class);
        return ResponseHelper.buildResponse(rescueStationDto);
    }

    /**
     * 列表分页查询
     *
     * @param pageNum          页码
     * @param pageSize         每页大小
     * @param rescueStationDto 查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<RescueStationDto>> listPage(String pageNum, String pageSize,
                                                           RescueStationDto rescueStationDto) {
        RescueStation rescueStation = BeanDtoVoUtils.convert(rescueStationDto, RescueStation.class);
        Page<RescueStation> pageBean;
        QueryWrapper<RescueStation> rescueStationQueryWrapper = new QueryWrapper<>();
        Class<? extends RescueStation> aClass = rescueStation.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(rescueStation);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(rescueStation);
                        rescueStationQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(rescueStation);
                        rescueStationQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(rescueStation);
                        rescueStationQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(rescueStation);
                        rescueStationQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<RescueStation> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iRescueStationService.page(pageBean, rescueStationQueryWrapper);
        IPage<RescueStationDto> rescueStationDtoIPage = BeanDtoVoUtils.iPageVoStream(page, RescueStationDto.class);
        return ResponseHelper.buildResponse(rescueStationDtoIPage);
    }

    /**
     * 分页查询救援站信息
     *
     * @param pageNum          页码
     * @param pageSize         每页大小
     * @param rescueStationDto 查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/query_rescue_station_list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页查询救援站信息", notes = "分页查询救援站信息")
    public ResponseModel<IPage<RescueStationDto>> queryRescueStationList(String pageNum, String pageSize,
                                                                        RescueStationDto rescueStationDto) {
        RescueStation rescueStation = BeanDtoVoUtils.convert(rescueStationDto, RescueStation.class);
        Page<RescueStation> pageBean;
        QueryWrapper<RescueStation> rescueStationQueryWrapper = new QueryWrapper<>();
        rescueStationQueryWrapper.eq("is_delete",false);
        Class<? extends RescueStation> aClass = rescueStation.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(rescueStation);
                if (o != null) {
                    String name = NameUtils.camel2Underline(field.getName());
                    if ("name".equalsIgnoreCase(name) || "address".equalsIgnoreCase(name) || "principal".equalsIgnoreCase(name) || "rescue_leader".equalsIgnoreCase(name) || "rescue_leader_phone".equalsIgnoreCase(name)) {
                        String fileValue = (String) o;
                        rescueStationQueryWrapper.like(name, fileValue);
                    } else if ("city".equalsIgnoreCase(name) || "district".equalsIgnoreCase(name) || "affiliated_unit"
                            .equalsIgnoreCase(name)) {
                        String fileValue = (String) o;
                        rescueStationQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) o;
                        rescueStationQueryWrapper.like(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<RescueStation> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iRescueStationService.page(pageBean, rescueStationQueryWrapper);
        IPage<RescueStationDto> rescueStationDtoIPage = BeanDtoVoUtils.iPageVoStream(page, RescueStationDto.class);
        return ResponseHelper.buildResponse(rescueStationDtoIPage);
    }


    /**
     * 根据警情id和距离返回救援机构信息
     * @param alertId
     * @param distance
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/alert/{alertId}/distance/{distance}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据警情id和距离返回救援机构信息", notes = "根据警情id和距离返回救援机构信息")
    public ResponseModel<Object> selectByAlertIdDistance(@PathVariable Long alertId, @PathVariable Integer distance) {
        // 获取根据警情获取电梯信息
        Elevator elevator  = elevatorServiceImpl.selectByAlertId(alertId);
        String longitude = elevator.getLongitude();
        String latitude = elevator.getLatitude();
        // 根据经纬度和距离返回救援机构信息
        return ResponseHelper.buildResponse(iRescueStationService.getListByLatLonDistance(latitude,longitude,distance));
    }

    /**
     * 根据警情id和距离返回救援机构信息
     * @param alertId
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/alert/{alertId}/distance", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据警情id和距离返回5个救援机构信息", notes = "根据警情id和距离返回5个救援机构信息")
    public ResponseModel<Object> selectByAlertIdDistance(@PathVariable Long alertId) {
        // 获取根据警情获取电梯信息
        Elevator elevator  = elevatorServiceImpl.selectByAlertId(alertId);
        String longitude = elevator.getLongitude();
        String latitude = elevator.getLatitude();
        // 根据经纬度和距离返回救援机构信息
        List<RescueStationDto> rescueStationDtos = new LinkedList<>();
        List<RescueStationDto> list = iRescueStationService.getListByLatLonDistance(latitude,longitude,1000);
        if(list.size() > 5) {
            for(int i = 0 ; i < 5 ; i ++ ) {
                rescueStationDtos.add(list.get(i));
            }
        }
        return ResponseHelper.buildResponse(list.size() > 5 ? rescueStationDtos: list);
    }

}

