package com.patzn.lims.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.sys.entity.SysOrg;
import com.patzn.lims.sys.entity.SysUser;
import com.patzn.lims.sys.mapper.SysOrgMapper;
import com.patzn.lims.sys.service.ISysOrgService;
import com.patzn.lims.sys.service.ISysUserService;
import com.patzn.lims.sys.vo.SysOrgVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 组织表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-08-02
 */
@Service
public class SysOrgServiceImpl extends BaseServiceImpl<SysOrgMapper, SysOrg> implements ISysOrgService {

    @Autowired
    private ISysUserService sysUserService;


    @Override
    public Page<SysOrgVO> page(Page<SysOrgVO> page, SysOrg sysOrg) {
        if (null != sysOrg.getId()) {
            // 递归分页情况
            return pageRecursive(page, sysOrg);
        }
        return page.setRecords(baseMapper.selectPageVo(page, sysOrg));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(SysOrg entity) {
        if (null == entity) {
            return false;
        }
        return super.save(entity);
    }


    @Override
    public Page<SysOrgVO> pageRecursive(Page<SysOrgVO> page, SysOrg sysOrg) {
        return page.setRecords(baseMapper.selectPageRecursive(page, sysOrg));
    }


    @Override
    public List<SysOrg> list(SysOrg sysOrg) {
        return list(Wrappers.query(sysOrg.setStatus(1)));
    }


    @Override
    public List<SysOrg> lisByOrgNames(Collection<String> orgNames, Long companyId) {
        QueryWrapper<SysOrg> wrapper = Wrappers.<SysOrg>query().select("id", "pid", "name");
        wrapper.eq("company_id", companyId);
        wrapper.in("name", orgNames);
        return super.list(wrapper);
    }


    @Override
    public SysOrgVO getVoById(Long companyId, Long id) {
        return baseMapper.selectVoById(companyId, id);
    }


    @Override
    public List<SysOrg> getOrgTree(String name) {
        QueryWrapper<SysOrg> wrapper = Wrappers.<SysOrg>query().select("id", "pid", "name");
        wrapper.eq("company_id", LoginHelper.getAccount().getCompanyId());
        wrapper.eq("status", 1).orderByAsc("sort");
        wrapper.like(StringUtils.isNotEmpty(name), "name", name);
        return list(wrapper);
    }


    @Override
    public SysOrg getByUserId(Long userId) {
        return baseMapper.selectOneByUserId(userId);
    }

    @Override
    public List<SysOrg> listByUserRealName(String realName) {
        SysUser sysUser = sysUserService.getByRealName(realName);
        if (null == sysUser) {
            return null;
        }
        return baseMapper.selectListByUserId(sysUser.getId());
    }

    @Override
    public boolean initRoot(Long companyId, String companyName) {
        SysOrg sysOrg = new SysOrg();
        sysOrg.setCompanyId(companyId);
        sysOrg.setName(companyName);
        sysOrg.setPid(null);
        sysOrg.setRemark("企业组织关系树");
        sysOrg.setStatus(1);
        return super.save(sysOrg);
    }

    @Override
    public boolean updateById(SysOrg sysOrg) {
        if (null == sysOrg || null == sysOrg.getId()) {
            return false;
        }
        SysOrg temp = getById(sysOrg.getId());
        PtAssert.fail(null == temp, "选择组织不存在请联系管理员");
        if (null == temp.getPid()) {
            // 初始化的父组织不能设置 PID
            sysOrg.setPid(null);
        }
        return super.updateById(sysOrg);
    }


    @Override
    public String getNamesByUserId(Long userId) {
        return baseMapper.selectNamesByUserId(userId);
    }


    @Override
    public boolean importOrg(MultipartFile file, Account account) {
//        Collection<OrgETO> orgs = ExcelUtils.readSheetAtOne(OrgETO.class, file, "导入组织失败");
//        if (CollectionUtils.isEmpty(orgs)) {
//            return false;
//        }
//
//        // 正确性检查
//        orgs.forEach(o -> {
//            PtAssert.fail(StringUtils.isEmpty(o.getName()), "组织名称不能为空");
//            PtAssert.fail(o.getName().equals(o.getParent()), "上级组织【" + o.getParent() + "】不能为与当前组织名称重复");
//        });
//
//        AtomicReference<Long> superId = new AtomicReference<>();
//        Map<String, Long> orgMap = new HashMap<>(16);
//        List<SysOrg> orgList = super.list(Wrappers.<>query().eq("company_id", account.getCompanyId()));
//        orgList.forEach(o -> {
//            if (null == superId.get() && null == o.getPid()) {
//                superId.set(o.getId());
//            }
//            if (null == orgMap.get(o.getName())) {
//                orgMap.put(o.getName(), o.getId());
//            }
//        });
//
//        // 赋值组织父 ID
//        orgs.forEach(o -> {
//            o.setId(IdWorker.getId());
//            if (StringUtils.isEmpty(o.getParent())) {
//                o.setPid(superId.get());
//            } else {
//                Long pid = orgMap.get(o.getParent());
//                if (null != pid) {
//                    o.setPid(pid);
//                }
//            }
//            // 当前导入的对象存入 MAP
//            if (null == orgMap.get(o.getName())) {
//                orgMap.put(o.getName(), o.getId());
//            }
//        });
//
//        List<SysOrg> sysOrgList = new ArrayList<>();
//
//        // 处理导入的子父级关系
//        orgs.forEach(o -> {
//            SysOrg sysOrg = new SysOrg();
//            sysOrg.setId(o.getId());
//            sysOrg.setName(o.getName());
//            sysOrg.setStatus(StatusEnum.NORMAL);
//            sysOrg.setCompanyId(account.getCompanyId());
//            sysOrg.setSort(o.getSort());
//            if (null == o.getPid()) {
//                Long pid = orgMap.get(o.getParent());
//                if (null != pid) {
//                    sysOrg.setPid(pid);
//                }
//            } else {
//                sysOrg.setPid(o.getPid());
//            }
//            sysOrgList.add(sysOrg);
//        });
//
//        return super.saveBatch(sysOrgList);
        return false;
    }

    @Override
    public boolean updateRootName(String name, Long companyId) {
        SysOrg sysOrg = new SysOrg();
        sysOrg.setName(name);
        return super.update(sysOrg, Wrappers.<SysOrg>query()
                .eq("company_id", companyId)
                .eq("pid", 0));
    }

    @Override
    public List<SysOrg> getListByUserId(Long e) {
        return baseMapper.selectListByUserId(e);
    }
}
