
package com.tmerclub.cloud.product.controller.admin;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.product.constant.CategoryLevel;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.i18n.I18nMessage;
import com.tmerclub.cloud.common.product.vo.CategoryVO;
import com.tmerclub.cloud.common.product.vo.app.CategoryAppVO;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.ExcelUtil;
import com.tmerclub.cloud.product.dto.CategoryDTO;
import com.tmerclub.cloud.product.service.CategoryService;
import com.tmerclub.cloud.product.vo.CategoryExcelVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 分类信息
 *
 * @author tmerclub
 * @date 2020-10-28 15:27:24
 */
@RestController("adminCategoryController")
@RequestMapping("/mp/category")
@Tag(name = "admin-分类信息")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @GetMapping
    @Operation(summary = "获取分类信息", description = "根据categoryId获取分类信息")
    public ServerResponseEntity<CategoryVO> getByCategoryId(@RequestParam Long categoryId) {
        return ServerResponseEntity.success(categoryService.getInfo(categoryId));
    }

    @PostMapping
    @Operation(summary = "保存分类信息", description = "保存分类信息")
    public ServerResponseEntity<Long> save(@Valid @RequestBody CategoryDTO categoryDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId()) && categoryDTO.getLevel() > CategoryLevel.SECOND.value()) {
            throw new LuckException("分类等级最高只能为二级分类");
        }
        Long shopId = AuthUserContext.get().getTenantId();
        Integer getSysType = AuthUserContext.get().getSysType();
        categoryDTO.setShopId(shopId);
        Long categoryId = categoryService.save(categoryDTO);
        categoryService.removeCategoryCache(shopId, null, getSysType);
        return ServerResponseEntity.success(categoryId);
    }

    @PutMapping
    @Operation(summary = "更新分类信息", description = "更新分类信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody CategoryDTO categoryDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        Integer getSysType = AuthUserContext.get().getSysType();
        categoryDTO.setShopId(shopId);
        categoryService.update(categoryDTO);
        categoryService.removeCategoryCache(AuthUserContext.get().getTenantId(), categoryDTO.getCategoryId(), getSysType);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除分类信息", description = "根据分类信息id删除分类信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long categoryId) {
        Integer sysType = AuthUserContext.get().getSysType();
        CategoryVO category = categoryService.getById(categoryId);
        if (Objects.isNull(category)) {
            throw new LuckException("当前分类不存在，请刷新后重试");
        }
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(category.getShopId(), shopId)) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        categoryService.deleteById(categoryId, shopId);
        if (Objects.equals(sysType, SysTypeEnum.PLATFORM.value())) {
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.MULTISHOP.value());
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.PLATFORM.value());
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.SUPPLIER.value());
        } else if (Objects.equals(sysType, SysTypeEnum.MULTISHOP.value())) {
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.MULTISHOP.value());
        } else if (Objects.equals(sysType, SysTypeEnum.SUPPLIER.value())) {
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.SUPPLIER.value());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/platform_categories")
    @Operation(summary = "获取平台所有的分类信息", description = "获取所有的分类列表信息")
    public ServerResponseEntity<List<CategoryAppVO>> platformCategories() {
        return ServerResponseEntity.success(categoryService.platformCategories());
    }

    @GetMapping("/shop_categories")
    @Operation(summary = "获取店铺所有的分类信息", description = "获取店铺所有的分类信息")
    public ServerResponseEntity<List<CategoryAppVO>> shopCategories() {
        return ServerResponseEntity.success(categoryService.list(AuthUserContext.get().getTenantId()));
    }

    @GetMapping("/enable_categories")
    @Operation(summary = "获取平台/店铺启用的分类信息", description = "仅获取启用的分类，以及包含三级分类的分类信息")
    public ServerResponseEntity<List<CategoryAppVO>> enableCategories(Long shopId) {
        if (Objects.isNull(shopId) || !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            shopId = AuthUserContext.get().getTenantId();
        }
        List<CategoryAppVO> categories = categoryService.shopCategoryList(shopId, I18nMessage.getLang());
        List<CategoryAppVO> categoryList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (CategoryAppVO primaryCategoryVO : categories) {
            categoryList.add(primaryCategoryVO);
            if (!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
                categoryList.addAll(primaryCategoryVO.getCategories());
                continue;
            }
            for (CategoryAppVO secondaryCategory : primaryCategoryVO.getCategories()) {
                categoryList.add(secondaryCategory);
                categoryList.addAll(secondaryCategory.getCategories());
            }
        }
        return ServerResponseEntity.success(categoryList);
    }

    @PutMapping("/category_enable_or_disable")
    @Operation(summary = "分类的启用或禁用", description = "分类的启用或禁用")
    public ServerResponseEntity<Boolean> categoryEnableOrDisable(@RequestBody CategoryDTO categoryDTO) {
        Integer sysType = AuthUserContext.get().getSysType();
        List<Long> categoryIds = categoryService.categoryEnableOrDisable(categoryDTO, sysType);
        // 批量更新
        Long tenantId = AuthUserContext.get().getTenantId();
        if (CollUtil.isNotEmpty(categoryIds)) {
            categoryIds.forEach(id -> categoryService.removeCategoryCache(tenantId, id, sysType));
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/soldExcel")
    @Operation(summary = "导出excel", description = "导出分类excel")
    public ServerResponseEntity<Void> spuSoldExcel(HttpServletResponse response) {
        Long shopId = AuthUserContext.get().getTenantId();
        List<CategoryExcelVO> list = categoryService.listExcel(shopId);
        ExcelUtil.soleExcel(response, list, CategoryExcelVO.EXCEL_NAME, CategoryExcelVO.MERGE_ROW_INDEX, CategoryExcelVO.MERGE_COLUMN_INDEX, CategoryExcelVO.class);
        return ServerResponseEntity.success();
    }
}
