package com.yc.ship.module.resource.controller.admin.route;

import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.util.ObjectUtil;
import com.yc.ship.framework.common.util.collection.CollectionUtils;
import com.yc.ship.framework.common.util.collection.MapUtils;
import com.yc.ship.module.resource.controller.admin.category.vo.CategoryListReqVO;
import com.yc.ship.module.resource.dal.dataobject.dock.ResourceDockDO;
import com.yc.ship.module.resource.dal.dataobject.scenic.ResourceScenicDO;
import com.yc.ship.module.resource.enums.UseStatusEnum;
import com.yc.ship.module.resource.service.dock.ResourceDockService;
import com.yc.ship.module.resource.service.scenic.ResourceScenicService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import static com.yc.ship.framework.common.pojo.CommonResult.success;

import com.yc.ship.framework.excel.core.util.ExcelUtils;

import com.yc.ship.framework.apilog.core.annotation.ApiAccessLog;
import static com.yc.ship.framework.apilog.core.enums.OperateTypeEnum.*;

import com.yc.ship.module.resource.controller.admin.route.vo.*;
import com.yc.ship.module.resource.dal.dataobject.route.ResourceRouteDO;
import com.yc.ship.module.resource.service.route.ResourceRouteService;

@Tag(name = "管理后台 - 航线管理")
@RestController
@RequestMapping("/resource/route")
@Validated
public class ResourceRouteController {

    @Resource
    private ResourceRouteService routeService;

    @Resource
    private ResourceDockService dockService;

    @Resource
    private ResourceScenicService scenicService;

    @PostMapping("/create")
    @Operation(summary = "创建航线管理")
    @PreAuthorize("@ss.hasPermission('resource:route:create')")
    public CommonResult<Long> createRoute(@Valid @RequestBody ResourceRouteSaveReqVO createReqVO) {
        return success(routeService.createRoute(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新航线管理")
    @PreAuthorize("@ss.hasPermission('resource:route:update')")
    public CommonResult<Boolean> updateRoute(@Valid @RequestBody ResourceRouteSaveReqVO updateReqVO) {
        routeService.updateRoute(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除航线管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('resource:route:delete')")
    public CommonResult<Boolean> deleteRoute(@RequestParam("id") Long id) {
        routeService.deleteRoute(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得航线管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('resource:route:query')")
    public CommonResult<ResourceRouteRespVO> getRoute(@RequestParam("id") Long id) {
        ResourceRouteDO route = routeService.getRoute(id);
        return success(BeanUtils.toBean(route, ResourceRouteRespVO.class));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取航线精简信息列表", description = "获取航线精简信息列表，主要用于前端的下拉选项")
    public CommonResult<List<ResourceRouteDO>> getSimpleList() {
        List<ResourceRouteDO> resourceRouteDOList = routeService.getRouteList();
        return success(resourceRouteDOList);
    }

    @GetMapping("/page")
    @Operation(summary = "获得航线管理分页")
    @PreAuthorize("@ss.hasPermission('resource:route:query')")
    public CommonResult<PageResult<ResourceRouteRespVO>> getRoutePage(@Valid ResourceRoutePageReqVO pageReqVO) {
        PageResult<ResourceRouteDO> pageResult = routeService.getRoutePage(pageReqVO);
        PageResult<ResourceRouteRespVO> page = BeanUtils.toBean(pageResult, ResourceRouteRespVO.class);
        List<ResourceRouteRespVO> list = page.getList();
        List<Long> scenicIds = new ArrayList<>();
        List<Long> dockIdList = CollectionUtils.convertList(list, ResourceRouteRespVO::getOnDockId);
        dockIdList.addAll(CollectionUtils.convertList(list, ResourceRouteRespVO::getLeaveDockId));
        list.stream().forEach(item -> {
            String midwayDockIds = item.getMidwayDockIds();
            if (StringUtils.isNotEmpty(midwayDockIds)) {
                dockIdList.addAll(Arrays.asList(midwayDockIds.split(",")).stream().map(Long::parseLong).collect(Collectors.toList()));
            }
            String relationScenicIds = item.getRelationScenicIds();
            if(StringUtils.isNotBlank(relationScenicIds)) {
                scenicIds.addAll(Arrays.asList(relationScenicIds.split(",")).stream().map(Long::parseLong).collect(Collectors.toList()));
            }
        });
        List<ResourceDockDO> dockList = dockService.getList(dockIdList);
        Map<Long, ResourceDockDO> longResourceDockDOMap = CollectionUtils.convertMap(dockList, ResourceDockDO::getId);

        List<ResourceScenicDO> scenicList = scenicService.getList(scenicIds);
        Map<Long, ResourceScenicDO> longResourceScenicDOMap = CollectionUtils.convertMap(scenicList, ResourceScenicDO::getId);
        list.stream().forEach(item -> {
            MapUtils.findAndThen(longResourceDockDOMap, item.getOnDockId(), dock -> item.setOnDockName(dock.getName()));
            MapUtils.findAndThen(longResourceDockDOMap, item.getLeaveDockId(), dock -> item.setLeaveDockName(dock.getName()));
            List<Long> ids = Arrays.asList(item.getMidwayDockIds().split(",")).stream().map(Long::parseLong).collect(Collectors.toList());
            String names = ids.stream().map(id -> longResourceDockDOMap.get(id).getName()).collect(Collectors.joining(","));
            item.setMidwayDockNames(names);

            List<Long> scenicIdList = Arrays.asList(item.getRelationScenicIds().split(",")).stream().map(Long::parseLong).collect(Collectors.toList());
            String scenicNames = scenicIdList.stream().map(id -> longResourceScenicDOMap.get(id).getName()).collect(Collectors.joining(","));
            item.setRelationScenicNames(scenicNames);
        });



        return success(page);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出航线管理 Excel")
    @PreAuthorize("@ss.hasPermission('resource:route:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRouteExcel(@Valid ResourceRoutePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ResourceRouteDO> list = routeService.getRoutePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "航线管理.xls", "数据", ResourceRouteRespVO.class,
                        BeanUtils.toBean(list, ResourceRouteRespVO.class));
    }

}