package com.artfess.yhxt.open.base.controller;


import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.cache.CacheManager;
import com.artfess.base.cache.setting.CacheSetting;
import com.artfess.base.conf.JwtConfig;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.jwt.JwtTokenHandler;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.util.TokenUtils;
import com.artfess.uc.util.ContextUtil;
import com.artfess.yhxt.basedata.manager.*;
import com.artfess.yhxt.basedata.model.*;
import com.artfess.yhxt.basedata.vo.BizEmergencyRescueManagement4OpenVO;
import com.artfess.yhxt.basedata.vo.BizEmergencyRescueManagementVO;
import com.artfess.yhxt.contract.manager.impl.WorkOrderInformationManagerImpl;
import com.artfess.yhxt.disease.manager.DiseaseManager;
import com.artfess.yhxt.disease.model.Disease;
import com.artfess.yhxt.statistics.vo.Org4AppVO;
import com.artfess.yhxt.statistics.vo.OrgDisease4AppVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultClock;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhx
 * @create 2022/1/10
 */
@RestController
@RequestMapping("/server/")
@Api(tags = "路产基础数据对外接口")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class BaseDataController {
    @Resource
    RoadManager roadManager;
    @Resource
    BridgeInformationManager bridgeInformationManager;
    @Resource
    RouteManager routeManager;
    @Resource
    SideSlopeInformationManager sideSlopeInformationManager;
    @Resource
    TunnelInformationManager tunnelInformationManager;
    @Resource
    BizRoadsideFacilitiesManager roadsideFacilitiesManager;
    @Resource
    private WorkOrderInformationManagerImpl workOrderInformationManager;
    @Resource
    JwtConfig jwtConfig;
    @Resource
    BizCulvertInformationManager bizCulvertInformationManager;
    @Resource
    DiseaseManager diseaseManager;
    @Resource
    private BizEmergeMaterialManagementManager emergeMaterialManagementManager;
    @Resource
    private BizEmergencyRescueManagementManager emergencyRescueManagementManager;
    @Resource
    private BizMaintenanceWorkAreaManager maintenanceWorkAreaManager;
    @Resource
    private BizStructureVehicleManager structureVehicleManager;
    @Resource
    private BizMaterialsManagementManager materialsManagementManager;
    @Resource
    private BizStructureVehicleManager bizStructureVehicleManager;

    private final List<String> accessKeyList = Arrays.asList("59zDDSsqq7Kkrf04Dtn3", "gPH2qC81nzk5y19eI63Y", "8A19AdZhisHjuQPKUyXB", "I7C3uDuTP4LqvN0DDJgm", "ZVrG0vlqQQciC4A8r0gh","9190EECE05BFD885");

    private Clock clock = DefaultClock.INSTANCE;

//    @Resource
//    CacheManager cacheManager;
//    private static final CacheSetting cacheSetting = CacheSetting.buildDefault("对外接口数据缓存");


    @GetMapping("/workOrderApp")
    @ApiOperation(value = "App养护工单节点统计信息", httpMethod = "GET", notes = "App养护工单节点统计信息")
    public CommonResult<Org4AppVO> workOrderApp(@RequestParam String level, @RequestParam(required = false) String dimension, @RequestParam String date) throws Exception {
        return new CommonResult<Org4AppVO>
                (true, "App养护工单节点统计信息", workOrderInformationManager.getWorkOrderCount4App(level,dimension,date));

    }

    @GetMapping("/workOrderListApp")
    @ApiOperation(value = "App养护工单统计信息", httpMethod = "GET", notes = "App养护工单统计信息")
    public CommonResult<List<Org4AppVO>> workOrderListApp(@RequestParam String level, @RequestParam(required = false) String dimension, @RequestParam String date) throws Exception {
        return new CommonResult<List<Org4AppVO>>
                (true, "App养护工单统计信息", workOrderInformationManager.getWorkOrderCountList4App(level,dimension,date));

    }

    @GetMapping("/diseaseApp")
    @ApiOperation(value = "App病害统计信息", httpMethod = "GET", notes = "App病害统计信息")
    public CommonResult<OrgDisease4AppVO> diseaseApp(@RequestParam String level, @RequestParam(required = false) String dimension, @RequestParam String date) throws Exception {
        return new CommonResult<OrgDisease4AppVO>(true, "App病害统计信息",diseaseManager.getDisease4AppCount(level,dimension,date) );

    }


    @GetMapping("road/list")
    @ApiOperation(value = "路段管理数据列表", httpMethod = "GET", notes = "路段管理数据列表")
    public CommonResult<List<Road>> listRoad(@RequestParam String token) throws Exception {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
            roadQueryWrapper.eq("is_dele_", "0");
            List<Road> list = roadManager.list(roadQueryWrapper);
            return new CommonResult<List<Road>>(true, "获取路段管理数据列表", list);
        } else {
            return new CommonResult<List<Road>>(false, "Token失效，请重新获取", null);
        }
    }

    @GetMapping("bridge/list")
    @ApiOperation(value = "桥梁数据列表", httpMethod = "GET", notes = "桥梁数据列表")
    public CommonResult<List<BridgeInformation>> listBridge(@RequestParam String token) throws Exception {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<BridgeInformation> roadQueryWrapper = new QueryWrapper<>();
            roadQueryWrapper.eq("is_dele_", "0");
            List<BridgeInformation> list = bridgeInformationManager.list(roadQueryWrapper);
//            List<BridgeInformation>  resultList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BridgeInformation :: getName))), ArrayList::new));
            return new CommonResult<List<BridgeInformation>>(true, "桥梁数据列表", list);
        } else {
            return new CommonResult<List<BridgeInformation>>(false, "Token失效，请重新获取", null);
        }
    }

    @GetMapping("route/list")
    @ApiOperation(value = "路线管理数据列表", httpMethod = "GET", notes = "获取路线管理列表")
    public CommonResult<List<Route>> listRoute(@RequestParam String token) throws Exception {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<Route> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_dele_", "0");
            List<Route> list = routeManager.list(queryWrapper);
            return new CommonResult<List<Route>>(true, "获取路线管理数据列表成功", list);
        } else {
            return new CommonResult<List<Route>>(false, "Token失效，请重新获取", null);
        }
    }

    @RequestMapping(value = "sideSlope/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "查询边坡信息", httpMethod = "GET")
    public CommonResult<List<SideSlopeInformation>> listSideSlope(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<SideSlopeInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_dele_", "0");
            List<SideSlopeInformation> list = sideSlopeInformationManager.list(queryWrapper);

            return new CommonResult<List<SideSlopeInformation>>(true, "获取路线管理数据列表成功", list);
        } else {
            return new CommonResult<List<SideSlopeInformation>>(false, "Token失效，请重新获取", null);
        }
    }

    @RequestMapping(value = "tunnel/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "查询隧道信息", httpMethod = "GET")
    public CommonResult<List<TunnelInformation>> listTunnel(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<TunnelInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_dele_", "0");
            List<TunnelInformation> list = tunnelInformationManager.list(queryWrapper);
//            List<TunnelInformation>  resultList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TunnelInformation :: getName))), ArrayList::new));
            return new CommonResult<List<TunnelInformation>>(true, "获取路线管理数据列表成功", list);
        } else {
            return new CommonResult<List<TunnelInformation>>(false, "Token失效，请重新获取", null);
        }
    }

    @RequestMapping(value = "roadsideFacilities/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "查询沿线设施信息", httpMethod = "GET")
    public CommonResult<List<BizRoadsideFacilities>> listRoadsideFacilities(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<BizRoadsideFacilities> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_dele_", "0");
            List<BizRoadsideFacilities> list = roadsideFacilitiesManager.list(queryWrapper);
            return new CommonResult<List<BizRoadsideFacilities>>(true, "获取路线管理数据列表成功", list);
        } else {
            return new CommonResult<List<BizRoadsideFacilities>>(false, "Token失效，请重新获取", null);
        }
    }

    @RequestMapping(value = "emergeMaterial/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "应急物资库", httpMethod = "GET")
    public CommonResult<List<BizEmergeMaterialManagement>> listEmergeMaterial(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {

            List<BizEmergeMaterialManagement> list = emergeMaterialManagementManager.list();
            return new CommonResult<List<BizEmergeMaterialManagement>>(true, "获取应急物资库列表成功", list);
        } else {
            return new CommonResult<List<BizEmergeMaterialManagement>>(false, "Token失效，请重新获取", null);
        }
    }
    @RequestMapping(value = "emergencyRescue/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "救援点", httpMethod = "GET")
    public CommonResult<List<BizEmergencyRescueManagement4OpenVO>> listEmergencyRescue(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {

            List<BizEmergencyRescueManagement> list = emergencyRescueManagementManager.list();

            List<BizEmergencyRescueManagement4OpenVO> rerurnList = new ArrayList<>();
            for (BizEmergencyRescueManagement model : list){
                BizEmergencyRescueManagement4OpenVO vo = new BizEmergencyRescueManagement4OpenVO();
                BeanUtils.copyProperties(model,vo);
                QueryWrapper<BizStructureVehicle> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("STRUCTURAL_ID_",vo.getId());
                vo.setNumber(bizStructureVehicleManager.list(queryWrapper).size());
                rerurnList.add(vo);
            }

            return new CommonResult<List<BizEmergencyRescueManagement4OpenVO>>(true, "获取救援点数据列表成功", rerurnList);
        } else {
            return new CommonResult<List<BizEmergencyRescueManagement4OpenVO>>(false, "Token失效，请重新获取", null);
        }
    }


    @RequestMapping(value = "maintenanceWorkArea/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "养护工区", httpMethod = "GET")
    public CommonResult<List<BizMaintenanceWorkArea>> listMaintenanceWorkArea(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {

            List<BizMaintenanceWorkArea> list = maintenanceWorkAreaManager.list();
            return new CommonResult<List<BizMaintenanceWorkArea>>(true, "获取养护工区数据列表成功", list);
        } else {
            return new CommonResult<List<BizMaintenanceWorkArea>>(false, "Token失效，请重新获取", null);
        }
    }

    @RequestMapping(value = "structureVehicle/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "养护工区、应急物资库、救援点的结构物车辆", httpMethod = "GET")
    public CommonResult<List<BizStructureVehicle>> listStructureVehicleManager(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {

            List<BizStructureVehicle> list = structureVehicleManager.list();
            return new CommonResult<List<BizStructureVehicle>>(true, "获取结构物车辆数据列表成功", list);
        } else {
            return new CommonResult<List<BizStructureVehicle>>(false, "Token失效，请重新获取", null);
        }
    }

    @RequestMapping(value = "materialsManagement/list", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "养护工区、应急物资库、救援点的物资类型及数量", httpMethod = "GET")
    public CommonResult<List<BizMaterialsManagement>> listMaterialsManagement(@RequestParam String token) {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {

            List<BizMaterialsManagement> list = materialsManagementManager.list();
            return new CommonResult<List<BizMaterialsManagement>>(true, "获取物资类型及数量数据列表成功", list);
        } else {
            return new CommonResult<List<BizMaterialsManagement>>(false, "Token失效，请重新获取", null);
        }
    }



    @GetMapping("culvert/list")
    @ApiOperation(value = "涵洞管理数据列表", httpMethod = "GET", notes = "获取涵洞管理列表")
    public CommonResult<List<BizCulvertInformation>> list(@RequestParam String token) throws Exception {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<BizCulvertInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_dele_", "0");
            List<BizCulvertInformation> list = bizCulvertInformationManager.list(queryWrapper);
            return new CommonResult<List<BizCulvertInformation>>(true, "获取路线管理数据列表成功", list);
        } else {
            return new CommonResult<List<BizCulvertInformation>>(false, "Token失效，请重新获取", null);
        }
    }

    @GetMapping("disease/list")
    @ApiOperation(value = "病害详情", httpMethod = "GET", notes = "病害详情")
    public CommonResult<List<Disease>> diseaseList(@RequestParam String token) throws Exception {
        boolean flag = this.checkToken(token);
        System.out.println(flag);
        if (flag) {
            QueryWrapper<Disease> queryWrapper = new QueryWrapper<>();
            List<Disease> list = diseaseManager.list(queryWrapper);
            return new CommonResult<List<Disease>>(true, "病害详情", list);
        } else {
            return new CommonResult<List<Disease>>(false, "Token失效，请重新获取", null);
        }
    }




    @RequestMapping(value = "getToken", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取token", httpMethod = "GET")
    public CommonResult<String> getToken(@RequestParam String accessKey) {

        boolean result = accessKeyList.stream().anyMatch(s -> s.equals(accessKey));
        System.out.println(result);
        if (result) {
            final Date createdDate = clock.now();
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("accessKey", accessKey);
            String token = Jwts.builder()
                    .setClaims(stringObjectHashMap)
                    .setSubject(accessKey)
                    .setIssuedAt(createdDate)
                    .setExpiration(new Date(createdDate.getTime() + jwtConfig.getExpiration() * 1000))
                    .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret())
                    .compact();
            return new CommonResult<>(true, "获取token成功", token);
        } else {
            return new CommonResult<>(false, "未授权的第三方，请联系管理员");
        }
    }

    //验证token是否正确
    private boolean checkToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtConfig.getSecret())
                    .parseClaimsJws(token)
                    .getBody();
            Object accessKey = claims.get("accessKey");
            return accessKeyList.stream().anyMatch(s -> s.equals(accessKey));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }





}
