package cn.com.countrygarden.bi.main.service.resident.impl;

import cn.com.countrygarden.bi.main.dao.resident.ContractTypeMapper;
import cn.com.countrygarden.bi.main.model.resident.ContractConstant;
import cn.com.countrygarden.bi.main.model.resident.ContractType;
import cn.com.countrygarden.bi.main.service.resident.ContractTypeService;
import cn.com.countrygarden.bi.main.util.RedisCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenweijiang on 2017/11/13.
 */
@Service
@Transactional(readOnly = true)
public class ContractTypeServiceImpl implements ContractTypeService {

    @Autowired
    private ContractTypeMapper mapper;

    @Override
    public List<ContractType> listAll() {
        List<ContractType> resultList = RedisCacheUtils.remeberList(ContractConstant.ContractType.CACHE_KEY, ContractConstant.ContractType.EXPIRED_TIME, new HashMap<String, String>(), ContractType.class,
                p -> {
                    ContractType query = new ContractType();
                    query.setIsDelete(false);
                    return mapper.select(query);
                }
        );

        return resultList;
    }

    /**
     * 级联分类列表
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> cascade() {
        List<Map<String, Object>> cascades = new ArrayList<>();
        Map<String, List<Map<String, Object>>> items = new HashMap<>();

        List<ContractType> contractTypes = listAll();
        for (ContractType contractType : contractTypes) {
            String parentCode = contractType.getParentCode();
            if (!items.containsKey(parentCode)) {
                items.put(parentCode, new ArrayList<>());
            }

            List<Map<String, Object>> children = items.get(parentCode);
            children.add(new HashMap<String, Object>() {{
                put("label", contractType.getCode());
                put("value", contractType.getName());
            }});
        }

        for (Map.Entry<String, List<Map<String, Object>>> entry : items.entrySet()) {
            String parentCode = entry.getKey();
            Map<String, Object> item = new HashMap<>();
            item.put("value", parentCode);
            item.put("label", parentCode);
            item.put("children", entry.getValue());

            cascades.add(item);
        }

        return cascades;
    }
}
