package com.kingtom.shengtai.api.controller;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.kingtom.kirin.app.system.utils.SystemUtils;
import com.kingtom.kirin.core.common.CommonConst;
import com.kingtom.kirin.core.common.base.PageInfo;
import com.kingtom.kirin.core.common.base.Result;
import com.kingtom.kirin.core.common.utils.CollectionUtils;
import com.kingtom.kirin.core.common.utils.JsonUtils;
import com.kingtom.shengtai.api.mapper.ProductDirMapper;
import com.kingtom.shengtai.api.model.ProductDirDTO;
import com.kingtom.shengtai.api.model.ProductDirTreeDTO;
import com.kingtom.shengtai.app.srm.model.ProductDir;
import com.kingtom.shengtai.app.srm.service.IProductDirService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 应用模块名称</p>
 * 产品目录表 控制层。</p>
 * Copyright: Copyright (C) 2024 , Inc. All rights reserved. <p>
 * Company: 成都诚唐科技有限责任公司</p>
 *
 * @author wany
 * @since 2024/01/17
 */
@RestController
@Tag(name = "ProductDirController", description = "产品目录表 控制层。")
@RequestMapping("/product_dirs")
public class ProductDirController{

    @Autowired
    private IProductDirService productDirService;

    @Operation(summary = "新建产品目录表")
    @PostMapping("/")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<ProductDirDTO> addProductDir(@RequestBody ProductDirDTO dto){
        ProductDir productDir = ProductDirMapper.INSTANCE.convert(dto);
        productDir.setSysId(SystemUtils.getCurrentSystemId());
        productDir = productDirService.create(productDir);
        if(productDir == null){
            Result.ok(null);
        }
        return Result.ok(ProductDirMapper.INSTANCE.convert(productDir));
    }

    @Operation(summary = "更新产品目录表")
    @PostMapping("/{id}/info")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<ProductDirDTO> updateProductDir(@PathVariable("id") String id, @RequestBody ProductDirDTO dto){
        ProductDir productDir = ProductDirMapper.INSTANCE.convert(dto);
        productDir.setId(id);
        productDir = productDirService.update(productDir);
        if(productDir == null){
            Result.ok(null);
        }
        return Result.ok(ProductDirMapper.INSTANCE.convert(productDir));
    }

    @Parameter(name = "id", description = "产品目录表Id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "删除产品目录表")
    @PostMapping("/{id}/")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<String> deleteProductDir(@PathVariable("id") String id){
        productDirService.deleteById(id);
        return Result.ok("操作成功！");
    }

    @Operation(summary = "批量删除产品目录表")
    @PostMapping("/delete/")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<String> deleteProductDirs(@RequestBody String json){
        List<String> ids = JsonUtils.toObjectList(json, String.class);
        productDirService.deleteByIds(ids);
        return Result.ok("操作成功！");
    }

    @Parameter(name = "id", description = "产品目录表Id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "根据id查找产品目录表")
    @GetMapping("/{id}/info")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<ProductDirDTO> findProductDir(@PathVariable("id") String id){
        ProductDir productDir = productDirService.findById(id);
        return Result.ok(ProductDirMapper.INSTANCE.convert(productDir));
    }

    @Parameter(name = "ids", description = "产品目录表Ids,多个id用英文逗号隔开", in = ParameterIn.QUERY, required = true)
    @Operation(summary = "根据id集合批量查找产品目录表")
    @GetMapping("/batch_info")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<List<ProductDirDTO>> findProductDirs(@RequestParam("ids") String ids){
        List<ProductDir> dirs = productDirService.findByIds(List.of(ids.split(CommonConst.COMMA_STRING)));
        List<ProductDirDTO> collect = dirs.stream().map(ProductDirMapper.INSTANCE::convert)
                                          .collect(Collectors.toList());
        collect.sort(Comparator.comparingInt(e -> ids.indexOf(e.getId())));
        return Result.ok(collect);
    }

    @Operation(summary = "分页查询产品目录表")
    @Parameters({@Parameter(name = "query", description = "搜索内容", in = ParameterIn.QUERY, required = false),
            @Parameter(name = "pageNum", description = "当前页", in = ParameterIn.QUERY, required = true),
            @Parameter(name = "pageSize", description = "每页数据条数", in = ParameterIn.QUERY, required = true)})
    @GetMapping("/page")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<PageInfo<ProductDirDTO>> getProductDirPage(String query, int pageNum, int pageSize){
        String search = null;
        if(StringUtils.isNotBlank(query)){
            Map<String, String> map = JsonUtils.toObject(query, Map.class);
            search = map.get("search");
        }
        Page<ProductDir> page = productDirService.page(search, pageNum, pageSize);
        PageInfo<ProductDirDTO> r = CollectionUtils.convertPage(page, ProductDirMapper.INSTANCE::convert);
        return Result.ok(r);
    }

    @Operation(summary = "产品目录树")
    @GetMapping("/tree")
    @SaCheckPermission(value = {"AuthMenu:srm_products:Execute"})
    public Result<List<ProductDirTreeDTO>> getProductDirTree(){
        List<ProductDir> list = productDirService.list();
        List<ProductDirDTO> dtoList =
                list.stream().map(ProductDirMapper.INSTANCE::convert).collect(Collectors.toList());
        return Result.ok(ProductDirTreeDTO.build(dtoList));
    }

    @Operation(summary = "产品目录树")
    @GetMapping("/tree_noauth")
    public Result<List<ProductDirTreeDTO>> getProductDirTreeWithOutAuth(){
        List<ProductDir> list = productDirService.list();
        List<ProductDirDTO> dtoList =
                list.stream().map(ProductDirMapper.INSTANCE::convert).collect(Collectors.toList());
        return Result.ok(ProductDirTreeDTO.build(dtoList));
    }

    @Operation(summary = "产品目录对应的供应商数量")
    @Parameter(name = "filterNoSupplier", description = "是否过滤总数为0的数据，默认为true", in = ParameterIn.QUERY,
            required = false)
    @GetMapping("/supplierCountGroupByProduct")
    public Result<List<Map<String, Object>>> getSupplierCountGroupByProduct(
            @RequestParam(name = "filterNoSupplier", defaultValue = "true") Boolean filterNoSupplier){
        List<Map<String, Object>> map = productDirService.findSupplierCountGroupByProduct(filterNoSupplier);
        return Result.ok(map);
    }

}
