package com.mvc.service.dic;

import com.mvc.dao.DicMarkTypeMapper;
import com.mvc.entity.DicMarkType;
import com.mvc.entity.DicMarkTypeExample;
import com.mvc.model.DicMarkTypeModel;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class DicMarkTypeService {
    @Resource
    private DicMarkTypeMapper dicMarkTypeMapper;

    public List<DicMarkTypeModel> findAllDicMarkType() {
        List<DicMarkTypeModel> resList = findDicMarkTypesByParentId(0);
        for (DicMarkTypeModel model : resList) {
            List<DicMarkTypeModel> child=findDicMarkTypesByParentId(model.getId());
            model.setChildList(child);
        }
        return resList;
    }

    /**
     * 根据parentId查询下属列表
     * @param parentId
     * @return
     */
    public List<DicMarkTypeModel> findDicMarkTypesByParentId(int parentId){
        DicMarkTypeExample example=new DicMarkTypeExample();
        DicMarkTypeExample.Criteria criteria=example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        return selectByExample(example);
    }

    private List<DicMarkTypeModel> selectByExample(DicMarkTypeExample example){
        List<DicMarkType> dicMarkTypes = dicMarkTypeMapper.selectByExample(example);
        List<DicMarkTypeModel> resList = new ArrayList<>();
        for (DicMarkType DicMarkType : dicMarkTypes) {
            DicMarkTypeModel model = new DicMarkTypeModel();
            BeanUtils.copyProperties(DicMarkType, model);
            resList.add(model);
        }
        return resList;
    }

    public DicMarkTypeModel saveDicMarkType(DicMarkTypeModel model) {
        model.setCreateTime(new Date());
        DicMarkType dicMarkType = new DicMarkType();
        BeanUtils.copyProperties(model, dicMarkType);
        int insert = dicMarkTypeMapper.insert(dicMarkType);
        model.setId(dicMarkType.getId());
        return model;
    }

    public DicMarkTypeModel updateDicMarkType(DicMarkTypeModel model) {
        DicMarkType dicMarkType = dicMarkTypeMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, dicMarkType);
        int i = dicMarkTypeMapper.updateByPrimaryKey(dicMarkType);
        return model;
    }

    public int deleteDicMarkType(int id) {
        int i = dicMarkTypeMapper.deleteByPrimaryKey(id);
        return i;
    }

    /**
     * 根据ID获取Model
     * @param id
     * @return
     */
    public DicMarkTypeModel findDicMarkTypeModelById(int id){
        DicMarkType dicMarkType = dicMarkTypeMapper.selectByPrimaryKey(id);
        if(dicMarkType!=null){
            DicMarkTypeModel model=new DicMarkTypeModel();
            BeanUtils.copyProperties(dicMarkType,model);
            return model;
        }
        return null;
    }
}
