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

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

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


@Service
@Transactional
public class PreOrganServiceImpl extends AbstractService<PreOrgan> implements PreOrganService {
    @Resource
    private PreOrganMapper mapper;
    @Resource
    private TbSysOrganService tbSysOrganService;


    public PreOrgan findByUk(String name) {
        return mapper.findByUk(name);
    }

    public PreOrgan findOrCreate(String name, TbSysUser sysUser) {
        PreOrgan preOrgan = mapper.findByUk(name);
        if (preOrgan == null) {
            String organCode = "";
            TbSysOrgan sysOrgan = tbSysOrganService.findByOrganName(name);
            if (sysOrgan != null) {
                organCode = sysOrgan.getOrganCode();
            }
            preOrgan = new PreOrgan();
            preOrgan.setName(name);
            preOrgan.setOrganCode(organCode);
            preOrgan.setCreateBy(sysUser.getUserCode());
            preOrgan.setModifiedBy(sysUser.getUserCode());
            Date date = new Date();
            preOrgan.setGmtCreate(date);
            preOrgan.setGmtModified(date);
            save(preOrgan);
        }

        return preOrgan;
    }
}
