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.ISysPositionService;
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.SysPosition;
import cn.estsh.i3plus.pojo.platform.repository.SysPositionRepository;
import cn.estsh.i3plus.pojo.platform.repository.SysUserRepository;
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 : yunhao
 * @Date : 2018-10-19 16:36
 * @Modify :
 **/
@Service
public class SysPositionService implements ISysPositionService {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysPositionService.class);

    @Autowired
    private SysPositionRepository positionRDao;

    @Autowired
    private CoreTreeService coreTreeService;

    @Autowired
    private SysUserRepository sysUserRDao;

    @Autowired
    private IPersonnelService personnelService;

    @Override
    @ApiOperation(value = "新增岗位信息")
    public SysPosition insertSysPosition(SysPosition position) {
        LOGGER.info("岗位信息 POSITION position:{}", position);
        // CODE 唯一校验
        long count = positionRDao.findByPropertyCount("positionCode", position.getPositionCode());
        if(count <= 0){
            // 查询父级岗位名称
            if (position.getParentId() != null && position.getParentId() > 0) {
                LOGGER.info("岗位信息 POSITION parentId:{}", position.getParentId());

                SysPosition parentSysPosition = positionRDao.getById(position.getParentId());
                ValidatorBean.checkNotNull(parentSysPosition,"上级岗位信息不存在");
                position.setParentNameRdd(parentSysPosition.getName());
            }

            // 添加岗位
            LOGGER.info("岗位信息 POSITION position:{}", position);
            return positionRDao.insert(position);
        }else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION.getCode())
                    .setErrorDetail("岗位代码已存在")
                    .setErrorSolution("请重新输入岗位代码")
                    .build();
        }
    }

    @Override
    @ApiOperation(value = "更新岗位信息")
    public void updateSysPosition(SysPosition position) {
        LOGGER.info("岗位信息 POSITION position:{}", position);

        // 唯一校验 CODE 相同 ID 不同 则视为相同
        List<SysPosition> list = positionRDao.findByProperty("positionCode", position.getPositionCode());
        if(null != list && list.size() > 0){
            for (SysPosition pos : list) {
                if(!pos.getId().equals(position.getId())){
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                            .setErrorCode(ImppExceptionEnum.IO_EXCEPTION.getCode())
                            .setErrorDetail("岗位代码已存在")
                            .setErrorSolution("请重新输入岗位代码")
                            .build();
                }
            }
        }

        // 父节点检查
        coreTreeService.doValidatorSysPositionParentId(position);

        // 查询父级岗位名称
        if (position.getParentId() != null  && position.getParentId() > 0) {
            LOGGER.info("岗位信息 POSITION parentId:{}", position.getParentId());
            SysPosition parentSysPosition = positionRDao.getById(position.getParentId());
            ValidatorBean.checkNotNull(parentSysPosition,"上级岗位信息不存在");

            position.setParentNameRdd(parentSysPosition.getName());
        }

        // 修改岗位信息
        LOGGER.info("岗位信息 POSITION position:{}", position);
        positionRDao.update(position);
        // 更新冗余信息
        personnelService.refreshPositionRdd(position.getId());
        personnelService.refreshUpdateRefSysUserInfoPositionRdd(position.getId());
    }

    @Override
    @ApiOperation(value = "删除岗位信息",notes = "根据ID 删除岗位信息")
    public void deleteSysPositionById(Long id) {
        LOGGER.info("岗位信息 POSITION id:{}", id);
        personnelService.checkSysPositionRef(id);

        positionRDao.deleteById(id);
    }

    @Override
    @ApiOperation(value = "删除岗位信息",notes = "根据ID 批量删除岗位信息")
    public void deleteSysPositionByIds(Long[] ids) {
        LOGGER.info("岗位信息 POSITION ids:{}", ids);
        // 检查是否存在引用关系
        for (Long id : ids) {
            personnelService.checkSysPositionRef(id);
        }
        positionRDao.deleteByIds(ids);

        for (Long id : ids) {
            personnelService.refreshUpdateRefSysUserInfoPositionRdd(id);
        }
    }

    @Override
    @ApiOperation(value = "新增岗位信息")
    public List listSysPosition() {
        LOGGER.info("岗位信息 SysPosition list");
        return positionRDao.list();
    }

    @Override
    @ApiOperation(value = "查询岗位信息",notes = "查询岗位信息 (分页，组合)")
    public ListPager<SysPosition> querySysPosition(SysPosition position, Pager pager) {
        LOGGER.info("岗位信息 SysPosition find SysPosition page");

        if(position == null){
            //不传入实体对象，查询所有
            int count = positionRDao.listCount();
            pager = PagerHelper.getPager(pager,count);
            return new ListPager(positionRDao.listPager(pager),pager);
        }else {
            //生成hql查询语句
            String hqlPack = CoreHqlPack.packHqlSysPosition(position);
            pager = PagerHelper.getPager(pager,positionRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(positionRDao.findByHqlWherePage(hqlPack + position.orderBy(), pager),pager);
        }
    }

    @Override
    @ApiOperation(value = "查询岗位信息",notes = "根据 ID 查询岗位信息")
    public SysPosition getSysPositionById(Long id) {
        LOGGER.info("岗位信息 SysPosition id:{}", id);
        return positionRDao.getById(id);
    }

    @Override
    @ApiOperation(value = "查询岗位信息",notes = "查询岗位信息 (分页，组合)")
    public ListPager findSysPositionByPager(SysPosition position, Pager pager) {
        LOGGER.info("岗位信息 SysPosition position", position);
        LOGGER.info("岗位信息 SysPosition pager:{}", pager);

        if (position == null) {
            pager = PagerHelper.getPager(pager, positionRDao.listCount());
            return new ListPager(positionRDao.listPager(pager),pager);
        } else {
            String hqlPack = CoreHqlPack.packHqlSysPosition(position);
            pager = PagerHelper.getPager(pager, positionRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(positionRDao.findByHqlWherePage(hqlPack + position.orderBy(),pager),pager);
        }
    }



}
