package com.goafanti.ambSystem.service.Impl;

import com.goafanti.ambSystem.bo.AmbAll;
import com.goafanti.ambSystem.bo.InputAmb;
import com.goafanti.ambSystem.bo.OutAmb;
import com.goafanti.ambSystem.service.AmbService;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.AmbSystemMapper;
import com.goafanti.common.dao.RoleMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.AmbSystem;
import com.goafanti.common.model.UserRole;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AmbServiceImpl extends BaseMybatisDao<AmbSystemMapper> implements AmbService {
    @Value(value = "${amb.maxLvl}")
    private Integer maxLvl=null;
    @Autowired
    private AmbSystemMapper ambSystemMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper  roleMapper;


    @Override
    public int addAmb(InputAmb in) {
        getParentParam(in);
        in.setStatus("0");
        in.setCreateBy(TokenManager.getAdminId());
        in.setCreateTime(new Date());
        ambSystemMapper.insertSelective(in);
        updateAmbRole(in.getLeader());
        return  1;
    }

    public  void getParentParam(InputAmb in){
        AmbSystem parentAmb = ambSystemMapper.selectByPrimaryKey(in.getParentId());
        in.setLvl(parentAmb.getLvl()+1);
        if (in.getLvl()>maxLvl)throw new BusinessException(String.format("层级最多添加%s层，如需添加更多请联系管理员。",maxLvl));
        in.setAncestors(parentAmb.getAncestors()+","+parentAmb.getId());
        in.setAncestorsNames(getAncestorsNames(in.getAncestors()));
    }

    @Override
    public int updateAmb(InputAmb in) {
        AmbSystem use = ambSystemMapper.selectByPrimaryKey(in.getId());
        int i=0;
        //0为执行计算巴名称，1为已执行，无需再执行
        if (in.getParentId()!=null&&in.getParentId()!=use.getParentId()){
            getParentParam(in);
            i=updateAncestorsNames(in,use.getName(),i);
        }
        if (in.getName()!=null&&!in.getName().equals(use.getName())){
            i=updateAncestorsNames(in,use.getName(),i);
        }

        in.setUpdateBy(TokenManager.getAdminId());
        in.setUpdateTime(new Date());
        ambSystemMapper.updateByPrimaryKeySelective(in);
        if (!in.getLeader().equals(use.getLeader()))pushAdminAmbRole(in,use);
        return 1;
    }

    /**
     * 设置巴主巴角色
     * @param in
     */
    private void pushAdminAmbRole(InputAmb in,AmbSystem use) {
        //如果是修改，处理原负责人
        if (in.getId()!=null){
            if (use !=null &&use.getLeader()!=null){
                updateAmbRole(use.getLeader());
            }
        }
        updateAmbRole(in.getLeader());
    }

    /**
     *
     * @param leader
     */
    private void updateAmbRole(String  leader) {
        StringBuffer str=new StringBuffer();
        List<AmbSystem> list=selectByLeader(leader);
        Admin a =new Admin();
        if (!list.isEmpty()){
            //不为空就是巴主，如果不是巴主则设置成巴主
            Integer i = userRoleMapper.selectByUidAndRoleName(leader, "巴主");
            if (i<1){
                String roleId = roleMapper.selectIdByName("巴主");
                UserRole userRole=new UserRole();
                userRole.setUid(leader);
                userRole.setRid(roleId);
                userRoleMapper.insert(userRole);
            }
            int ambManage=0;
            for (AmbSystem ambSystem : list) {
                str.append(ambSystem.getLvl()).append(",");
                if(ambSystem.getLvl()==5||ambSystem.getLvl()==6){
                    ambManage=1;
                }
            }
            a.setAmbManage(ambManage);
        }
        a.setId(leader);
        if (StringUtils.isNotBlank(str)) a.setAmbRole(str.substring(0,str.length()-1));
        if (a.getAmbRole()!=null){
            adminMapper.update(a);
        }
    }

    private List<AmbSystem> selectByLeader(String leader) {
        AmbSystem a =new AmbSystem();
        a.setLeader(leader);
        return ambSystemMapper.selectByParameter(a);
    }

    private List<AmbSystem> selectByParentId(Long parentId) {
        AmbSystem a =new AmbSystem();
        a.setParentId(parentId);
        return ambSystemMapper.selectByParameter(a);
    }

    private int updateAncestorsNames(InputAmb in,String useName,Integer i) {
        if (i>0)return i;
        return ambSystemMapper.updateAncestorsNames(in.getId(),in.getName(),useName);
    }

    @Override
    public Pagination<OutAmb> selectAmb(InputAmb in) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("name",in.getName());
        param.put("lvl",in.getLvl());
        param.put("leader",in.getLeader());
        param.put("ancestors",in.getAncestors());
        return (Pagination<OutAmb>) findPage("selectAmbSystemList","selectAmbSystemCount",param,in.getPageNo(),in.getPageSize());
    }

    @Override
    public List<?> selectAll() {
        List<AmbAll> list = ambSystemMapper.getAncestorsList(null);
        List<AmbAll> all=new ArrayList<>();
        for (AmbAll a : list) {
            if (a.getLvl()==0){
                pushLvl(a,list);
                all.add(a);
            }
        }

        return all;
    }

    @Override
    public int deleteAmb(InputAmb in) {
        return ambSystemMapper.deleteByPrimaryKey(in.getId());
    }

    @Override
    public int checkAmb(InputAmb in,Integer type) {

        if (type==0){
            int i = ambSystemMapper.selectByName(in.getName());
            if (i>0)return -1;
        }else if (type==2){
            List<AmbSystem> ambSystems = selectByParentId(in.getId());
            if (!ambSystems.isEmpty())return -1;
        }

        return 0;
    }



    @Override
    public Object detailsAmb(InputAmb in) {
        return ambSystemMapper.selectDtailsAmb(in.getId());
    }




    private void pushLvl(AmbAll a , List<AmbAll> list) {
        if (a.getLvl()<7){
            List<AmbAll> all=new ArrayList<>();
            for (AmbAll as : list) {
                if (as.getParentId().equals(a.getId())){
                    pushLvl(as,list);
                    all.add(as);
                }
            }
            a.setList(all);
        }

    }

    private String getAncestorsNames(String ancestors) {
        String[] split = ancestors.split(",");
        List<String> list = Arrays.asList(split);
        List<AmbAll> ancestorsList = ambSystemMapper.getAncestorsList(list);
        StringBuffer sb=new StringBuffer();
        for (AmbAll ambSystem : ancestorsList) {
            for (String s : list) {
                //第一层无需装配
                if (!ambSystem.getId().toString().equals("1")){
                    if (ambSystem.getId().toString().equals(s)){
                        sb=sb.append(ambSystem.getName()).append(",");
                        break;
                    }
                }
            }
        }
        String str="";
        if (sb.length()>1)str=sb.substring(0,sb.length()-1);
        return str;
    }

    @Override
    public Object getMyambDtails() {
        List<AmbSystem> ambSystems = ambSystemMapper.selectByParameter(new AmbSystem(TokenManager.getAdminId()));
        return ambSystems;
    }

}
