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

import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.util.ObjectUtil;
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.category.vo.*;
import com.yc.ship.module.resource.dal.dataobject.category.CategoryDO;
import com.yc.ship.module.resource.enums.UseStatusEnum;
import com.yc.ship.module.resource.service.category.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
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.Comparator;
import java.util.List;
import java.util.Objects;
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/category")
@Validated
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    @PostMapping("/create")
    @Operation(summary = "创建资源-产品分类")
    @PreAuthorize("@ss.hasPermission('product:category:create')")
    public CommonResult<Long> createCategory(@Valid @RequestBody CategorySaveReqVO createReqVO) {
        return success(categoryService.createCategory(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新资源-产品分类")
    @PreAuthorize("@ss.hasPermission('product:category:update')")
    public CommonResult<Boolean> updateCategory(@Valid @RequestBody CategorySaveReqVO updateReqVO) {
        categoryService.updateCategory(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除资源-产品分类")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('product:category:delete')")
    public CommonResult<Boolean> deleteCategory(@RequestParam("id") Long id) {
        categoryService.deleteCategory(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得资源-产品分类")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    public CommonResult<CategoryRespVO> getCategory(@RequestParam("id") Long id) {
        return success(categoryService.getCategoryExtra(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得资源-产品分类分页")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    public CommonResult<PageResult<CategoryRespVO>> getCategoryPage(@Valid CategoryPageReqVO pageReqVO) {
        PageResult<CategoryRespVO> pageResultVO;
        if (pageReqVO.getTypeId() == null) {
            PageResult<CategoryDO> pageResult = categoryService.getCategoryPage(pageReqVO);
            pageResultVO = BeanUtils.toBean(pageResult, CategoryRespVO.class);
        } else {
            pageResultVO = categoryService.selectCategoryPage(pageReqVO);
        }
        return success(pageResultVO);
    }

    @GetMapping("/list")
    @Operation(summary = "获取资源-产品分类列表", description = "用于【资源分类管理】界面")
    @PreAuthorize("@ss.hasPermission('product:category:query')")
    public CommonResult<List<CategoryRespVO>> getList(CategoryListReqVO reqVO) {
        List<CategoryDO> list = categoryService.getCategoryList(reqVO);
        list.sort(Comparator.comparing(CategoryDO::getSortNum));
        List<CategoryRespVO> respVOS = BeanUtils.toBean(list, CategoryRespVO.class);
        respVOS = respVOS.stream().filter(item -> {
            CategoryRespVO extra = categoryService.getCategoryExtra(item.getId());
            CategoryExtraRespVO extraInfo = extra.getExtraInfo();
            if (Objects.isNull(reqVO.getTypeId()) || Objects.equals(0L, reqVO.getTypeId()) || Objects.equals(extraInfo.getType(), reqVO.getTypeId())) {
                item.setExtraInfo(extraInfo);
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return success(respVOS);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出资源-产品分类 Excel")
    @PreAuthorize("@ss.hasPermission('product:category:export')")
    @OperateLog(type = EXPORT,enable = false)
    public void exportCategoryExcel(@Valid CategoryPageReqVO pageReqVO,
                                    HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CategoryDO> list = categoryService.getCategoryPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "资源-产品分类.xls", "数据", CategoryRespVO.class,
                BeanUtils.toBean(list, CategoryRespVO.class));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取资源类型精简信息列表", description = "只包含被开启的类型，主要用于前端的下拉选项")
    public CommonResult<List<TreeNode>> getSimpleList(CategoryListReqVO reqVO) {
        if (ObjectUtil.isNull(reqVO.getType())) {
            reqVO.setType(0);
        }
        reqVO.setUseStatus(UseStatusEnum.ENABLE.getStatus());
        List<TreeNode> categoryTreeList = categoryService.getCategoryTreeList(reqVO);
        return success(categoryTreeList);
    }

    @GetMapping("list-num")
    @Operation(summary = "获取资源类型列表", description = "只包含被开启的类型，主要用于前端的下拉选项")
    public CommonResult<List<CategoryRespVO>> getListNum(CategoryPageReqVO reqVO) {
        return success(categoryService.selectListWithSupplierNum(reqVO));
    }

    @PostMapping("list-by-ids")
    @Operation(summary = "根据资源ids获取资源类型列表")
    public CommonResult<List<CategoryRespVO>> getListByIds(@RequestBody CategoryListReqVO reqVO) {
        return success(categoryService.getListByIds(reqVO));
    }

}
