/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.base.entity.Menu;
import com.tofly.base.entity.Syschildcode;
import com.tofly.base.mapper.SyschildcodeMapper;
import com.tofly.base.service.SyschildcodeService;
import com.tofly.base.service.SysparentcodeService;
import com.tofly.common.core.util.JSONUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.pojo.CustomCode;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 系统通用码表子级表
 *
 * @author wangjieliu
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("syschildcodeService")
@AllArgsConstructor
public class SyschildcodeServiceImpl extends ServiceImpl<SyschildcodeMapper, Syschildcode> implements SyschildcodeService {

    @Override
    public List<CustomCode> getAll() {
        //获取所有的编码信息
        List<Syschildcode> codeList = this.list(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCdisable,"1")
                .orderByAsc(Syschildcode::getSort));
        //可以将一下的转换以及树结构拿出来单独使用
      /*  List<CustomCode> jsonList = JSONObject.parseArray(JSONObject.toJSONString(codeList), CustomCode.class);
        List<CustomCode> json= JSONUtil.parTree(jsonList,CustomCode::getId,CustomCode::getPcid,CustomCode::getCodeList);
*/
        List<CustomCode> customCodes = JSONObject.parseArray(JSON.toJSONString(codeList),CustomCode.class);

        List<CustomCode> customCodes1 = customCodes.stream().filter(m -> m.getPcid()==null)
                .map((m) -> {

                            m.setCodeList(getChildrens(m, customCodes));
                            return m;
                        }
                ).collect(Collectors.toList());
        return customCodes1;

    }

    @Override
    public List<Syschildcode> getfj() {
        List<Syschildcode> syschildcodes = this.list(Wrappers.<Syschildcode>lambdaQuery()
                .isNull(Syschildcode::getPcid).eq(Syschildcode::getCdisable,"1")
                .select(Syschildcode::getId,Syschildcode::getCname,Syschildcode::getCcontert)
                .orderByAsc(Syschildcode::getSort));
        return syschildcodes;
    }

    @Override
    public Page<Syschildcode> getParentList(Page page,Syschildcode syschildcode) {
        QueryWrapper<Syschildcode> queryWrapper=new QueryWrapper<>();
        if(StringUtil.isNotEmpty(syschildcode.getCname())){
            queryWrapper.like("CNAME",syschildcode.getCname());

        }
        if(StringUtil.isNotEmpty(syschildcode.getCcode())){
            queryWrapper.like("CCODE",syschildcode.getCcode());

        }

        queryWrapper.eq("CDISABLE","1");
        queryWrapper.isNull("PCID");
        queryWrapper.orderByAsc("SORT");
       return baseMapper.selectPage(page,queryWrapper);
    }

    //定义一个全局的变量存放子级列表
//    List<Syschildcode> listSys=new ArrayList<>();

    public List<CustomCode> getBylistPcid_Old(List<String> list) {
//        //调用之前都将全局变量中的数据清空
//        listSys.clear();
//        //查询父级
//        List<Syschildcode> fCodes = this.list(Wrappers.<Syschildcode>lambdaQuery().in(Syschildcode::getId,list));
//        listSys.addAll(fCodes);
//        //查询子级
//        List<Syschildcode> codes = this.list(Wrappers.<Syschildcode>lambdaQuery().in(Syschildcode::getPcid,list));
//        listSys.addAll(codes);
//        //定义的递归查找子级的子级
//        List<Syschildcode> childeList=select(codes);

        //根据父级ID查询优化
        List<Syschildcode> syschildcodeList = baseMapper.getBylistPcid(list);
        //转换
        List<CustomCode> customCodes = JSONObject.parseArray(JSON.toJSONString(syschildcodeList),CustomCode.class);
        //树状
        List<CustomCode> customCodes1=JSONUtil.parTree(customCodes,CustomCode::getId,CustomCode::getPcid, CustomCode::getCodeList);

        return customCodes1;
    }


    @Override
    public List<CustomCode> getBylistPcid(List<String> list) {

        //根据父级ID查询优化
        List<Syschildcode> syschildcodeList = baseMapper.getBylistPcid(list);
        //转换
        List<CustomCode> customCodes = JSONObject.parseArray(JSON.toJSONString(syschildcodeList),CustomCode.class);

        List<CustomCode> customCodes1 = customCodes.stream().filter(m -> m.getPcid()==null)
                .map((m) -> {

                            m.setCodeList(getChildrens(m, customCodes));
                            return m;
                        }
                ).collect(Collectors.toList());
        return customCodes1;
    }

    @Override
    public Page<Syschildcode> getDataPage(Page page, Syschildcode syschildcode) {
        Long pid = syschildcode.getPcid();
        Long id = syschildcode.getId();
       return this.page(page, Wrappers.<Syschildcode>lambdaQuery()
                .eq(Syschildcode::getCdisable, "1")
                .like(StringUtil.isNotEmpty(syschildcode.getCname()), Syschildcode::getCname, syschildcode.getCname())
                .eq(StringUtil.isNotEmpty(syschildcode.getPcname()), Syschildcode::getPcname, syschildcode.getPcname())
                .eq(StringUtil.isNotNull(pid), Syschildcode::getPcid, pid)
                .eq(StringUtil.isNotNull(id), Syschildcode::getId, id)
                .orderByAsc(Syschildcode::getSort));
    }


    private List<CustomCode> getChildrens(CustomCode parent, List<CustomCode> menuDatas) {
        List<CustomCode> childList = menuDatas.stream().filter(m -> {
            return Objects.equals(m.getPcid(), parent.getId());
        }).map((m) -> {

            m.setCodeList(getChildrens(m, menuDatas));
            return m;
        }).collect(Collectors.toList());
        return childList;
    }




//    /**
//     * 根据父级ID递归查询所有的子级
//     * @param codeList
//     * @return
//     */
//    public List<Syschildcode> select(List<Syschildcode> codeList){
//        //得到主键ID，然后去查询是否还有子级
//        List<Long> ids = codeList.stream().map(Syschildcode::getId).collect(Collectors.toList());
//        List<Syschildcode> codes = this.list(Wrappers.<Syschildcode>lambdaQuery().in(Syschildcode::getPcid,ids));
//        //这里一般都很少使用递归，因为编码表层次很少有超过两级的，但是不排除有三级四级或更多的
//        if (codes.size()>0){
//            listSys.addAll(codes);
//            //递归
//            for (int i=0;i<codes.size();i++){
//                select(codes);
//            }
//        }
//        return listSys;
//    }

    @Override
    public boolean insert(Syschildcode syschildcode) {

        //判断有没有父级编码节点
         if (StringUtil.isNotNull(syschildcode.getPcid())) {
            //插入之前判断有没有相同的编码名称
            Integer code = baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCname,syschildcode.getCname()).eq(Syschildcode::getPcid,syschildcode.getPcid())
                    .eq(Syschildcode::getCdisable, "1"));

            if (code>0){
                throw new ToflyDeniedException("存在相同名字，请勿重复添加");
            }

            code= baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCcode,syschildcode.getCcode()).eq(Syschildcode::getPcid,syschildcode.getPcid())
                    .eq(Syschildcode::getCdisable, "1"));
            if (code>0){
                throw new ToflyDeniedException("编码重复");
            }

            //需要查询顺序，这里写个SQL用nvl方便
            Long sortNum = baseMapper.getSort(syschildcode.getPcid());
            syschildcode.setSort(sortNum);
        }else {
            syschildcode.setSort(1L);
            //插入之前判断有没有相同的编码名称
            Integer code = baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCname,syschildcode.getCname()).isNull(Syschildcode::getPcid).eq(Syschildcode::getCdisable, "1"));
            if (code>0){
                throw new ToflyDeniedException("存在相同名字，请勿重复添加");
            }

            code= baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCcode,syschildcode.getCcode()).isNull(Syschildcode::getPcid).eq(Syschildcode::getCdisable, "1"));
            if (code>0){
                throw new ToflyDeniedException("编码重复");
            }
        }
        syschildcode.setCdisable("1");
        baseMapper.insert(syschildcode);
        return true;
    }

    @Override
    public boolean updateInfo(Syschildcode syschildcode) {
        //修改前查询是否系统编码，如果是系统编码，则无法修改
        Syschildcode old=this.baseMapper.selectById(syschildcode.getId());
        if(old==null || old.getFlag().equals("1")){
            throw new ToflyDeniedException("该编码是系统编码，无法修改");
        }

       /* //由于编码表特殊；修改删除会影响系统的进行；所以目前只能修改厂家的编码
        Long cjId = 2L;
        if (!cjId.equals(syschildcode.getPcid())) {
            throw new ToflyDeniedException("修改失败");
        }*/
        if (StringUtil.isNotNull(syschildcode.getPcid())) {
            Integer count = this.baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCname, syschildcode.getCname())
                    .eq(Syschildcode::getPcid, syschildcode.getPcid()).eq(Syschildcode::getCdisable, "1").ne(Syschildcode::getId , syschildcode.getId()));
            if (count>0) {
                throw new ToflyDeniedException("存在相同名字，请勿重复添加");
            }
            count = this.baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCcode, syschildcode.getCcode())
                    .eq(Syschildcode::getPcid, syschildcode.getPcid()).eq(Syschildcode::getPcid, syschildcode.getPcid()).eq(Syschildcode::getCdisable, "1").ne(Syschildcode::getId, syschildcode.getId()));
            if (count>0) {
                throw new ToflyDeniedException("编码重复");
            }
        } else {
            Integer count = this.baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCname, syschildcode.getCname())
                    .isNull(Syschildcode::getPcid).eq(Syschildcode::getCdisable, "1").ne(Syschildcode::getId , syschildcode.getId()));
            if (count>0) {
                throw new ToflyDeniedException("存在相同名字，请勿重复添加");
            }
            count = this.baseMapper.selectCount(Wrappers.<Syschildcode>lambdaQuery().eq(Syschildcode::getCcode, syschildcode.getCcode())
                    .isNull(Syschildcode::getPcid).eq(Syschildcode::getCdisable, "1").ne(Syschildcode::getId , syschildcode.getId()));
            if (count>0) {
                throw new ToflyDeniedException("编码重复");
            }
        }

        return this.baseMapper.updateById(syschildcode)>0?true:false;

    }


}
