package com.yd.base.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.constant.CodeGeneratorConstants;
import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.CodeGenerator;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.base.api.service.ApiCategoryService;
import com.yd.base.feign.request.category.ApiCategoryAddRequest;
import com.yd.base.feign.request.category.ApiCategoryEditRequest;
import com.yd.base.feign.request.category.ApiCategoryPageRequest;
import com.yd.base.feign.request.category.ApiCategoryTreeListRequest;
import com.yd.base.feign.response.category.ApiCategoryDetailResponse;
import com.yd.base.feign.response.category.ApiCategoryPageResponse;
import com.yd.base.feign.response.category.ApiCategoryTreeListResponse;
import com.yd.base.service.dto.CategoryDto;
import com.yd.base.service.model.Category;
import com.yd.base.service.service.ICategoryService;
import com.yd.user.service.model.SysDept;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

@Slf4j
@Service
public class ApiCategoryServiceImpl implements ApiCategoryService {

    @Autowired
    private ICategoryService iCategoryService;

    /**
     * 分页列表查询-分类
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiCategoryPageResponse>> page(ApiCategoryPageRequest request) {
        Page<ApiCategoryPageResponse> page = new Page<>(request.getPageNo(), request.getPageSize());
        IPage<ApiCategoryPageResponse> iPage = iCategoryService.page(page, request);
        return Result.success(iPage);
    }

    /**
     * 树形列表查询-分类
     * @param request
     * @return
     */
    @Override
    public Result<List<ApiCategoryTreeListResponse>> treeList(ApiCategoryTreeListRequest request) {
        return null;
    }

    /**
     * 添加分类
     * @param request
     * @return
     */
    @Override
    public Result add(ApiCategoryAddRequest request) {
        //校验分类名称的唯一性
        List<Category> categoryList = iCategoryService.queryList(CategoryDto.builder()
                .name(request.getName())
                .build());
        if (!CollectionUtils.isEmpty(categoryList)) {
            throw new BusinessException("分类名称已存在");
        }
        Category category = new Category();
        category.setCategoryBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_CATEGORY.getCode()));
        //分类编码
        category.setCode(CodeGenerator.generate10Code(CodeGeneratorConstants.PREFIX_CATEGORY_CODE));
        category.setPid(request.getPid());
        category.setName(request.getName());
        //分类层级
        category.setLevel(calculateLevel(request.getPid()));
        //父子路径
        category.setPath(calculatePath(request.getPid(),category.getCategoryBizId()));
        category.setRemark(request.getRemark());
        category.setType(request.getType());
        iCategoryService.saveOrUpdate(category);
        return Result.success();
    }

    /**
     * 编辑分类
     * @param request
     * @return
     */
    @Override
    public Result edit(ApiCategoryEditRequest request) {
        //查询分类信息是否存在
        Result<Category> result = checkCategoryIsExist(request.getCategoryBizId());
        Category category = result.getData();
        //校验分类名称的唯一性
        List<Category> categoryList = iCategoryService.queryList(CategoryDto.builder()
                .name(request.getName())
                .categoryBizId(request.getCategoryBizId())
                .isExcludeMy(true)
                .build());
        if (!CollectionUtils.isEmpty(categoryList)) {
            throw new BusinessException("分类名称已存在");
        }
        category.setPid(request.getPid());
        category.setName(request.getName());
        //分类层级
        category.setLevel(calculateLevel(request.getPid()));
        //父子路径
        category.setPath(calculatePath(request.getPid(),category.getCategoryBizId()));
        category.setRemark(request.getRemark());
        category.setType(request.getType());
        iCategoryService.saveOrUpdate(category);
        return Result.success();
    }

    /**
     * 详情-分类
     * @param categoryBizId 分类表唯一业务ID
     * @return
     */
    @Override
    public Result<ApiCategoryDetailResponse> detail(String categoryBizId) {
        //查询分类信息是否存在
        Result<Category> result = checkCategoryIsExist(categoryBizId);
        Category category = result.getData();

        ApiCategoryDetailResponse response = new ApiCategoryDetailResponse();
        BeanUtils.copyProperties(category,response);
        return Result.success(response);
    }

    /**
     * 删除-分类
     * @param categoryBizId 分类表唯一业务ID
     * @return
     */
    @Override
    public Result del(String categoryBizId) {
        return null;
    }

    /**
     * 根据父级层级计算当前层级
     * @param pid 父id
     * @return
     */
    public Integer calculateLevel(String pid) {
        if (StringUtils.isBlank(pid) || "0".equals(pid)) {
            //当前层级是第一级
            return 1;
        }
        Category category = iCategoryService.queryOne(CategoryDto.builder().categoryBizId(pid).build());
        return category.getLevel() + 1;
    }

    /**
     * 根据父级路径计算当前路径
     * @param pid 父id
     * @param categoryBizId 当前业务唯一id
     * @return
     */
    public String calculatePath(String pid,String categoryBizId) {
        if (StringUtils.isBlank(pid) || "0".equals(pid)) {
            //当前层级是第一级
            return categoryBizId;
        }
        Category category = iCategoryService.queryOne(CategoryDto.builder().pid(pid).build());
        return category.getPath() + "&" + categoryBizId;
    }

    /**
     * 校验分类是否存在
     * @param categoryBizId
     * @return
     */
    public Result<Category> checkCategoryIsExist(String categoryBizId) {
        Category category = iCategoryService.queryOne(CategoryDto.builder().categoryBizId(categoryBizId).build());
        if (Objects.isNull(category)) {
            //数据不存在
            throw new BusinessException("分类数据不存在");
        }
        return Result.success(category);
    }
}
