package com.hfkj.service.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.dao.BsIndustryMapper;
import com.hfkj.entity.BsIndustry;
import com.hfkj.entity.BsIndustryExample;
import com.hfkj.service.BsIndustryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hurui
 */
@Service("industryService")
public class BsIndustryServiceImpl implements BsIndustryService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private BsIndustryMapper industryMapper;

    @Override
    public List<BsIndustry> getCacheIndustry() {
        Object data = redisUtil.get("INDUSTRY_DATA");
        if (data != null) {
            return (List<BsIndustry>)data;
        }
        BsIndustryExample example = new BsIndustryExample();
        example.createCriteria().andStatusNotEqualTo(0).andParentIdIsNull();
        List<BsIndustry> industryList = industryMapper.selectByExample(example);
        for (BsIndustry industry : industryList) {
            industry.setChildIndustry(listChildIndustry(industry.getId()));
        }
        redisUtil.set("INDUSTRY_DATA", industryList);
        return industryList;
    }

    @Override
    public BsIndustry getDetailById(Long id) {
        return industryMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<BsIndustry> listChildIndustry(Long parentId) {
        BsIndustryExample example = new BsIndustryExample();
        example.createCriteria().andStatusNotEqualTo(0).andParentIdEqualTo(parentId);
        return industryMapper.selectByExample(example);
    }

    @Override
    public Map<String, BsIndustry> getChildIndustry(Long childId) {
        BsIndustry childIndustry = industryMapper.selectByPrimaryKey(childId);
        if (childIndustry != null) {
            Map<String, BsIndustry> map = new HashMap<>();
            map.put("child", childIndustry);
            if (childIndustry.getParentId() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "不是子行业数据");
            }
            map.put("parent", industryMapper.selectByPrimaryKey(childIndustry.getParentId()));
            return map;
        }
        return null;
    }
}
