package com.mosty.base.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mosty.base.manager.remote.TbBaseAdaptRemoteService;
import com.mosty.base.model.entity.jcgl.TbJcglZbfl;

import com.mosty.base.manager.mapper.TpJcglZbflMapper;
import com.mosty.base.manager.service.TpJcglZbflService;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@AllArgsConstructor
@Service
public class TpJcglZbflServiceImpl implements TpJcglZbflService {

    private final TpJcglZbflMapper tpJcglZbflMapper;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;


    @Override
    public void addZbfl(TbJcglZbfl zbfl) {
        synchronized (zbfl.getClass()) {//同时刻不能同时新增
            //查询是否存在当前节点
            TbJcglZbfl tbJcglZbfl = tpJcglZbflMapper.selectOne(new QueryWrapper<TbJcglZbfl>().
                    eq("sname", zbfl.getPname())
                    .eq("xt_scbz", 0)
            );
            //子节点是否重复
            TbJcglZbfl son = tpJcglZbflMapper.selectOne(new QueryWrapper<TbJcglZbfl>().
                    eq("sname", zbfl.getSname())
                    .eq("xt_scbz", 0)
            );
            if (son != null) {
                throw new BusinessException("装备类型名称重复");
            }
            String pname = zbfl.getPname();//父副本
            String sname = zbfl.getSname();//子副本
            String maxCode = tpJcglZbflMapper.selectMaxCode();//查询最大编码
            NumberFormat f = new DecimalFormat("0000");
            String max = maxCode.substring(maxCode.lastIndexOf("0") + 1);
            String scode = f.format(Integer.parseInt(max) + 1);//标签编号生成规则
            if (tbJcglZbfl != null) {
                //新增子节点
                if (StringUtils.isNotBlank(zbfl.getSname()) && StringUtils.isNotBlank(zbfl.getPname())) {
                    zbfl.setScode("ZB" + scode)
                            .setId(UUID.randomUUID().toString())
                            .setSname(zbfl.getSname())
                            .setPname(tbJcglZbfl.getSname())
                            .setPcode(tbJcglZbfl.getScode())
                            .setJdcj(tbJcglZbfl.getJdcj() + 1)
                            .setXtScbz("0")
                    ;
                    tpJcglZbflMapper.insert(zbfl);
                }
            } else {//同时新增子节点父节点
                String code = "ZB" + scode;
                //先新增父节点
                zbfl.setScode(code)
                        .setId(UUID.randomUUID().toString())
                        .setSname(zbfl.getPname())
                        .setPname("装备管理")
                        .setPcode("ZB0005")
                        .setJdcj(1)
                        .setXtScbz("0")
                ;
                tpJcglZbflMapper.insert(zbfl);
                //再新增子节点
                zbfl.setScode("ZB" + f.format(Integer.parseInt(max) + 2))
                        .setId(UUID.randomUUID().toString())
                        .setSname(sname)
                        .setPname(pname)
                        .setPcode(code)
                        .setJdcj(1)
                        .setXtScbz("0")
                ;
                tpJcglZbflMapper.insert(zbfl);
            }
        }
    }

    @Override
    public List<TbJcglZbfl> zbTree(String scode) {
        //只查询当前能选择的设备类型
        List<TbJcglZbfl> tbJcglZbfls = tpJcglZbflMapper.selectList(new QueryWrapper<TbJcglZbfl>().orderByAsc("jdcj")
                .in(StringUtils.isNotBlank(scode), "scode", scode, "ZB0005")
                .or(StringUtils.isNotBlank(scode)).in(StringUtils.isNotBlank(scode), "pcode", scode)
        );
        List<TbJcglZbfl> zhjmxfZbglZbsjgs1 = null;
        if (tbJcglZbfls.size() > 0) {
            //获取最父节点信息
            TbJcglZbfl tbJcglZbfl = tbJcglZbfls.get(0);
            //递归
            zhjmxfZbglZbsjgs1 = depTree(tbJcglZbfl, tbJcglZbfls);
        }
        return zhjmxfZbglZbsjgs1;
    }


    public List<TbJcglZbfl> depTree(TbJcglZbfl zhjmxfZbglZbsjg, List<TbJcglZbfl> list) {
        //获取子节点信息
        String socode = zhjmxfZbglZbsjg.getScode();
        List<TbJcglZbfl> childList = new ArrayList<TbJcglZbfl>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getPcode().equals(socode)) {
                //添加子节点信息
                childList.add(list.get(i));
                //删除已存在的节点 减少循环次数
                list.remove(i);
                i--;
            }
        }

        if (list.size() > 0) {
            for (int i = 0; i < childList.size(); i++) {
                childList.get(i).setChildren(depTree(childList.get(i), list));

            }
        }
        return childList;
    }

    @Override
    public void editZbfl(TbJcglZbfl zbfl) {
        tpJcglZbflMapper.updateById(zbfl);
    }

    @Override
    public IPage<TbJcglZbfl> selectList(TbJcglZbfl zbfl, IPage<TbJcglZbfl> page) {
        QueryWrapper<TbJcglZbfl> queryWrapper = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(queryWrapper,userInfo);
        zbfl.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(zbfl.getSsbmdm(), null));
        if (zbfl != null) {
            queryWrapper.lambda()
                    .like(StringUtils.isNotBlank(zbfl.getSname()), TbJcglZbfl::getSname, zbfl.getSname())
                    .likeRight(StringUtils.isNotBlank(zbfl.getSsbmdm()), TbJcglZbfl::getSsbmdm, zbfl.getSsbmdm())
                    .eq(TbJcglZbfl::getXtScbz, 0);
        }
        IPage<TbJcglZbfl> page1 = tpJcglZbflMapper.selectPage(page, queryWrapper);
        return page1;
    }

    @Override
    public void deleteZbfl(List<String> id) {
        if (id.size() > 0) {
            List<TbJcglZbfl> tbJcglZbfls = tpJcglZbflMapper.selectList(new QueryWrapper<TbJcglZbfl>().eq("xt_scbz", 0));
            id.forEach(i -> {
                TbJcglZbfl tbJcglZbfl = tpJcglZbflMapper.selectById(i);
                if (tbJcglZbfl != null) {
                    if (tbJcglZbfls.size() > 0) {
                        deleteTree(tbJcglZbfl, tbJcglZbfls);
                    }
                    tbJcglZbfl.setXtScbz("1");
                    //删除子节点
                    tpJcglZbflMapper.updateZt(tbJcglZbfl.getScode());
                }
            });
        }
    }

    //递归删除树
    public void deleteTree(TbJcglZbfl tbJcglZbfl, List<TbJcglZbfl> tbJcglZbfls) {
        List<TbJcglZbfl> childList = new ArrayList<TbJcglZbfl>();
        for (int i = 0; i < tbJcglZbfls.size(); i++) {
            //当遍历到最后层级时自己和自己比较
            if (tbJcglZbfls.get(i).getPcode().equals(tbJcglZbfl.getScode()) || tbJcglZbfls.get(i).getScode().equals(tbJcglZbfl.getScode())) {
                tpJcglZbflMapper.updateType(tbJcglZbfls.get(i).getId());
                childList.add(tbJcglZbfls.get(i));
                tbJcglZbfls.remove(i);
            }
        }
        if (tbJcglZbfls.size() > 0) {
            childList.forEach(c -> {
                deleteTree(c, tbJcglZbfls);
            });
        }

    }

}
