/*
 * Copyright [2022] [https://www.baiduc.com]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.baiduc.com
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.baiduc.com
 */
package vip.xiaonuo.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.erp.entity.ErpBdMaterial;
import vip.xiaonuo.erp.entity.ErpBdOrg;
import vip.xiaonuo.erp.entity.voucher.ErpMaterial;
import vip.xiaonuo.erp.mapper.ErpBdMaterialMapper;
import vip.xiaonuo.erp.mapper.ErpBdOrgMapper;
import vip.xiaonuo.erp.param.*;
import vip.xiaonuo.erp.service.ErpBdMaterialService;
import vip.xiaonuo.sale.entity.ErpBaseMaterial;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * erp_bd_materialService接口实现类
 *
 * @author 1
 * @date  2025/03/01 14:50
 **/
@Service
public class ErpBdMaterialServiceImpl extends ServiceImpl<ErpBdMaterialMapper, ErpBdMaterial> implements ErpBdMaterialService {

    @Override
    public Page<ErpBdMaterial> page(ErpBdMaterialPageParam erpBdMaterialPageParam) {
        QueryWrapper<ErpBdMaterial> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(erpBdMaterialPageParam.getSortField(), erpBdMaterialPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(erpBdMaterialPageParam.getSortOrder());
            queryWrapper.orderBy(true, erpBdMaterialPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(erpBdMaterialPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ErpBdMaterial::getId);
        }
        queryWrapper.eq(StringUtils.isNotBlank(erpBdMaterialPageParam.getOrgId()),"org_id",erpBdMaterialPageParam.getOrgId());
        queryWrapper.eq("parent",0);
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ErpBdMaterialAddParam erpBdMaterialAddParam) {
        ErpBdMaterial erpBdMaterial = BeanUtil.toBean(erpBdMaterialAddParam, ErpBdMaterial.class);
        this.save(erpBdMaterial);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ErpBdMaterialEditParam erpBdMaterialEditParam) {
        ErpBdMaterial erpBdMaterial = this.queryEntity(erpBdMaterialEditParam.getId());
        BeanUtil.copyProperties(erpBdMaterialEditParam, erpBdMaterial);
        this.updateById(erpBdMaterial);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ErpBdMaterialIdParam> erpBdMaterialIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(erpBdMaterialIdParamList, ErpBdMaterialIdParam::getId));
    }

    @Override
    public ErpBdMaterial detail(ErpBdMaterialIdParam erpBdMaterialIdParam) {
        return this.queryEntity(erpBdMaterialIdParam.getId());
    }

    @Override
    public ErpBdMaterial queryEntity(Integer id) {
        ErpBdMaterial erpBdMaterial = this.getById(id);
        if(ObjectUtil.isEmpty(erpBdMaterial)) {
            throw new CommonException("erp_bd_material不存在，id值为：{}", id);
        }
        return erpBdMaterial;
    }

    @Override
    public List<ErpBdMaterial> getByParentId(ErpBdMaterialParentParam erpBdMaterial) {
        String orgId = erpBdMaterial.getOrgId();
        Integer parent = erpBdMaterial.getId();
        if (ObjectUtil.isEmpty(parent)){
            parent = 0;
        }
        return  this.list(new QueryWrapper<ErpBdMaterial>().eq("parent", parent).eq(StringUtils.isNotBlank(orgId), "org_id", orgId));
    }

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ErpBdOrgMapper erpBdOrgMapper;
    @Autowired
    private ErpBdMaterialMapper erpBdMaterialMapper;

    @Override
    public void sync() {
        ResponseEntity<List<ErpMaterial>> response = restTemplate.exchange(
                "http://127.0.0.1:9200/erp-bd-org/getMaterial",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ErpMaterial>>() {
                }
        );
        List<ErpMaterial> forObjects = response.getBody();
        System.out.println(forObjects);

        for (ErpMaterial forObject : forObjects) {

            ResponseEntity<List<ErpMaterial>> response2 = restTemplate.exchange(
                    "http://127.0.0.1:9200/erp-bd-org/getMaterialDetail?fnumber=" + forObject.getFnumber(),
                    HttpMethod.GET,
                    null,
                    new ParameterizedTypeReference<List<ErpMaterial>>() {
                    }
            );
            //二
            List<ErpMaterial> forObjects2 = response2.getBody();
            System.out.println(forObjects2);

            boolean b = false;
            //判断有没有下级
            for (ErpMaterial erpMaterial : forObjects2) {
                if (erpMaterial.getFnumber().contains("0000")) {

                    ErpBdOrg forgid = erpBdOrgMapper.selectOne(new QueryWrapper<ErpBdOrg>().eq("forgid", erpMaterial.getFacctorgid()));
                    if (ObjectUtil.isEmpty(forgid))
                        continue;
                    if (erpBdMaterialMapper.exists(new QueryWrapper<ErpBdMaterial>().eq("erp_fnumber", erpMaterial.getFnumber()).eq("org_id", forgid.getOrgId()))) {
                        continue;
                    }
                    ErpBdMaterial erpBaseMaterial = new ErpBdMaterial();
                    erpBaseMaterial.setErpFnumber(erpMaterial.getFnumber());
                    erpBaseMaterial.setOrgId(forgid.getOrgId());
                    erpBaseMaterial.setFname(erpMaterial.getFname() + " " + erpMaterial.getFspecification());
                    erpBaseMaterial.setFspecification(erpMaterial.getFspecification());
                    erpBaseMaterial.setParent(0);
                    erpBdMaterialMapper.insert(erpBaseMaterial);
                    b = true;
                }
            }
            //有下级
            if (b) {
                for (ErpMaterial erpMaterial : forObjects2) {
                    if (!erpMaterial.getFnumber().contains("0000")) {

                        ErpBdOrg forgid = erpBdOrgMapper.selectOne(new QueryWrapper<ErpBdOrg>().eq("forgid", erpMaterial.getFacctorgid()));
                        if (ObjectUtil.isEmpty(forgid))
                            continue;
                        if (erpBdMaterialMapper.exists(new QueryWrapper<ErpBdMaterial>().eq("erp_fnumber", erpMaterial.getFnumber()).eq("org_id", forgid.getOrgId()))) {
                            continue;
                        }
                        ErpBdMaterial erpBaseMaterial = new ErpBdMaterial();
                        erpBaseMaterial.setErpFnumber(erpMaterial.getFnumber());
                        erpBaseMaterial.setOrgId(forgid.getOrgId());
                        erpBaseMaterial.setFname(erpMaterial.getFname() + "  " + erpMaterial.getFspecification());
                        erpBaseMaterial.setFspecification(erpMaterial.getFspecification());
                        ErpBdMaterial erpBdMaterial = erpBdMaterialMapper.selectOne(new QueryWrapper<ErpBdMaterial>().
                                eq("erp_fnumber", forObject.getFnumber() + "0000").eq("org_id", forgid.getOrgId()));
                        if (ObjectUtil.isEmpty(erpBdMaterial)) {
                            continue;
                        }
                        erpBaseMaterial.setParent(erpBdMaterial.getId());
                        erpBdMaterialMapper.insert(erpBaseMaterial);
                    }
                }
            } else {
                for (ErpMaterial erpMaterial : forObjects2) {

                    ErpBdOrg forgid = erpBdOrgMapper.selectOne(new QueryWrapper<ErpBdOrg>().eq("forgid", erpMaterial.getFacctorgid()));
                    if (ObjectUtil.isEmpty(forgid))
                        continue;
                    if (erpBdMaterialMapper.exists(new QueryWrapper<ErpBdMaterial>().eq("erp_fnumber", erpMaterial.getFnumber()).eq("org_id", forgid.getOrgId()))) {
                        continue;
                    }
                    ErpBdMaterial erpBaseMaterial = new ErpBdMaterial();
                    erpBaseMaterial.setErpFnumber(erpMaterial.getFnumber());
                    erpBaseMaterial.setOrgId(forgid.getOrgId());
                    erpBaseMaterial.setFname(erpMaterial.getFname() + "  " + erpMaterial.getFspecification());
                    erpBaseMaterial.setFspecification(erpMaterial.getFspecification());
                    erpBaseMaterial.setParent(0);
                    erpBdMaterialMapper.insert(erpBaseMaterial);

                    ErpBdMaterial erpBaseMaterial1 = new ErpBdMaterial();
                    erpBaseMaterial1.setErpFnumber(erpMaterial.getFnumber());
                    erpBaseMaterial1.setOrgId(forgid.getOrgId());
                    erpBaseMaterial1.setFname(erpMaterial.getFname() + "  " + erpMaterial.getFspecification());
                    erpBaseMaterial1.setFspecification(erpMaterial.getFspecification());
                    erpBaseMaterial1.setParent(erpBaseMaterial.getId());
                    erpBdMaterialMapper.insert(erpBaseMaterial1);
                }
            }

        }
    }

    @Override
    public List<ErpBdMaterialVo> getTreeParentId(ErpBdMaterialParentParam erpBdMaterial) {

        List<ErpBdMaterial> materials = this.list(new QueryWrapper<ErpBdMaterial>().eq(StringUtils.isNotBlank(erpBdMaterial.getOrgId()), "org_id", erpBdMaterial.getOrgId()));

        return buildTree(materials,0);

    }

    public static List<ErpBdMaterialVo> buildTree(List<ErpBdMaterial> nodes, int rootParentId) {
        Map<Integer, ErpBdMaterialVo> nodeMap = new HashMap<>();
        List<ErpBdMaterialVo> rootNodes = new ArrayList<>();

        List<ErpBdMaterialVo> bdMaterialVos = new ArrayList<>();
        // 将所有节点放入 Map 中，方便通过 ID 查找
        for (ErpBdMaterial node : nodes) {
            ErpBdMaterialVo erpBdMaterialVo = new ErpBdMaterialVo();
            BeanUtil.copyProperties(node, erpBdMaterialVo);
            bdMaterialVos.add(erpBdMaterialVo);
            nodeMap.put(node.getId(), erpBdMaterialVo);
        }

        // 构建树
        for (ErpBdMaterialVo node : bdMaterialVos) {
            if (node.getParent() == 0) {
                // 顶级节点，直接加入根节点列表
                rootNodes.add(node);
            } else {
                // 查找父节点，并将当前节点加入父节点的子节点列表
                ErpBdMaterialVo parentNode = nodeMap.get(node.getParent());
                if (parentNode != null) {
                    parentNode.addChild(node);
                }
            }
        }
        return rootNodes;
    }


    public List<ErpBdMaterial> getByParentId2(Integer erpBdMaterial,String orgId) {
        if (ObjectUtil.isEmpty(erpBdMaterial)){
            erpBdMaterial = 0;
        }
        return  this.list(new QueryWrapper<ErpBdMaterial>().eq("parent", erpBdMaterial).eq(StringUtils.isNotBlank(orgId), "org_id", orgId));
    }

}
