package cn.ey.biz.module.system.api.category.v2;

import cn.ey.biz.common.exception.util.ServiceExceptionUtil;
import cn.ey.biz.common.pojo.R;
import cn.ey.biz.common.util.i18n.I18nContextHolder;
import cn.ey.biz.module.system.api.category.CategoryDataV2Api;
import cn.ey.biz.module.system.api.category.dto.CategoryDataV2ReqDTO;
import cn.ey.biz.module.system.api.category.dto.CategoryDataV2RespDTO;
import cn.ey.biz.module.system.api.category.dto.CategorySyncReq;
import cn.ey.biz.module.system.service.category.CategorySyncService;
import cn.ey.biz.module.system.service.category.v2.CategoryDataV2Service;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

import static cn.ey.biz.common.pojo.R.success;
import static cn.ey.biz.module.system.enums.ApiConstants.VERSION;
import static cn.ey.biz.module.system.enums.ErrorCodeConstants.ACCEPT_LANGUAGE_NOT_NULL;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@DubboService(version = VERSION) // 提供 Dubbo RPC 接口，给 Dubbo Consumer 调用
@Validated
public class CategoryDataV2ApiImpl implements CategoryDataV2Api {

    @Resource
    private CategoryDataV2Service categoryDataService;

    @Resource
    private CategorySyncService categorySyncService;

    @Override
    public R<List<CategoryDataV2RespDTO>> getCategoryData(@Valid CategoryDataV2ReqDTO req) {
        String acceptLanguage = I18nContextHolder.getLangId();
        if (StringUtils.isEmpty(req.getAcceptLanguage()) && StringUtils.isEmpty(acceptLanguage)) {
            throw ServiceExceptionUtil.exception(ACCEPT_LANGUAGE_NOT_NULL);
        }
        if (StringUtils.isEmpty(req.getAcceptLanguage())) {
            req.setAcceptLanguage(acceptLanguage);
        }
        List<CategoryDataV2RespDTO> result ;
        if (req.isNonCacheable()) {
            result = categoryDataService.getCategoryDataNonCache(req);
        } else {
            result = categoryDataService.getCategoryData(req);
        }
        return R.success(result);
    }

    @Override
    public R<Boolean> dictSync(CategorySyncReq syncReq) {
        categorySyncService.dictSync(syncReq);
        return  R.success(Boolean.TRUE);
    }

    @Override
    public R<Map<String, List<Map<String, Object>>>> listDefaultCategoryDataByCategoryCodes(String statusName, List<String> categoryCodeList) {
        return success(categoryDataService.listDefaultCategoryDataByCodesAndStatusName(categoryCodeList, statusName));
    }
}
