/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.platform.api.dict.service;

import com.alibaba.fastjson.JSONObject;
import com.hzbank.testteam.autotest.dependencies.monsterDependency.vo.ResponseVO;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.saas.cache.StaticTenantCache;
import net.northking.cctp.common.util.DateUtil;
import net.northking.cctp.platform.bus.feign.HzBankFeign;
import net.northking.cctp.platform.constants.PlatformAppError;
import net.northking.cctp.platform.db.entity.CltDictCatalog;
import net.northking.cctp.platform.db.entity.CltDictItem;
import net.northking.cctp.platform.dto.bus.DictItem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典目录服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "CltDictCatalogApiServiceImpl")
public class CltDictCatalogApiServiceImpl implements CltDictCatalogApiService {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(CltDictCatalogApiServiceImpl.class);

    @Autowired
    private HzBankFeign hzBankFeign;

    @Override
    public List<CltDictItem> query(String tenantId, String catalogCode) {
        List<CltDictItem> result = new ArrayList<>();
        ResponseVO<List<DictItem>> responseVO = hzBankFeign.getDictItemByCode(catalogCode);
        logger.info("调用monster字典接口返回：{}", JSONObject.toJSONString(responseVO));
        if (StringUtils.equals(responseVO.getCode(),"success")) {
            List<DictItem> dictItemList = responseVO.getData();
            if (CollectionUtils.isEmpty(dictItemList)) {
                return result;
            } else {
                List<DictItem> notDeletedDictItemList = dictItemList.stream().filter(dictItem -> dictItem.getIsDeleted() == 0
                        && dictItem.getIsEnabled() == 1).collect(Collectors.toList());
                notDeletedDictItemList.forEach(dictItem -> {
                    CltDictItem cltDictItem = new CltDictItem();
                    BeanUtils.copyProperties(dictItem,cltDictItem);
                    cltDictItem.setId(String.valueOf(dictItem.getId()));
                    cltDictItem.setItemCode(dictItem.getCode());
                    cltDictItem.setItemName(dictItem.getName());
                    if (dictItem.getUpdater()!=null) {
                        cltDictItem.setUpdatedBy(String.valueOf(dictItem.getUpdater()));
                    }
                    if (dictItem.getCreator()!=null) {
                        cltDictItem.setCreatedBy(String.valueOf(dictItem.getCreator()));
                    }
                    cltDictItem.setEnabled(dictItem.getIsEnabled() == 1);
                    cltDictItem.setIdx(dictItem.getInnerOrder());
                    cltDictItem.setCatalogId(String.valueOf(dictItem.getCatalogId()));
                    if (!StringUtils.isEmpty(dictItem.getCreateTime())) {
                        try {
                            cltDictItem.setCreatedTime(DateUtil.parse(dictItem.getCreateTime()));
                        }catch (Exception e){
                            logger.error("日期格式话错误，createtime，{}",dictItem.getCreateTime());
                        }

                    }
                    if (!StringUtils.isEmpty(dictItem.getUpdateTime())) {
                        try {
                            cltDictItem.setUpdatedTime(DateUtil.parse(dictItem.getUpdateTime()));
                        }catch (Exception e){
                            logger.error("日期格式话错误，updateTime，{}",dictItem.getUpdateTime());
                        }
                    }
                    result.add(cltDictItem);
                });
            }
            return result;
        } else {
            logger.error("从monster获取字典项失败，response，{}" ,responseVO.toString());
            throw new PlatformRuntimeException(PlatformAppError.GET_DICT_FROM_HZBANK_FAIL);
        }
    }


    @Override
    public List<CltDictItem> queryItem(CltDictCatalog cltDictCatalog) {
        return this.query(StaticTenantCache.getDefaultTenantId(), cltDictCatalog.getCatalogCode());
    }

}
