package com.zcloud.service.hiddenDangerCheckStandard.impl;

import com.alibaba.fastjson.JSONArray;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.datasource.hiddenDangerCheckStandard.CustomLabelFactoryMapper;
import com.zcloud.service.hiddenDangerCheckStandard.CustomLabelFactoryService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.Warden;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 说明：标签库
 * 作者：luoxiaobao
 * 时间：2022-12-27
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class CustomLabelFacoryServiceImpl implements CustomLabelFactoryService {

    @Resource
    private CustomLabelFactoryMapper customLabelFactoryMapper;

    /**
     * 新增
     *
     * @param pd
     * @throws Exception
     */
    public void save(PageData pd) throws Exception {
        customLabelFactoryMapper.save(pd);
    }

    /**
     * 删除
     *
     * @param pd
     * @throws Exception
     */
    public void delete(PageData pd) throws Exception {
        customLabelFactoryMapper.delete(pd);
    }

    /**
     * 修改
     *
     * @param pd
     * @throws Exception
     */
    public void edit(PageData pd) throws Exception {
        customLabelFactoryMapper.edit(pd);
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    public List<PageData> list(Page page) throws Exception {
        return customLabelFactoryMapper.datalistPage(page);
    }

    /**
     * 列表(全部)
     *
     * @param pd
     * @throws Exception
     */
    public List<PageData> listAll(PageData pd) throws Exception {
        return customLabelFactoryMapper.listAll(pd);
    }

    /**
     * 通过id获取数据
     *
     * @param pd
     * @throws Exception
     */
    public PageData findById(PageData pd) throws Exception {
        return customLabelFactoryMapper.findById(pd);
    }

    /**
     * 批量删除
     *
     * @param ArrayDATA_IDS
     * @throws Exception
     */
    public void deleteAll(String[] ArrayDATA_IDS) throws Exception {
        customLabelFactoryMapper.deleteAll(ArrayDATA_IDS);
    }

    @Override
    public List<PageData> getTree(PageData request) throws Exception {
        List<PageData> result = new ArrayList<>();
        PageData condition = new PageData();
        List<PageData> labels = customLabelFactoryMapper.findByAncestors(condition);
        for (PageData label : labels) {
            if ("1".equals(label.getString("IS_ANCESTORS_FLAG"))){
                condition.clear();
                condition.put("BUS_LABEL_FACTORY_ID",label.getString("BUS_LABEL_FACTORY_ID"));
                PageData ancestors = customLabelFactoryMapper.findById(condition);
                analysis(labels, ancestors);
                if (ancestors != null) {
                    result.add(ancestors);
                }
            }
        }
        result = result.stream().sorted(Comparator.comparing(o -> new BigDecimal(String.valueOf(o.get("SORT").toString())))).collect(Collectors.toList());
        return result;
    }

    @Override
    @Transactional
    public List<PageData> saveTree(PageData pd) throws Exception {
        // 组织
        List<PageData> _tree = Warden.getList(pd.getString("tree"));
        PageData condition = new PageData();
        // 删除所有标签
        condition.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
        condition.put("TYPE",pd.getString("TYPE"));
        customLabelFactoryMapper.deleteByAncestors(condition);
        List<PageData> result = new ArrayList<>();
        for (PageData leaf : _tree) {
            Warden.initDate(leaf);
            leaf.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
            if (leaf.get("BUS_LABEL_FACTORY_ID").toString().length() > 30) {
                if ("1".equals(leaf.getString("IS_ANCESTORS_FLAG"))) {
                    leaf.put("NAME", leaf.getString("NAME"));
                    customLabelFactoryMapper.save(leaf);
                } else {
                    leaf.put("ANCESTORS_ID", leaf.getString("BUS_LABEL_FACTORY_ID"));
                    leaf.put("NAME", leaf.getString("NAME"));
                    leaf.put("PARENT_ID", "0");
                    leaf.put("IS_ANCESTORS_FLAG", "1");
                    leaf.put("TYPE", pd.getString("TYPE"));
                    customLabelFactoryMapper.save(leaf);
                }
            } else {
                leaf.put("BUS_LABEL_FACTORY_ID", Warden.get32UUID());
                leaf.put("ANCESTORS_ID", leaf.getString("BUS_LABEL_FACTORY_ID"));
                leaf.put("NAME", leaf.getString("NAME"));
                leaf.put("PARENT_ID", "0");
                leaf.put("IS_ANCESTORS_FLAG", "1");
                leaf.put("TYPE", pd.getString("TYPE"));
                customLabelFactoryMapper.save(leaf);
            }
            analysis(leaf, result, 1);
        }
        return result;
    }

    @Override
    public List<PageData> findAllAncestors(PageData condition) throws Exception {
        return customLabelFactoryMapper.findAllAncestors(condition);
    }

    private void analysis(PageData pd, List<PageData> result, Integer level) {
        JSONArray children = (JSONArray) pd.get("children");
        if (children == null || children.size() <= 0) {
            return;
        }
        List<PageData> tree = Warden.getList(children);
        result.addAll(tree);
        for (PageData leaf : tree) {
            leaf.put("BUS_LABEL_FACTORY_ID", leaf.get("BUS_LABEL_FACTORY_ID").toString().length() > 30 ? leaf.getString("BUS_LABEL_FACTORY_ID") : Warden.get32UUID());
            leaf.put("ANCESTORS_ID", pd.getString("ANCESTORS_ID"));
            leaf.put("PARENT_ID", pd.getString("BUS_LABEL_FACTORY_ID"));
            leaf.put("IS_ANCESTORS_FLAG", "0");
            leaf.put("LEVEL", level);
            leaf.put("CREATOR_ID", Jurisdiction.getUSER_ID());
            leaf.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
            leaf.put("CREATED_TIME", DateUtil.date2Str(new Date()));
            leaf.put("ISDELETE", "0");
            leaf.put("TYPE", pd.getString("TYPE"));
            customLabelFactoryMapper.save(leaf);
            analysis(leaf, result, ++level);
        }
    }

    private void analysis(List<PageData> labels, PageData parent) {
        List<PageData> sons = labels.stream()
                .filter(n -> n.getString("PARENT_ID").equals(parent.getString("BUS_LABEL_FACTORY_ID")))
                .sorted(Comparator.comparing(o -> new BigDecimal(String.valueOf(o.get("SORT").toString()))))
                .collect(Collectors.toList());
        if (parent == null) {
            return;
        }
        parent.put("children", sons);
        if (sons.size() > 0) {
            for (PageData son : sons) {
                analysis(labels, son);
            }
        }
    }

    private PageData findParentNode(List<PageData> tree, PageData branch) throws Exception {
        for (PageData root : tree) {
            List<PageData> branches = (List<PageData>) root.get("children");
            if (branches.size() <= 0) {
                continue;
            }
            for (PageData _branch : branches) {
                if (branch.getString("BUS_LABEL_FACTORY_ID").equals(_branch.getString("BUS_LABEL_FACTORY_ID"))) {
                    return root;
                }
            }
            PageData parentNode = findParentNode(branches, branch);
            if (parentNode != null && parentNode.size() > 0) {
                return parentNode;
            }
        }
        return null;
    }

    private void initNode(PageData info, PageData gene) {
        info.put("BUS_LABEL_FACTORY_ID", info.get("BUS_LABEL_FACTORY_ID").toString().length() > 30 ? info.getString("BUS_LABEL_FACTORY_ID") : Warden.get32UUID());
        info.put("PARENT_ID", gene.getString("BUS_LABEL_FACTORY_ID"));
        info.put("ANCESTORS_ID", gene.getString("ANCESTORS_ID"));
        info.put("IS_ANCESTORS_FLAG", "0");
        info.put("LEVEL", Integer.parseInt(gene.get("LEVEL").toString()) + 1);
        info.put("CREATOR_ID", Jurisdiction.getUSER_ID());
        info.put("CREATED_TIME", DateUtil.date2Str(new Date()));
        info.put("ISDELETE", "0");
        info.put("TYPE", gene.getString("TYPE"));
        JSONArray _children = (JSONArray) info.get("children");
        if (_children == null || _children.size() <= 0) {
            return;
        }
        List<PageData> children = Warden.getList(_children);
        for (PageData child : children) {
            initNode(child, info);
        }
    }

}

