package com.zt.plat.module.erp.service.erp;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.zt.plat.module.api.InternalSupplyFactoryApi;
import com.zt.plat.module.api.dto.internalsupplyfactory.InternalSupplyFactoryDTO;
import com.zt.plat.module.erp.utils.ErpConfig;
import com.zt.plat.module.erp.utils.MyRedisConfig;
import com.zt.plat.module.erp.enums.OftenEnum;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpFactoryPageReqVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpFactoryRespVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpFactorySaveReqVO;
import com.zt.plat.module.erp.dal.dataobject.erp.ErpFactoryDO;
import com.zt.plat.module.erp.dal.mysql.erp.ErpFactoryMapper;
import jakarta.annotation.Resource;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.erp.enums.ErrorCodeConstants.*;
import static dm.jdbc.util.DriverUtil.log;

/**
 * ERP工厂 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class ErpFactoryServiceImpl implements ErpFactoryService {

    @Resource
    private ErpFactoryMapper erpFactoryMapper;

    @Resource
    private MyRedisConfig myRedisConfig;
    @Resource
    private ErpConfig erpConfig;
    @Resource
    private InternalSupplyFactoryApi internalSupplyFactoryApi;

    @Override
    public ErpFactoryRespVO createErpFactory(ErpFactorySaveReqVO createReqVO) {
        // 校验存在
        validateErpFactoryExistsNumber(createReqVO.getNumber());
        // 插入
        ErpFactoryDO erpFactory = BeanUtils.toBean(createReqVO, ErpFactoryDO.class);
        // 工厂编码自动生成，格式 GC-0001,依次新增
//        if (erpFactory.getNumber() == null) {
//            String maxCode = erpFactoryMapper.selectMaxCode();
//            if (maxCode == null) {
//                erpFactory.setNumber("GC-0001");
//            } else {
//                String prefix = "GC-";
//                String numberPart = maxCode.substring(prefix.length());
//                int nextNumber = Integer.parseInt(numberPart) + 1;
//                String nextCode = prefix + String.format("%04d", nextNumber);
//                erpFactory.setNumber(nextCode);
//            }
//        }
        //工厂编码校验
     //   validateErpFactoryNumberExists(erpFactory);
        if (erpFactory.getType() == null || erpFactory.getType().isEmpty()) {
            erpFactory.setType("SPLY");
        }
        erpFactory.setIsEnable("1");
        erpFactoryMapper.insert(erpFactory);
        // 返回
        return BeanUtils.toBean(erpFactory, ErpFactoryRespVO.class);
    }

    private void validateErpFactoryNumberExists(ErpFactoryDO erpFactory) {
        String number = erpFactory.getNumber();
        if (number == null || number.isEmpty()) {
            throw exception(ERP_NUMBER_IS_NULL);
        }
        boolean exists = erpFactoryMapper.exists(new LambdaQueryWrapperX<ErpFactoryDO>().eq(ErpFactoryDO::getNumber, number));
        if (exists) {
            throw exception(ERP_NUMBER_EXISTS);
        }
    }

    @Override
    public void updateErpFactory(ErpFactorySaveReqVO updateReqVO) {
        // 校验存在
        validateErpFactoryExists(updateReqVO.getId());
        // 更新
        ErpFactoryDO updateObj = BeanUtils.toBean(updateReqVO, ErpFactoryDO.class);
        if (updateObj.getType().equals("ERP") || updateObj.getIsEnable().equals("1")) {
            throw exception(ERP_FACTORY_NOT_ALLOW_UPDATE);
        }

        erpFactoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteErpFactory(Long id) {
        // 校验存在
        validateErpFactoryExists(id);
        // 删除
        erpFactoryMapper.deleteById(id);
    }

    @Override
    public void deleteErpFactoryListByIds(List<Long> ids) {
        // 校验存在
        validateErpFactoryExists(ids);
        // 删除
        erpFactoryMapper.deleteByIds(ids);
    }

    private void validateErpFactoryExists(List<Long> ids) {
        List<ErpFactoryDO> list = erpFactoryMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ERP_FACTORY_NOT_EXISTS);
        }
    }

    private void validateErpFactoryExists(Long id) {
        if (erpFactoryMapper.selectById(id) == null) {
            throw exception(ERP_FACTORY_NOT_EXISTS);
        }
    }

    private void validateErpFactoryExistsNumber(String number) {
        List<ErpFactoryDO> list = erpFactoryMapper.selectList(new LambdaQueryWrapperX<ErpFactoryDO>())
                .stream().filter(erpFactoryDO -> erpFactoryDO.getNumber().equals(number)).toList();
        if (!list.isEmpty()) {
            throw exception(ERP_FACTORY_EXISTS);
        }
    }

    @Override
    public ErpFactoryDO getErpFactory(Long id) {
        return erpFactoryMapper.selectById(id);
    }

    @Override
    public PageResult<ErpFactoryDO> getErpFactoryPage(ErpFactoryPageReqVO pageReqVO) {
        // 获取分页数据
        List<ErpFactoryDO> list = erpFactoryMapper.getPageByReq(pageReqVO);
        if (list == null) {
            list = CollUtil.newArrayList();
        }
        // 分页处理
        int pageNo = pageReqVO.getPageNo();
        int pageSize = pageReqVO.getPageSize();
        int total = list.size();
        // 计算分页起始和结束位置
        int fromIndex = (pageNo - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        // 如果起始位置超出范围，则返回空列表
        if (fromIndex >= total) {
            return new PageResult<>(new ArrayList<>(), (long) total);
        }
        // 截取当前页数据
        List<ErpFactoryDO> pageList = list.subList(fromIndex, toIndex);
        return new PageResult<>(pageList, (long) total);
    }

    @Override
    public List<ErpFactoryDO> getErpFactoryList() {
        return erpFactoryMapper.selectList(new LambdaQueryWrapperX<ErpFactoryDO>());
    }

    @Override
    public void enableFactoryList(List<ErpFactoryRespVO> saveReqVOS) {
        List<ErpFactoryDO> updateObj = BeanUtils.toBean(saveReqVOS, ErpFactoryDO.class);
        List<BatchResult> count = erpFactoryMapper.updateById(updateObj);
        if (CollUtil.isEmpty(count)) {
            throw exception(ERP_FACTORY_NOT_EXISTS);
        }
    }

    @Override
    @Transactional
    @XxlJob("getErpFactoryTask")
    public void callErpRfcInterface() {
        OftenEnum.FuncnrEnum funcnrEnum = OftenEnum.FuncnrEnum.工厂信息;
        String funcnr = funcnrEnum.getFuncnr();
        //防止缓存数据丢失
        String key = "erpMap" + funcnrEnum.getFuncnr();
        if (myRedisConfig.getRedisCacheMap(key).isEmpty()) {
            initializeMap(key);
        }
        // 1. 调用ERP接口获取数据
        Map<String, Object> req = new HashMap<>();
        JSONArray dataArrayALL = new JSONArray();
        String companykey = "erpMap" + OftenEnum.FuncnrEnum.公司代码.getFuncnr();
        Map<String, Long> redisCache = myRedisConfig.getRedisCacheMap(companykey);
        if (CollUtil.isEmpty(redisCache)) {
            throw exception(ERP_COMPANY_REDIS_NOT_EXISTS);
        }
        for (String companyNumber : redisCache.keySet()) {
            req.put("BUKRS", companyNumber);
            // 1. 调用ERP接口获取数据
            Map<String, Object> dataFromERP = erpConfig.fetchDataFromERP(funcnr, req);
            JSONArray dataArray = (JSONArray) dataFromERP.get("E_RESP");
            if (dataArray == null || dataArray.isEmpty()) {
                continue;
            }
            // 往每个子项中添加BUKRS字段
            for (int j = 0; j < dataArray.size(); j++) {
                JSONObject item = dataArray.getJSONObject(j);
                if (item != null) {
                    item.put("BUKRS", companyNumber);
                }
            }
            dataArrayALL.addAll(dataArray);
        }
        if (CollUtil.isEmpty(dataArrayALL)) {
            throw exception(ERP_FACTORY_NOT_EXISTS);
        }

        // 2. 处理公司数据，区分新增和更新
        ProcessingResult result = processData(dataArrayALL, funcnrEnum);

        // 3. 批量保存数据
        saveData(result);
    }

    /**
     * 处理数据，区分新增和更新
     */
    private ProcessingResult processData(JSONArray dataArray, OftenEnum.FuncnrEnum funcnr) {
        String key = "erpMap" + funcnr.getFuncnr();
        Map<String, Long> numbers = myRedisConfig.getRedisCacheMap(key);
        List<ErpFactoryDO> toUpdate = new ArrayList<>();
        List<ErpFactoryDO> toInsert = new ArrayList<>();

        List<String> dataArrayNumbers = new ArrayList<>();
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataJson = dataArray.getJSONObject(i);
            if (dataJson != null) {
                String number = dataJson.getString(funcnr.getDatakey()).trim();
                ErpFactoryDO DO = new ErpFactoryDO();
                DO.setName(dataJson.getString("NAME1"));
                DO.setNumber(number);
                DO.setErpCompanyNumber(dataJson.getString("BUKRS"));
                DO.setType("ERP");
                if (numbers.get(number) != null) {
                    // 更新
                    DO.setId(numbers.get(number));
                    toUpdate.add(DO);
                } else {
                    // 新增
                    toInsert.add(DO);
                }
                dataArrayNumbers.add(number);
            }
        }

        // 过滤出numbers中有，但dataArray中KOSTL没有的记录，即为需要删除的数据
        List<String> deleteNumbers = new ArrayList<>();
        for (String number : numbers.keySet()) {
            if (!dataArrayNumbers.contains(number)) {
                deleteNumbers.add(number);
            }
        }
        return new ProcessingResult(toUpdate, toInsert, key, deleteNumbers);
    }

    /**
     * 批量保存数据
     */
    private void saveData(ProcessingResult result) {
        // 批量新增和更新
        if (!result.toInsert.isEmpty()) {
            //自动绑定工厂
            erpFactoryMapper.insertBatch(result.toInsert);
            //工厂绑定
           // internalSupplyFactoryApi.batchCreate(BeanUtils.toBean(result.toInsert, InternalSupplyFactoryDTO.class));
            // 批量查询刚插入数据的id，提升效率
            List<String> insertedNumbers = result.toInsert.stream()
                    .map(ErpFactoryDO::getNumber)
                    .collect(Collectors.toList());
            List<ErpFactoryDO> insertedRecords = erpFactoryMapper.selectList(
                    new LambdaQueryWrapperX<ErpFactoryDO>()
                            .in(ErpFactoryDO::getNumber, insertedNumbers)
            );
            Map<String, Long> numberIdMap = insertedRecords.stream()
                    .collect(Collectors.toMap(ErpFactoryDO::getNumber, ErpFactoryDO::getId));
            myRedisConfig.addRedisCacheMap(result.key, numberIdMap);
        }
        if (!result.toUpdate.isEmpty()) {
            erpFactoryMapper.updateBatch(result.toUpdate);
        }
        if (!result.deleteNumbers.isEmpty()) {
            // 使用 in 条件批量删除，提高删除效率
            erpFactoryMapper.delete(new LambdaQueryWrapperX<ErpFactoryDO>().in(ErpFactoryDO::getNumber, result.deleteNumbers));
            myRedisConfig.deleteRedisCacheMap(result.key, result.deleteNumbers);
        }
    }

    /**
     * 数据处理结果封装类
     */
    private static class ProcessingResult {
        private final List<ErpFactoryDO> toUpdate;
        private final List<ErpFactoryDO> toInsert;
        private final String key;
        private final List<String> deleteNumbers;

        public ProcessingResult(List<ErpFactoryDO> toUpdate, List<ErpFactoryDO> toInsert, String key, List<String> deleteNumbers) {
            this.toUpdate = toUpdate;
            this.toInsert = toInsert;
            this.key = key;
            this.deleteNumbers = deleteNumbers;
        }
    }

    private void initializeMap(String key) {
        Map<String, Long> existingNumbers = erpFactoryMapper.selectList(new LambdaQueryWrapperX<ErpFactoryDO>())
                .stream().filter(erpFactoryDO -> erpFactoryDO.getType().equals("ERP"))
                .collect(Collectors.toMap(ErpFactoryDO::getNumber, ErpFactoryDO::getId));
        myRedisConfig.addRedisCacheMap(key, existingNumbers);
    }
}