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

import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.framework.operatelog.core.annotations.OperateLog;
import com.yc.ship.module.resource.controller.admin.car.vo.CarTypeNumRespVO;
import com.yc.ship.module.resource.controller.admin.cartype.vo.*;
import com.yc.ship.module.resource.dal.dataobject.cartype.CarTypeDO;
import com.yc.ship.module.resource.enums.UseStatusEnum;
import com.yc.ship.module.resource.service.car.CarService;
import com.yc.ship.module.resource.service.cartype.CarTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yc.ship.framework.common.pojo.CommonResult.success;
import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;


@Tag(name = "管理后台 - 车辆类型管理")
@RestController
@RequestMapping("/resource/car-type")
@Validated
public class CarTypeController {

    @Resource
    private CarTypeService carTypeService;
    @Resource
    private CarService carService;

    @PostMapping("/create")
    @Operation(summary = "创建车辆类型管理")
    @PreAuthorize("@ss.hasPermission('dispatch:car-type:create')")
    public CommonResult<String> createCarType(@Valid @RequestBody CarTypeSaveReqVO createReqVO) {
        return success(carTypeService.createCarType(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新车辆类型管理")
    @PreAuthorize("@ss.hasPermission('dispatch:car-type:update')")
    public CommonResult<Boolean> updateCarType(@Valid @RequestBody CarTypeSaveReqVO updateReqVO) {
        carTypeService.updateCarType(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除车辆类型管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('dispatch:car-type:delete')")
    public CommonResult<Boolean> deleteCarType(@RequestParam("id") String id) {
        carTypeService.deleteCarType(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得车辆类型管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('dispatch:car-type:query')")
    public CommonResult<CarTypeRespVO> getCarType(@RequestParam("id") String id) {
        CarTypeDO carType = carTypeService.getCarType(id);
        return success(BeanUtils.toBean(carType, CarTypeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得车辆类型管理分页")
    @PreAuthorize("@ss.hasPermission('dispatch:car-type:query')")
    public CommonResult<PageResult<CarTypeRespVO>> getCarTypePage(@Valid CarTypePageReqVO pageReqVO) {
        PageResult<CarTypeDO> pageResult = carTypeService.getCarTypePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, CarTypeRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出车辆类型管理 Excel")
    @PreAuthorize("@ss.hasPermission('dispatch:car-type:export')")
    @OperateLog(type = EXPORT)
    public void exportCarTypeExcel(@Valid CarTypePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CarTypeDO> list = carTypeService.getCarTypePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "车辆类型管理.xls", "数据", CarTypeRespVO.class,
                        BeanUtils.toBean(list, CarTypeRespVO.class));
    }

    @GetMapping(value = {"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取车辆类型精简信息列表", description = "列表数据以树结构展示")
    public CommonResult<List<CarTypeSimpleRespVO>> getSimpleCarTypeList(@RequestParam("isTree") String isTree) {
        List<CarTypeDO> list = carTypeService.getCarTypeList(
                CarTypeReqVO.builder().useStatus(UseStatusEnum.ENABLE.getStatus()).build());
        List<CarTypeSimpleRespVO> respList = BeanUtils.toBean(list, CarTypeSimpleRespVO.class);
        if (!respList.isEmpty() && isTree.equals("true")) {
            respList.forEach(c -> c.setParentId("root"));
            respList.add(CarTypeSimpleRespVO.builder().id("root").name("车辆类型").parentId("0").build());
        }
        return success(respList);
    }

    @GetMapping(value = {"/list-type_tree_stacs"})
    @Operation(summary = "获取车辆类型精简信息列表-按车辆类型统计数量", description = "列表数据以树结构展示")
    public CommonResult<List<CarTypeSimpleRespVO>> getSimpleCarTypeListTree(@RequestParam("isTree") String isTree) {
        List<CarTypeDO> list = carTypeService.getCarTypeList(
                CarTypeReqVO.builder().useStatus(UseStatusEnum.ENABLE.getStatus()).build());
        List<CarTypeSimpleRespVO> respList = BeanUtils.toBean(list, CarTypeSimpleRespVO.class);
        if(CollectionUtils.isNotEmpty(respList)){
            List<CarTypeNumRespVO> carTypeNumRespVOList =carService.getstatiscisCarTypeNum();
            // 将carTypeNumRespVOList转换为map
            if(CollectionUtils.isNotEmpty(carTypeNumRespVOList)){
                Map<String, Integer> carTypeMap = carTypeNumRespVOList.stream().collect(Collectors.toMap(CarTypeNumRespVO::getCarTypeId, CarTypeNumRespVO::getCarTypeNum));
                for (CarTypeSimpleRespVO carTypeSimpleRespVO : respList) {
                    carTypeSimpleRespVO.setCarTypeNum(MapUtils.getIntValue(carTypeMap,carTypeSimpleRespVO.getId(),0));
                }
            }else {
                for (CarTypeSimpleRespVO carTypeSimpleRespVO : respList) {
                    carTypeSimpleRespVO.setCarTypeNum(0);
                }
            }

        }
        if (!respList.isEmpty() && isTree.equals("true")) {
            respList.forEach(c -> c.setParentId("root"));
            respList.add(CarTypeSimpleRespVO.builder().id("root").name("车辆类型").parentId("0").build());
        }
        return success(respList);
    }
}