package com.artfess.sysConfig.persistence.manager.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.sysConfig.persistence.dao.SysAreasDao;
import com.artfess.sysConfig.persistence.manager.SysAreasManager;
import com.artfess.sysConfig.persistence.model.SysAreas;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Program: edp
 * @Date: 2021/3/2
 * @Author: ZQF
 * @Description: 系统行政区划
 */
@Service
public class SysAreasManagerImpl extends BaseManagerImpl<SysAreasDao, SysAreas> implements SysAreasManager {

    @Resource
    SysAreasDao sysAreasDao;

    @Override
    @Transactional
    public String saveSysAreas(SysAreas sysAreas) {
        Assert.notNull(sysAreas, "行政区划信息不能为空！");
        String msg = "";
        if (StringUtils.isNotBlank(sysAreas.getId())) { // 更新
            SysAreas old = this.sysAreasDao.selectById(sysAreas.getId());
            this.newUpdateTree(sysAreas, old.getName());
            msg = "更新成功";
        } else { // 新增
            sysAreas.setHasChildren(0);
            sysAreas.setSn(this.getNextSequenceByParentId(sysAreas.getParentId()));
            this.newInsertTree(sysAreas);
            msg = "新增成功";
        }
        return msg;
    }

    @Override
    public List<SysAreas> queryAreasEntity(SysAreas sysAreas) {
        QueryWrapper<SysAreas> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(sysAreas.getName())){
            queryWrapper.like("name_",sysAreas.getName());
        }
        if(StringUtils.isNotEmpty(sysAreas.getCode())){
            queryWrapper.eq("code_",sysAreas.getCode());
        }

        if(StringUtils.isNotEmpty(sysAreas.getLevelCode())){
            queryWrapper.like("LEVEL_CODE_", sysAreas.getLevelCode());
        }
        if(StringUtils.isNotEmpty(sysAreas.getFullCode())){
            queryWrapper.likeRight("FULL_CODE_", sysAreas.getFullCode());
        }
        if(StringUtils.isNotEmpty(sysAreas.getFullId())){
            queryWrapper.likeRight("FULL_ID_", sysAreas.getFullId());
        }
        if(!CollectionUtils.isEmpty(sysAreas.getLevels())){
            queryWrapper.in("LEVEL_CODE_", sysAreas.getLevels());
        }
        queryWrapper.orderByAsc("SN_");
        return this.sysAreasDao.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public void updateSequence(Map<String, Integer> params) {
        Assert.notNull(params, "参数不能为空！");
        for (String key : params.keySet()) {
            UpdateWrapper<SysAreas> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("SN_",params.get(key)).eq("ID_",key);
            this.update(updateWrapper);
        }
    }

    @Override
    @Transactional
    public void deleteBatch(String ids) {
        Assert.hasText(ids, "参数ids不能为空");
        List<String> idsList = Arrays.asList(ids.split(","));
        idsList.forEach(s -> {
            SysAreas sysAreas = this.sysAreasDao.selectById(s);
            // 父节点不是根节点时，修改父节点的 hasChildren 数量
            if (!sysAreas.getParentId().equals("root")) {
                SysAreas parent = this.sysAreasDao.selectById(sysAreas.getParentId());
                parent.setHasChildren(parent.getHasChildren() - 1);
                this.update(parent);
            }
            // 删除自身及子节点
            QueryWrapper<SysAreas> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("FULL_ID_", sysAreas.getFullId());
            this.sysAreasDao.delete(queryWrapper);
        });
    }

    @Override
    public JSONArray tree(SysAreas sysAreas) {
        List<SysAreas> list = this.queryAreasEntity(sysAreas);
        List<SysAreas> tree = BeanUtils.listToTree(list);
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(BeanUtils.listToTree(tree)));
        for (Object o : array) {
            JSONObject jsonObject = (JSONObject) o;
            JSONArray childrenList = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("children")));
            if (null == childrenList || childrenList.size() < 1) {
                jsonObject.remove("children");
            } else {
                jsonObject.put("children", processChildren(childrenList));
            }
        }
        return array;
    }

    private JSONArray processChildren(JSONArray array) {
        for (Object o : array) {
            JSONObject jsonObject = (JSONObject) o;
            JSONArray childrenList = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("children")));
            if (null == childrenList || childrenList.size() < 1) {
                jsonObject.remove("children");
            } else {
                jsonObject.put("children", processChildren(childrenList));
            }
        }
        return array;
    }
}
