package com.artfess.yhxt.businessdata.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.base.util.JsonUtil;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.manager.OrgManager;
import com.artfess.uc.model.Org;
import com.artfess.uc.params.org.OrgVo;
import com.artfess.yhxt.basedata.dao.RoadDao;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.Road;
import com.artfess.yhxt.businessdata.model.Company;
import com.artfess.yhxt.businessdata.dao.CompanyDao;
import com.artfess.yhxt.businessdata.manager.CompanyManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.businessdata.vo.CompanyVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import net.hasor.utils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 养护单位 服务实现类
 *
 * @author wangping
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-05
 */
@Service
public class CompanyManagerImpl extends BaseManagerImpl<CompanyDao, Company> implements CompanyManager {
    @Resource
    OrgManager orgManager;
    @Resource
    OrgDao orgDao;
    @Resource
    BaseContext baseContext;
    @Resource
    RoadDao roadDao;

    @Override
    public PageList<Company> queryCompany(QueryFilter<Company> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();

        IPage<Company> result = baseMapper.getCompany(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<Company>(result);
    }

    @Override
    public void removeCompanyByIds(List<String> list,String code) throws Exception {
        this.orgManager.deleteOrg(code);
        this.removeByIds(list);
    }

    @Override
    @Transactional
    public void saveCompany(Company company) throws Exception {
        OrgVo orgVo = new OrgVo();
        orgVo.setName(company.getName());
        orgVo.setCode(company.getCode());
        orgVo.setParentId(company.getParentId());
        orgVo.setGrade(company.getGrade());
        orgVo.setOrgKind(company.getOrgKind());
        orgVo.setDemId(company.getDemId());
        orgVo.setOrderNo(company.getOrderNo());
        orgVo.setLimitNum(company.getLimitNum());
        orgVo.setNowNum(company.getNowNum());
        orgVo.setExceedLimitNum(company.getExceedLimitNum());
        CommonResult<String> result = this.orgManager.addOrg(orgVo);

        Map<String,Object>  map= JsonUtil.toMap(result.getValue());

        company.setId(map.get("id").toString());
        company.setPath(map.get("path").toString());
        company.setPathName(map.get("pathName").toString());

        this.create(company);
    }

    @Override
    @Transactional
    public void updateCompany(Company company) throws Exception {
        OrgVo orgVo = new OrgVo();
        orgVo.setName(company.getName());
        orgVo.setCode(company.getCode());
        orgVo.setParentId(company.getParentId());
        orgVo.setGrade(company.getGrade());
        orgVo.setOrgKind(company.getOrgKind());
        orgVo.setDemId(company.getDemId());
        orgVo.setOrderNo(company.getOrderNo());
        orgVo.setLimitNum(company.getLimitNum());
        orgVo.setNowNum(company.getNowNum());
        orgVo.setExceedLimitNum(company.getExceedLimitNum());
        CommonResult<String> result = this.orgManager.updateOrg(orgVo);

        Map<String,Object>  map= JsonUtil.toMap(result.getValue());

        company.setPath(map.get("path").toString());
        company.setPathName(map.get("pathName").toString());
        this.update(company);
    }

    @Override
    public List<CompanyVo> getTree(String demId, List<String> grades) {
        QueryWrapper<Org> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(demId), "DEM_ID_", demId);
        queryWrapper.eq("IS_DELE_", "0");
        List<Org> orgs = this.orgDao.selectList(queryWrapper);
        //根
        List<CompanyVo> vos = new ArrayList<CompanyVo>();
        List<CompanyVo> rootMenu = new ArrayList<CompanyVo>();
        for (Org org : orgs) {
            CompanyVo vo = new CompanyVo();
            vo.setCode(org.getCode());
            vo.setId(org.getId());
            vo.setName(org.getName());
            vo.setParentId(org.getParentId());
            vo.setCode(org.getCode());
            vo.setGrade(org.getGrade());
            vo.setOrgKind(org.getOrgKind());
            vo.setDemId(org.getDemId());
            vo.setOrderNo(org.getOrderNo());
            vo.setPath(org.getPath());
            vo.setPathName(org.getPathName());
            if(grades != null && grades.size() > 0 && StringUtils.isNotBlank(org.getGrade()) && grades.contains(org.getGrade())){
                vo.setDisabled(true);
            }else {
                vo.setDisabled(false);
            }
            vos.add(vo);

        }
        for (CompanyVo vo : vos) {
            if ("0".equals(vo.getParentId())) { //父节点是0的，为根节点。
                rootMenu.add(vo);
            }
        }
        for (CompanyVo menu : rootMenu) {
            List<CompanyVo> child = getChild(menu.getId(), vos);
            menu.setChildren(child);
        }

        return rootMenu;
    }



    @Override
    public List<Org> getCompany(QueryFilter queryFilter) {
        QueryWrapper<Org> orgQueryWrapper = new QueryWrapper<>();
        String currentOrgId = baseContext.getCurrentOrgId();
        Org org = this.orgManager.getById(currentOrgId);
        List<Org> orgs;
        List<Org> orgList = new ArrayList<>();
        //admin 没有组织ID
        if (StringUtils.isEmpty(currentOrgId)){
            orgQueryWrapper.eq("grade_","1");
            orgQueryWrapper.eq("parent_id_","0");
            orgQueryWrapper.eq("is_dele_",0);
            orgQueryWrapper.eq("org_kind_","ogn");
             //orgList = this.orgManager.getBaseMapper().selectList(orgQueryWrapper);
            List<Org> o = this.orgManager.getBaseMapper().selectList(orgQueryWrapper);
            String id = o.get(0).getId();

            orgList.addAll(this.baseMapper.getOrgsByparentId(id));
        }
        //公司等级为1 是总公司
        if (org!=null && org.getGrade().equals("1") && org.getOrgKind().equals("ogn")) {
            String id = org.getId();
            orgs = this.baseMapper.getOrgsByparentId(id);
            orgList.addAll(orgs);
        }
        //等级为2是分公司
        if (org!=null &&org.getGrade().equals("2")&& org.getOrgKind().equals("ogn") ){

            orgQueryWrapper.eq("ID_",org.getId());
            orgs = this.orgManager.getBaseMapper().selectList(orgQueryWrapper);
            orgList.addAll(orgs);
        }

        return orgList;
    }

    @Override
    public List<CompanyVo> getTreeNewCompany(String demId) {
        QueryWrapper<Org> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(demId), "DEM_ID_", demId);
        queryWrapper.eq("IS_DELE_", "0");
        queryWrapper.eq("ORG_KIND_", "ogn");
        queryWrapper.like("CODE_","10");
        List<Org> orgs = this.orgDao.selectList(queryWrapper);
        //根
        List<CompanyVo> vos = new ArrayList<CompanyVo>();
        List<CompanyVo> rootMenu = new ArrayList<CompanyVo>();
        for (Org org : orgs) {
            CompanyVo vo = new CompanyVo();
            vo.setCode(org.getCode());
            vo.setId(org.getId());
            vo.setName(org.getName());
            vo.setParentId(org.getParentId());
            vo.setCode(org.getCode());
            vo.setGrade(org.getGrade());
            vo.setOrgKind(org.getOrgKind());
            vo.setDemId(org.getDemId());
            vo.setOrderNo(org.getOrderNo());
            vo.setPath(org.getPath());
            vo.setPathName(org.getPathName());

            vo.setDisabled(false);
            if (org!=null &&org.getGrade().equals("3")&& org.getOrgKind().equals("ogn") ){
                QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
                roadQueryWrapper.eq("COMPANY_ID",org.getId());
                for (Road road : roadDao.selectList(roadQueryWrapper)){
                    CompanyVo roadVo = new CompanyVo();
                    roadVo.setParentId(org.getId());
                    roadVo.setCode(road.getCode());
                    roadVo.setId(road.getId());
                    roadVo.setName(road.getName());
                    roadVo.setCode(road.getCode());
                    vos.add(roadVo);
                }

            }

            vos.add(vo);

        }
        for (CompanyVo vo : vos) {
            if ("0".equals(vo.getParentId())) { //父节点是0的，为根节点。
                rootMenu.add(vo);
            }
        }
        for (CompanyVo menu : rootMenu) {
            List<CompanyVo> child = getChild(menu.getId(), vos);
            menu.setChildren(child);
        }

        return rootMenu;
    }

    @Override
    public List<CompanyVo> getTreeCompany(String demId) {
        QueryWrapper<Org> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(demId), "DEM_ID_", demId);
        queryWrapper.eq("IS_DELE_", "0");
        queryWrapper.eq("ORG_KIND_", "ogn");
        queryWrapper.like("CODE_","10");
        List<Org> orgs = this.orgDao.selectList(queryWrapper);
        //根
        List<CompanyVo> vos = new ArrayList<CompanyVo>();
        List<CompanyVo> rootMenu = new ArrayList<CompanyVo>();
        for (Org org : orgs) {
            CompanyVo vo = new CompanyVo();
            vo.setCode(org.getCode());
            vo.setId(org.getId());
            vo.setName(org.getName());
            vo.setParentId(org.getParentId());
            vo.setCode(org.getCode());
            vo.setGrade(org.getGrade());
            vo.setOrgKind(org.getOrgKind());
            vo.setDemId(org.getDemId());
            vo.setOrderNo(org.getOrderNo());
            vo.setPath(org.getPath());
            vo.setPathName(org.getPathName());

            vo.setDisabled(false);

            vos.add(vo);

        }
        for (CompanyVo vo : vos) {
            if ("0".equals(vo.getParentId())) { //父节点是0的，为根节点。
                rootMenu.add(vo);
            }
        }
        for (CompanyVo menu : rootMenu) {
            List<CompanyVo> child = getChild(menu.getId(), vos);
            menu.setChildren(child);
        }

        return rootMenu;
    }

    //@Override
    public List<Org> getCompany() {
        QueryWrapper<Org> orgQueryWrapper = new QueryWrapper<>();
        String currentOrgId = baseContext.getCurrentOrgId();
        Org org = this.orgManager.getById(currentOrgId);
        List<Org> orgs = new ArrayList<>();
        //admin 没有组织ID
        if (StringUtils.isEmpty(currentOrgId)){
            orgQueryWrapper.eq("grade_","1");
            orgQueryWrapper.eq("parent_id_","0");
            orgQueryWrapper.eq("is_dele_",0);
            List<Org> orgList = this.orgManager.getBaseMapper().selectList(orgQueryWrapper);
            String id = orgList.get(0).getId();

            orgs = this.orgManager.getOrgsByparentId(id);
        }
        //公司等级为1 是总公司
        if (org!=null && org.getGrade().equals("1") && org.getOrgKind().equals("ogn")) {
            String id = org.getId();
            orgs = this.orgManager.getOrgsByparentId(id);
        }
        //等级为2是分公司
        if (org!=null &&org.getGrade().equals("2")&& org.getOrgKind().equals("ogn") ){

            orgQueryWrapper.eq("ID_",org.getId());
            orgs = this.orgManager.getBaseMapper().selectList(orgQueryWrapper);
        }

        return orgs;
    }

    private List<CompanyVo> getChild(String id, List<CompanyVo> vos) {
        ArrayList<CompanyVo> childrens = new ArrayList<>();

        for (CompanyVo vo : vos) {
            if (vo.getParentId().equals(id)) {
                childrens.add(vo);
            }
        }

        for (CompanyVo vo : childrens) {
            List<CompanyVo> child = getChild(vo.getId(), vos);
            if (child.size() > 0) {
                vo.setChildren(child);
            }
        }
        if (childrens.size() == 0) {
            return new ArrayList<CompanyVo>();
        }
        return childrens;
    }
}
