package com.yc.ship.module.product.controller.admin.productSpu;

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.framework.tenant.core.context.TenantContextHolder;
import com.yc.ship.module.product.controller.admin.productSpu.groupVO.ProductGroupRespVO;
import com.yc.ship.module.product.controller.admin.productSpu.skuVO.ProductSkuRespVO;
import com.yc.ship.module.product.controller.admin.productSpu.spuVO.*;
import com.yc.ship.module.product.dal.dataobject.productSku.ProductSkuDO;
import com.yc.ship.module.product.dal.dataobject.productSpu.ProductSpuDO;
import com.yc.ship.module.product.service.productSpu.ProductSpuService;
import com.yc.ship.module.resource.controller.admin.category.vo.CategoryListReqVO;
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.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
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;
import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.PRODUCT;


@Tag(name = "管理后台 - 附加产品基础信息spu")
@RestController
@RequestMapping("/product/product-spu")
@Validated
public class ProductSpuController {

    @Resource
    private ProductSpuService productSpuService;

    @PostMapping("/create")
    @Operation(summary = "创建附加产品基础信息")
    @OperateLog(type = PRODUCT)
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:create','product:otc-spu:create')")
    public CommonResult<Long> createProductSpu(@Valid @RequestBody ProductSpuSaveReqVO createReqVO) {
        return success(productSpuService.createProductSpu(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新房间产品基础信息")
    @OperateLog(type = PRODUCT)
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:update','product:otc-spu:update')")
    public CommonResult<Boolean> updateProductSpu(@Valid @RequestBody ProductSpuSaveReqVO updateReqVO) {
        productSpuService.updateProductSpu(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除产品基础信息")
    @OperateLog(type = PRODUCT)
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:delete','product:otc-spu:delete')")
    public CommonResult<Boolean> deleteProductSpu(@RequestParam("id") Long id) {
        productSpuService.deleteProductSpu(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得产品基础信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:query','product:plat-spu:query')")
    public CommonResult<ProductSpuRespVO> getProductSpu(@RequestParam("id") Long id) {
        return success(productSpuService.getProductSpuResp(id,null,null,true));
    }

    @GetMapping("/page")
    @Operation(summary = "获得产品基础信息分页")
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:query','product:otc-spu:query')")
    public CommonResult<PageResult<ProductSpuRespVO>> getProductSpuPage(@Valid ProductSpuPageReqVO pageReqVO) {
        return success(productSpuService.getProductSpuPage(pageReqVO));
    }

    @GetMapping("/applet/page")
    @Operation(summary = "获得产品基础信息分页")
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:query','product:otc-spu:query')")
    public CommonResult<PageResult<ProductSpuRespVO>> getAppletProductPage(@Valid ProductSpuPageReqVO pageReqVO) {
        PageResult<ProductSpuRespVO> pageResult = productSpuService.getAppletProductPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ProductSpuRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出产品基础信息 Excel")
    @PreAuthorize("@ss.hasAnyPermissions('product:spu:export','product:otc-spu:export')")
    @OperateLog(type = EXPORT,enable = false)
    public void exportProductSpuExcel(@Valid ProductSpuPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProductSpuRespVO> list = productSpuService.getProductSpuPage(pageReqVO).getList();
        List<ProductSpuExcelVO> excelList = new ArrayList<>();
        for (ProductSpuRespVO spu : list) {
            ProductSpuExcelVO excelSpu = BeanUtils.toBean(spu, ProductSpuExcelVO.class);
            Set<String> strings = spu.getProductGroupList().stream().map(ProductGroupRespVO::getProductBaseName).collect(Collectors.toSet());
            StringJoiner sj = new StringJoiner("、");
            for (String s : strings) {
                sj.add(s);
            }
            excelSpu.setProjectNames(sj.toString());
            excelList.add(excelSpu);
        }
        // 导出 Excel
        ExcelUtils.write(response, "产品基础信息.xls", "数据", ProductSpuExcelVO.class, excelList);
    }

    @GetMapping("/list")
    @Operation(summary = "获得产品信息list")
    public CommonResult<List<ProductSpuSimpleVO>> list(@Valid ProductSpuPageReqVO pageReqVO) {
        return success(productSpuService.selectSimpleList(pageReqVO));
    }

    @GetMapping("/listByShipId")
    @Operation(summary = "获得产品信息list")
    public CommonResult<List<ProductSpuSimpleVO>> listByShipId(@RequestParam("shipId") Long shipId) {
        return success(productSpuService.listByShipId(shipId));
    }

    @GetMapping("/list-platform")
    @Operation(summary = "获得组合产品(平台分销的)",description = "可传租户id(其他参数无效)")
    public CommonResult<PageResult<ProductSpuRespVO>> listPlatform(@Valid ProductSpuPageReqVO pageReqVO) {
        Long tenantId = TenantContextHolder.getTenantId();
        if (ObjectUtil.isNull(pageReqVO.getTenantId())) {
            pageReqVO.setTenantId(tenantId);
        }
        return success(productSpuService.selectSpuListByTenantId(pageReqVO));
    }

    @PutMapping("/update-status")
    @Operation(summary = "更改状态")
    @OperateLog(type = PRODUCT)
    public CommonResult<Boolean> updateStatus(@Valid @RequestBody UpdateProductStatusVO updateReqVO) {
        productSpuService.updateStatus(updateReqVO.getId(),updateReqVO.getIsUse());
        return success(true);
    }


    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取精简信息列表", description = "只包含被开启的点位类型，主要用于前端的下拉选项")
    public CommonResult<List<ProductSpuSimpleRespVO>> getSimpleList(ProductSpuPageReqVO pageReqVO) {
        List<ProductSpuDO> list = productSpuService.getProductSpuListByStatus(pageReqVO.getCategoryId(), pageReqVO.getChannelId(), pageReqVO.getIsUse());
        return success(BeanUtils.toBean(list, ProductSpuSimpleRespVO.class));
    }

    @GetMapping("/category-and-spu-list")
    @Operation(summary = "获取产品分类和spu树")
    public CommonResult<List<TreeNode>> categoryAndSpuTree() {
        return success(productSpuService.getCategoryAndSpuList());
    }

    @GetMapping({"/distributor-product-list"})
    @Operation(summary = "获取分销的产品列表", description = "获取分销的产品列表树")
    public CommonResult<List<TreeNode>> getDistributorProductList() {
        return success( productSpuService.getDistributorProductSpuList());
    }

    @GetMapping("/getProductSpuListByCategory")
    @Operation(summary = "根据分类获取产品")
    public CommonResult<List<ProductSpuSimpleRespVO>> getProductSpuPage(@RequestParam Long categoryId) {
        return success(productSpuService.getProductSpuListByCategory(categoryId));
    }

    @PostMapping("/get-sku-list")
    @Operation(summary = "获得产品sku信息")
    @Parameter(name = "ids", description = "编号", required = true, example = "1024")
    public CommonResult<List<ProductSkuRespVO>> getProductSkuList(@RequestBody CategoryListReqVO reqVO) {
        List<ProductSkuDO> list = productSpuService.getProductSkuList(reqVO.getIds());
        return success(BeanUtils.toBean(list, ProductSkuRespVO.class));
    }
}
