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.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.ErpCostcenterPageReqVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpCostcenterRespVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpCostcenterSaveReqVO;
import com.zt.plat.module.erp.dal.dataobject.erp.ErpCostcenterDO;
import com.zt.plat.module.erp.dal.mysql.erp.ErpCostcenterMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
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.ERP_CONTRACT_NOT_EXISTS;
import static com.zt.plat.module.erp.enums.ErrorCodeConstants.ERP_COSTCENTER_NOT_EXISTS;
import static dm.jdbc.util.DriverUtil.log;

/**
 * ERP成本中心 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class ErpCostcenterServiceImpl implements ErpCostcenterService {

    @Resource
    private ErpCostcenterMapper erpCostcenterMapper;

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

    @Override
    public ErpCostcenterRespVO createErpCostcenter(ErpCostcenterSaveReqVO createReqVO) {
        // 插入
        ErpCostcenterDO erpCostcenter = BeanUtils.toBean(createReqVO, ErpCostcenterDO.class);
        erpCostcenterMapper.insert(erpCostcenter);
        // 返回
        return BeanUtils.toBean(erpCostcenter, ErpCostcenterRespVO.class);
    }

    @Override
    public void updateErpCostcenter(ErpCostcenterSaveReqVO updateReqVO) {
        // 校验存在
        validateErpCostcenterExists(updateReqVO.getId());
        // 更新
        ErpCostcenterDO updateObj = BeanUtils.toBean(updateReqVO, ErpCostcenterDO.class);
        erpCostcenterMapper.updateById(updateObj);
    }

    @Override
    public void deleteErpCostcenter(Long id) {
        // 校验存在
        validateErpCostcenterExists(id);
        // 删除
        erpCostcenterMapper.deleteById(id);
    }

    @Override
    public void deleteErpCostcenterListByIds(List<Long> ids) {
        // 校验存在
        validateErpCostcenterExists(ids);
        // 删除
        erpCostcenterMapper.deleteByIds(ids);
    }

    private void validateErpCostcenterExists(List<Long> ids) {
        List<ErpCostcenterDO> list = erpCostcenterMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ERP_COSTCENTER_NOT_EXISTS);
        }
    }

    private void validateErpCostcenterExists(Long id) {
        if (erpCostcenterMapper.selectById(id) == null) {
            throw exception(ERP_COSTCENTER_NOT_EXISTS);
        }
    }

    @Override
    public ErpCostcenterDO getErpCostcenter(Long id) {
        return erpCostcenterMapper.selectById(id);
    }

    @Override
    public PageResult<ErpCostcenterDO> getErpCostcenterPage(ErpCostcenterPageReqVO pageReqVO) {
        return erpCostcenterMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional
    @XxlJob("getErpCostcenterTask")
    public void callErpRfcInterface() {
        OftenEnum.FuncnrEnum funcnrEnum = OftenEnum.FuncnrEnum.成本中心;
        String funcnr = funcnrEnum.getFuncnr();
        //防止缓存数据丢失
        String key = "erpMap" + funcnr;
        if (myRedisConfig.getRedisCacheMap(key).isEmpty()) {
            initializeMap(key);
        }
        Map<String, Object> req = new HashMap<>();
        JSONArray dataArrayALL = new JSONArray();
        String commanyKey = "erpMap" + OftenEnum.FuncnrEnum.公司代码.getFuncnr();
        Map<String, Long> redisCache = myRedisConfig.getRedisCacheMap(commanyKey);
        if (CollUtil.isEmpty(redisCache)) {
            return;
        }
        // 1. 调用ERP接口获取数据
        for (String number : redisCache.keySet()) {
            req.put("BUKRS", number);
            // 1. 调用ERP接口获取数据
            Map<String, Object> dataFromERP = erpConfig.fetchDataFromERP(funcnr, req);
            JSONArray dataArray = (JSONArray) dataFromERP.get("E_RESP");
            if (dataArray == null || dataArray.isEmpty()) {
                continue;
            }
            dataArrayALL.addAll(dataArray);
        }
        if (CollUtil.isEmpty(dataArrayALL)) {
            throw exception(ERP_COSTCENTER_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<ErpCostcenterDO> toUpdate = new ArrayList<>();
        List<ErpCostcenterDO> toInsert = new ArrayList<>();

        List<String> dataArrayNumbers = new ArrayList<>();
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataJson = dataArray.getJSONObject(i);
            if (dataJson != null) {
                ErpCostcenterDO DO = new ErpCostcenterDO();
                String number = dataJson.getString("KOSTL").trim();
                DO.setNumber(number);
                DO.setName(dataJson.getString("KTEXT"));
                DO.setIsUse(dataJson.getString("DRNAM"));
                DO.setScopeNumber(dataJson.getString("FKBER"));
                if (!dataJson.getString("DATAB").equals("0000-00-00")) {
                    DO.setStartDate(LocalDateTime.parse(dataJson.getString("DATAB") + "T00:00:00"));
                }
                if (!dataJson.getString("DATBI").equals("0000-00-00")) {
                    DO.setEndDate(LocalDateTime.parse(dataJson.getString("DATBI") + "T00:00:00"));
                }
                DO.setScopeName(dataJson.getString("FKBTX"));
                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, deleteNumbers, key);
    }

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

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

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

    private void initializeMap(String key) {
        Map<String, Long> existingNumbers = erpCostcenterMapper.selectList(new LambdaQueryWrapperX<ErpCostcenterDO>())
                .stream()
                .collect(Collectors.toMap(ErpCostcenterDO::getNumber, ErpCostcenterDO::getId));
        myRedisConfig.addRedisCacheMap(key, existingNumbers);
    }
}