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

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.constant.AttrType;
import com.tmerclub.cloud.common.product.constant.SearchType;
import com.tmerclub.cloud.common.product.vo.AttrVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.product.dto.AttrDTO;
import com.tmerclub.cloud.product.model.Attr;
import com.tmerclub.cloud.product.model.AttrValue;
import com.tmerclub.cloud.product.service.AttrService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 属性信息
 *
 * @author tmerclub
 * @date 2020-10-28 15:27:23
 */
@RestController("supplierAttrController")
@RequestMapping("/s/attr")
@Tag(name = "supplier-属性信息")
public class AttrController {

    @Autowired
    private AttrService attrService;


    @GetMapping("/page")
    @Operation(summary = "获取属性信息列表", description = "分页获取属性信息列表")
    public ServerResponseEntity<PageVO<AttrVO>> page(@Valid PageDTO pageDTO, AttrDTO attrDTO) {
        attrDTO.setSysType(AuthUserContext.get().getSysType());
        PageVO<AttrVO> attrPage = attrService.page(pageDTO, attrDTO);
        return ServerResponseEntity.success(attrPage);
    }

    @GetMapping
    @Operation(summary = "获取属性信息", description = "根据attrId获取属性信息")
    public ServerResponseEntity<AttrVO> getByAttrId(@RequestParam Long attrId) {
        return ServerResponseEntity.success(attrService.getByAttrId(attrId));
    }

    @PostMapping
    @Operation(summary = "保存属性信息", description = "保存属性信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody AttrDTO attrDTO) {
        Integer sysType = AuthUserContext.get().getSysType();
        attrDTO.setSysType(sysType);
        if (Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId()) && Objects.isNull(attrDTO.getAttrType())) {
            throw new LuckException("属性类型不能为空");
        }
        checkAttrInfo(attrDTO);
        attrService.save(attrDTO);
        removeCacheAttrUnionCategory(attrDTO.getCategoryIds());
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新属性信息", description = "更新属性信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody AttrDTO attrDTO) {
        checkAttrInfo(attrDTO);
        Attr attr = BeanUtil.map(attrDTO, Attr.class);
        if (CollUtil.isNotEmpty(attrDTO.getAttrValues())) {
            attr.setAttrValues(BeanUtil.mapAsList(attrDTO.getAttrValues(), AttrValue.class));
        }
        List<Long> categoryIds = null;
        if (Objects.equals(AttrType.BASIC.value(), attr.getAttrType())) {
            categoryIds = attrService.getAttrOfCategoryIdByAttrId(attrDTO.getAttrId());
            categoryIds.addAll(attrDTO.getCategoryIds());
        }
        attrDTO.setShopId(AuthUserContext.get().getTenantId());
        attrService.update(attrDTO);
        removeCacheAttrUnionCategory(categoryIds);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除属性信息", description = "根据属性信息id删除属性信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long attrId) {
        Integer sysType = AuthUserContext.get().getSysType();
        List<Long> categoryIds = attrService.getAttrOfCategoryIdByAttrId(attrId);
        if (CollUtil.isNotEmpty(categoryIds)) {
            removeCacheAttrUnionCategory(categoryIds);
        }
        attrService.deleteById(attrId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/get_attrs_by_category_id")
    @Operation(summary = "根据分类及属性类别获取属性列表", description = "根据分类及属性类别获取属性列表")
    @Parameter(name = "categoryId", description = "分类id", required = true)
    public ServerResponseEntity<List<AttrVO>> getAttrsByCategoryId(@RequestParam("categoryId") Long categoryId) {
        return ServerResponseEntity.success(attrService.getAttrsByCategoryIdAndAttrType(categoryId));
    }

    @GetMapping("/get_shop_attrs")
    @Operation(summary = "获取店铺中的销售属性", description = "获取店铺中的销售属性")
    public ServerResponseEntity<List<AttrVO>> getShopAttrs() {
        Integer sysType = AuthUserContext.get().getSysType();
        return ServerResponseEntity.success(attrService.getShopAttrs(AuthUserContext.get().getTenantId(), sysType));
    }

    /**
     * 校验属性数据
     *
     * @param attrDTO
     */
    private void checkAttrInfo(AttrDTO attrDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            attrDTO.setAttrType(AttrType.SALES.value());
        }
        if (Objects.equals(AttrType.SALES.value(), attrDTO.getAttrType())) {
            attrDTO.setSearchType(SearchType.NOT_SEARCH.value());
            return;
        }
        if (CollUtil.isEmpty(attrDTO.getCategoryIds())) {
            throw new LuckException("关联分类不能为空");
        }
        if (Objects.isNull(attrDTO.getSearchType())) {
            throw new LuckException("搜索属性不能为空");
        }
    }

    /**
     * 删除属性关联的分类缓存
     */
    private void removeCacheAttrUnionCategory(List<Long> categoryIds) {
        // 清除分类缓存
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId()) || CollUtil.isEmpty(categoryIds)) {
            return;
        }
        attrService.removeAttrByCategoryId(categoryIds);
    }

}
