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

import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.dao.common.OrganMapper;
import cn.com.countrygarden.bi.main.model.common.Organ;
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.common.OrganService;
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 OrganServiceImpl extends AbstractService<Organ> implements OrganService {
    @Resource
    private OrganMapper mapper;
    @Resource
    private TbSysOrganService tbSysOrganService;

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

        return organ;
    }
}
