package cn.estsh.i3plus.core.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.core.api.iservice.busi.IPersonnelService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysOrganizeService;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysOrganize;
import cn.estsh.i3plus.pojo.platform.repository.SysOrganizeRepository;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description : 组织业务接口实现
 * @Reference   :
 * @Author      : wei.peng
 * @Date        : 2018-10-22 16:58:42.957
 * @Modify      :
 **/
@Service
public class SysOrganizeService implements ISysOrganizeService {

    public static final Logger LOGGER = LoggerFactory.getLogger(SysOrganizeService.class);

    @Autowired
    private SysOrganizeRepository organizeRDao;

    @Autowired
    private CoreTreeService coreTreeService;

    @Autowired
    private IPersonnelService personnelService;

    @Override
    @ApiOperation(value = "更新组织",notes = "传入持久化组织对象，进行更新")
    public void updateSysOrganize(SysOrganize organize) {
        LOGGER.info("组织 ORGANIZE :{}", organize);
        // 唯一校验 CODE 相同 ID 不同 则视为相同
        List<SysOrganize> list = organizeRDao.findByProperty("organizeCode", organize.getOrganizeCode());
        if(null != list && list.size() > 0){
            for (SysOrganize org : list) {
                if(!org.getId().equals(organize.getId())){
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                            .setErrorCode(ImppExceptionEnum.IO_EXCEPTION.getCode())
                            .setErrorDetail("组织代码已存在")
                            .setErrorSolution("请重新输入组织代码")
                            .build();
                }
            }
        }

        // 父节点检查
        coreTreeService.doValidatorSysOrganizeParentId(organize);

        // 冗余父节点
        if(organize.getParentId() != null && organize.getParentId() > 0){
            SysOrganize org = getSysOrganizeById(organize.getParentId());
            ValidatorBean.checkNotNull(org,"上级组织信息不存在");

            organize.setParentNameRdd(org.getName());
        }

        // 更新数据
        organizeRDao.update(organize);
        // 修改冗余信息
        personnelService.refreshOrganizeRdd(organize.getId());
        personnelService.refreshUpdateOrganizeRdd(organize.getId());
    }

    @Override
    @ApiOperation(value = "修改组织状态",notes = "")
    public void updateSysOrganizeStatus(Long id, int status, SessionUser user) {
        LOGGER.info("组织 ORGANIZE  id:{} status:{} user:{}", id,status,user);
        SysOrganize organize = organizeRDao.getById(id);
        organize.setOrganizeStatus(status);
        organize.setModifyUser(user.getUserName());
        organizeRDao.update(organize);
    }

    @Override
    @ApiOperation(value = "删除组织信息",notes = "根据 ID 删除组织信息")
    public void deleteSysOrganizeById(Long id) {
        LOGGER.info("组织 ORGANIZE Key:{}", id);
        long count = organizeRDao.findByPropertyCount("parentId", id);
        if (count >= 1) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.IMPP.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("存在相关组织信息无法删除！")
                    .setErrorSolution("请先删除子集信息在操作")
                    .build();
        }
        // 检查引用关系
        personnelService.checkSysOrganizeRef(id);
        // 删除数据
        organizeRDao.deleteById(id);
    }

    @Override
    @ApiOperation(value = "删除组织信息",notes = "根据 ID 批量删除组织信息")
    public void deleteSysOrganizeByIds(Long[] ids) {
        List<SysOrganize> list = organizeRDao.findByHqlWhere(CoreHqlPack.packHqlIds("parentId", ids));
        if (list != null && list.size() >= 1) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("["+list.get(0).getParentNameRdd()+"]存在相关组织信息无法删除！")
                    .setErrorSolution("请先删除子集信息在操作")
                    .build();
        }else {
            // 检查引用关系
            for (Long id : ids) {
                personnelService.checkSysOrganizeRef(id);
            }
            organizeRDao.deleteByIds(ids);
        }
    }

    @Override
    @ApiOperation(value = "新增组织信息")
    public SysOrganize insertSysOrganize(SysOrganize organize) {
        LOGGER.info("组织 ORGANIZE :{}", organize);

        // 代码唯一校验
        long count = organizeRDao.findByPropertyCount("organizeCode", organize.getOrganizeCode());
        if(count <= 0){
            // 冗余信息
            if(organize.getParentId() != null && organize.getParentId() > 0){
                SysOrganize org = getSysOrganizeById(organize.getParentId());
                ValidatorBean.checkNotNull(org,"上级组织信息不存在");

                organize.setParentNameRdd(org.getName());
            }

            // 插入数据入库
            return organizeRDao.insert(organize);
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION.getCode())
                    .setErrorDetail("组织代码已存在")
                    .setErrorSolution("请重新输入组织代码")
                    .build();
        }
    }

    @Override
    @ApiOperation(value = "查询组织信息",notes = "查询所有组织信息")
    public List<SysOrganize> listSysOrganize() {
        LOGGER.info("组织 ORGANIZE find All");
        return organizeRDao.findAll();
    }

    @Override
    @ApiOperation(value = "查询组织信息",notes = "查询 组织信息(分页、组合)")
    public ListPager<SysOrganize> querySysOrganize(SysOrganize organize, Pager pager) {
        LOGGER.info("组织信息 SysOrganize find SysOrganize page");

        if(organize == null){
            //不传入实体对象，查询所有
            int count = organizeRDao.listCount();
            pager = PagerHelper.getPager(pager,count);
            return new ListPager(organizeRDao.listPager(pager),pager);
        }else {
            if(organize.getParentId() != null){
                SysOrganize parent = coreTreeService.getSysOrganizeTreeById(organize.getParentId());
                List<Long> childIds = coreTreeService.findSysOrganizeChildIds(parent);
                organize.setChildIdList(childIds);
            }

            //生成hql查询语句
            String hqlPack = CoreHqlPack.packHqlSysOrganize(organize);
            pager = PagerHelper.getPager(pager,organizeRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(organizeRDao.findByHqlWherePage(hqlPack + organize.orderBy(), pager),pager);
        }
    }

    @Override
    @ApiOperation(value = "查询组织信息",notes = "根据ID查询组织信息")
    public SysOrganize getSysOrganizeById(Long id) {
        LOGGER.info("组织 ORGANIZE find id:{}", id);
        return organizeRDao.getById(id);
    }

    @Override
    public long getSysOrganizeCount() {
        return organizeRDao.listCount();
    }
}
