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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.annotation.ResubmitCheck;
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.elevator.api.dto.RescueStationDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.Elevator;
import com.yeejoin.amos.boot.module.elevator.api.entity.RescueStation;
import com.yeejoin.amos.boot.module.elevator.api.mapper.RescueStationMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IRescueStationService;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.ElevatorServiceImpl;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.RescueStationServiceImpl;
import com.yeejoin.amos.boot.module.elevator.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
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.*;
import org.springframework.web.multipart.MultipartFile;
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.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;


/**
 * 救援站
 *
 * @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 map 救援站
     * @return 返回结果
     */
    @ResubmitCheck
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增救援站", notes = "新增救援站")
    public ResponseModel<Boolean> saveRescueStation(@RequestBody Map<String, Object> map) {
        Object addressJson = map.get("address");
        RescueStationDto rescueStationDto = BeanUtil.copyProperties(map, RescueStationDto.class);
        String[] city = rescueStationDto.getCity().split("_");
        String[] district = rescueStationDto.getDistrict().split("_");
        String[] province = rescueStationDto.getProvince().split("_");
        String[] unit = rescueStationDto.getAffiliatedUnit().split("_");
        rescueStationDto.setAffiliatedUnit(unit[1]);
        rescueStationDto.setAffiliatedUnitId(Long.valueOf(unit[0]));
        rescueStationDto.setCity(city[1]);
        rescueStationDto.setDistrict(district[1]);
        rescueStationDto.setProvince(province[1]);
        rescueStationDto.setRegionCode(province[0] + "#" + city[0] + "#" + district[0]);
        JSONObject address = JSONUtil.parseObj(addressJson);
        rescueStationDto.setLongitudeLatitude(JSONUtil.toJsonStr(address));
        rescueStationDto.setAddress(ObjectUtils.isEmpty(address.get("address")) ? null : String.valueOf(address.get("address")));
        rescueStationDto.setLatitude(ObjectUtils.isEmpty(address.get("latitude")) ? null : String.valueOf(address.get("latitude")));
        rescueStationDto.setLongitude(ObjectUtils.isEmpty(address.get("longitude")) ? null : String.valueOf(address.get("longitude")));
        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 map 救援站
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改救援站", notes = "修改救援站")
    public ResponseModel<Boolean> updateByIdRescueStation(@RequestBody Map<String, Object> map) {
//        RescueStation rescueStation = BeanDtoVoUtils.convert(rescueStationDto, RescueStation.class);
        Object addressJson = map.get("address");
        RescueStation rescueStation = BeanUtil.copyProperties(map, RescueStation.class);
        String[] city = rescueStation.getCity().split("_");
        String[] district = rescueStation.getDistrict().split("_");
        String[] unit = rescueStation.getAffiliatedUnit().split("_");
        rescueStation.setAffiliatedUnit(unit[1]);
        rescueStation.setAffiliatedUnitId(Long.valueOf(unit[0]));
        rescueStation.setCity(city[1]);
        rescueStation.setDistrict(district[1]);
        rescueStation.setRegionCode("610000" + "#" + city[0] + "#" + district[0]);
        JSONObject address = JSONUtil.parseObj(addressJson);
        rescueStation.setLongitudeLatitude(JSONUtil.toJsonStr(address));
        rescueStation.setAddress(ObjectUtils.isEmpty(address.get("address")) ? null : String.valueOf(address.get("address")));
        rescueStation.setLatitude(ObjectUtils.isEmpty(address.get("latitude")) ? null : String.valueOf(address.get("latitude")));
        rescueStation.setLongitude(ObjectUtils.isEmpty(address.get("longitude")) ? null : String.valueOf(address.get("longitude")));
        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<Map<String, Object>> selectById(@PathVariable Long id) {
        Map<String, Object> detail = rescueStationMapper.getDetailById(id);
        detail.put("address", String.valueOf(detail.get("longitudeLatitude")).contains("{") ? JSON.parseObject(String.valueOf(detail.get("longitudeLatitude"))) : detail.get("address"));
        List<String> strings = Arrays.asList(String.valueOf(detail.get("regionCode")).split("#"));
        detail.put("city", strings.get(1) + "_" + detail.get("city"));
        detail.put("district", strings.get(2) + "_" + detail.get("district"));
//        RescueStation rescueStation = iRescueStationService.getById(id);
//        List<String> strings = Arrays.asList(rescueStation.getRegionCode().split("#"));
//        rescueStation.setCity(strings.get(1)+"_"+rescueStation.getCity());
//        rescueStation.setDistrict(strings.get(2)+"_"+rescueStation.getDistrict());
//        RescueStationDto rescueStationDto = BeanDtoVoUtils.convert(rescueStation, RescueStationDto.class);

        return ResponseHelper.buildResponse(detail);
    }

    /**
     * 列表分页查询
     *
     * @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);
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        rescueStationDto.setOrgCode(companyModels.get(0).getOrgCode());
        IPage<RescueStation> page = new Page<>();
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            page.setSize(Long.MAX_VALUE);
            page.setCurrent(0);
        } else {
            page.setSize(Integer.parseInt(pageSize));
            page.setCurrent(Integer.parseInt(pageNum));
        }
        page = iRescueStationService.getRescueStationList(page,rescueStationDto);
        IPage<RescueStationDto> rescueStationDtoIPage = ObjectUtils.isEmpty(page)? new Page<>(): 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) {
        // 获取根据警情获取电梯信息
        Map<String,Object> map  = elevatorServiceImpl.selectByAlertId(alertId);
        String longitude = String.valueOf(map.get("longitude"));
        String latitude = String.valueOf(map.get("latitude"));
        // 根据经纬度和距离返回救援机构信息
        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) {
        // 获取根据警情获取电梯信息
        Map<String,Object> map  = elevatorServiceImpl.selectByAlertId(alertId);
        String longitude = String.valueOf(map.get("longitude"));
        String latitude = String.valueOf(map.get("latitude"));
        // 根据经纬度和距离返回救援机构信息
        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);
    }

    /**
     * @author chang xiangyu
     * @param file
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/import")
    @ApiOperation(httpMethod = "POST", value = "救援站列表数据导入", notes = "救援站列表数据导入")
    public ResponseModel<Object> expertDataImport(@RequestBody MultipartFile file) {
        // 校验文件是否为空
        if (file.isEmpty()) {
            return ResponseHelper.buildResponse("文件不能为空");
        }
        // 校验文件类型为 Excel
        String contentType = file.getContentType();
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 校验 Excel 文件的 MIME type 和扩展名
        if (!("application/vnd.ms-excel".equals(contentType) ||
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)) ||
                !("xls".equalsIgnoreCase(fileExtension) || "xlsx".equalsIgnoreCase(fileExtension))) {
            return ResponseHelper.buildResponse("文件类型必须是 Excel 文件");
        }
        AgencyUserModel userModel = getSelectedOrgInfo().getUserModel();
        return iRescueStationService.expertDataImport(file,userModel);
    }

}

