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

import cn.com.countrygarden.bi.main.dao.PreCommMapper;
import cn.com.countrygarden.bi.main.model.PreComm;
import cn.com.countrygarden.bi.main.model.PreOrgan;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.PreCommService;
import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.service.PreOrganService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
@Transactional
public class PreCommServiceImpl extends AbstractService<PreComm> implements PreCommService {
    @Resource
    private PreCommMapper mapper;

    @Resource
    private PreOrganService preOrganService;

    public PreComm findByUk(Map<String, Object> param) {
        return mapper.findByUk(param);
    }

    public PreComm findOrCreate(String commName, String organName, TbSysUser sysUser) {
        PreOrgan preOrgan = preOrganService.findOrCreate(organName, sysUser);

        PreComm preComm = findByUk(new HashMap<String, Object>() {{
            put("name", commName);
            put("organId", preOrgan.getId());
        }});

        if (preComm == null) {
            preComm = new PreComm();
            preComm.setName(commName);
            preComm.setOrganId(preOrgan.getId());
            preComm.setCreateBy(sysUser.getUserCode());
            preComm.setModifiedBy(sysUser.getUserCode());
            Date date = new Date();
            preComm.setGmtCreate(date);
            preComm.setGmtModified(date);

            save(preComm);
        }

        return preComm;
    }
}
