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.module.erp.controller.admin.erp.vo.ErpProductiveVersionPageReqVO;
import com.zt.plat.module.erp.dal.dataobject.erp.ErpProductiveVersionDO;
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.ErpProductiveOrderPageReqVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpProductiveOrderRespVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpProductiveOrderSaveReqVO;
import com.zt.plat.module.erp.dal.dataobject.erp.ErpProductiveOrderDO;
import com.zt.plat.module.erp.dal.mysql.erp.ErpProductiveOrderMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 ErpProductiveOrderServiceImpl implements ErpProductiveOrderService {

    @Resource
    private ErpProductiveOrderMapper erpProductiveOrderMapper;

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

    @Override
    public ErpProductiveOrderRespVO createErpProductiveOrder(ErpProductiveOrderSaveReqVO createReqVO) {
        // 插入
        ErpProductiveOrderDO erpProductiveOrder = BeanUtils.toBean(createReqVO, ErpProductiveOrderDO.class);
        erpProductiveOrderMapper.insert(erpProductiveOrder);
        // 返回
        return BeanUtils.toBean(erpProductiveOrder, ErpProductiveOrderRespVO.class);
    }

    @Override
    public void updateErpProductiveOrder(ErpProductiveOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateErpProductiveOrderExists(updateReqVO.getId());
        // 更新
        ErpProductiveOrderDO updateObj = BeanUtils.toBean(updateReqVO, ErpProductiveOrderDO.class);
        erpProductiveOrderMapper.updateById(updateObj);
    }

    @Override
    public void deleteErpProductiveOrder(Long id) {
        // 校验存在
        validateErpProductiveOrderExists(id);
        // 删除
        erpProductiveOrderMapper.deleteById(id);
    }

    @Override
    public void deleteErpProductiveOrderListByIds(List<Long> ids) {
        // 校验存在
        validateErpProductiveOrderExists(ids);
        // 删除
        erpProductiveOrderMapper.deleteByIds(ids);
    }

    private void validateErpProductiveOrderExists(List<Long> ids) {
        List<ErpProductiveOrderDO> list = erpProductiveOrderMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ERP_PRODUCTIVE_ORDER_NOT_EXISTS);
        }
    }

    private void validateErpProductiveOrderExists(Long id) {
        if (erpProductiveOrderMapper.selectById(id) == null) {
            throw exception(ERP_PRODUCTIVE_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public ErpProductiveOrderDO getErpProductiveOrder(Long id) {
        return erpProductiveOrderMapper.selectById(id);
    }

    @Override
    public PageResult<ErpProductiveOrderDO> getErpProductiveOrderPage(ErpProductiveOrderPageReqVO pageReqVO) {
        return erpProductiveOrderMapper.selectPage(pageReqVO);
    }

    //直接从erp查询生产订单
//    @Override
//    public PageResult<ErpProductiveOrderDO> getErpProductiveOrderPage(ErpProductiveOrderPageReqVO pageReqVO) {
//        OftenEnum.FuncnrEnum funcnrEnum = OftenEnum.FuncnrEnum.生产订单;
//        String funcnr = funcnrEnum.getFuncnr();
//        Map<String, Object> req = new HashMap<>();
//
//        // 构建查询参数
//        req.put("BUKRS", pageReqVO.getCompanyNumber());
//        req.put("WERKS", pageReqVO.getFactoryNumber());
//
//        // 处理日期参数
//        if (pageReqVO.getStartDate() != null) {
//            req.put("BEGDA", pageReqVO.getStartDate()[0].format(DateTimeFormatter.ofPattern("yyyyMMdd")));
//        }
//        if (pageReqVO.getEndDate() != null) {
//            req.put("ENDDA", pageReqVO.getEndDate()[0].format(DateTimeFormatter.ofPattern("yyyyMMdd")));
//        }
//
//        // 调用ERP接口获取数据
//        HashMap<String, Object> dataFromERP = erpConfig.fetchDataFromERP(funcnr, req);
//        JSONArray dataArray = (JSONArray) dataFromERP.get("E_RESP");
//        if (dataArray == null || dataArray.isEmpty()) {
//            // 返回空结果而不是抛出异常
//            return new PageResult<>(new ArrayList<>(), 0L);
//        }
//
//        List<ErpProductiveOrderDO> list = new ArrayList<>();
//        for (int i = 0; i < dataArray.size(); i++) {
//            JSONObject dataJson = dataArray.getJSONObject(i);
//            if (dataJson != null) {
//                ErpProductiveOrderDO orderDO = new ErpProductiveOrderDO();
//
//                // 基本信息
//                orderDO.setCompanyNumber(dataJson.getString("BUKRS"));
//                orderDO.setFactoryNumber(dataJson.getString("WERKS").trim());
//                orderDO.setFactoryName(dataJson.getString("NAME1"));
//                orderDO.setOrderNumber(dataJson.getString("AUFNR"));
//
//                // 日期处理
//                String plannedStartDate = dataJson.getString("GLTRP");
//                String actualStartDate = dataJson.getString("GSTRP");
//
//                if (plannedStartDate != null && !plannedStartDate.equals("0000-00-00")) {
//                    try {
//                        orderDO.setStartDate(LocalDateTime.parse(plannedStartDate));
//                    } catch (Exception e) {
//                        // 忽略日期解析错误
//                    }
//                }
//
//                if (actualStartDate != null && !actualStartDate.equals("0000-00-00")) {
//                    try {
//                        orderDO.setEndDate(LocalDateTime.parse(actualStartDate));
//                    } catch (Exception e) {
//                        // 忽略日期解析错误
//                    }
//                }
//
//                // 物料和工艺信息
//                orderDO.setMainMaterialNumber(dataJson.getString("STLBEZ"));
//                orderDO.setUnit(dataJson.getString("GMEIN"));
//                orderDO.setMaterialDescription(dataJson.getString("MAKTX"));
//                orderDO.setProcessingList(dataJson.getString("L_AFVC"));
//                orderDO.setProcessingNumber(dataJson.getString("VORNR"));
//                orderDO.setProcessingDescription(dataJson.getString("LTXA1"));
//                orderDO.setObjectNumber(dataJson.getString("OBJID"));
//                orderDO.setWorkCenterNumber(dataJson.getString("ARBPL"));
//                orderDO.setWorkCenterDescription(dataJson.getString("KTEXT"));
//                orderDO.setCostcenterNumber(dataJson.getString("KOSTL"));
//                orderDO.setCostcenterName(dataJson.getString("TEXT_C"));
//
//                list.add(orderDO);
//            }
//        }
//
//        // 返回分页结果
//        return new PageResult<>(list, (long) list.size());
//    }

    @Override
    @Transactional
    @XxlJob("getErpProductiveOrderTask")
    public void callErpRfcInterface() {
        OftenEnum.FuncnrEnum funcnrEnum = OftenEnum.FuncnrEnum.生产订单;
        String funcnr = funcnrEnum.getFuncnr();

        Map<String, Object> req = new HashMap<>();
        List<Map<String, String>> datumList = new ArrayList<>();
        Map<String, String> datumEntry = new HashMap<>();
        // 构建datum参数数组
        datumEntry.put("sign", "I");
        datumEntry.put("option", "EQ");
        datumEntry.put("low", LocalDate.now().toString());
        datumList.add(datumEntry);
        req.put(funcnrEnum.getDatekey(), datumList);
        JSONArray dataArrayALL = new JSONArray();
        List<String> redisCache = myRedisConfig.getRedisCache(OftenEnum.FuncnrEnum.工厂信息.getFuncnr());
        if (CollUtil.isEmpty(redisCache)) {
            throw exception(ERP_FACTORY_NOT_EXISTS);
        }
        // 1. 调用ERP接口获取数据
        for (String number : redisCache) {
            req.put("WERKS", number);
            // 1. 调用ERP接口获取数据
            HashMap<String, Object> dataFromERP = erpConfig.fetchDataFromERP(funcnr, req);
            JSONArray dataArray = (JSONArray) dataFromERP.get("E_RESP");
            if (dataArray == null || dataArray.isEmpty()) {
                continue;
            }
            dataArrayALL.addAll(dataArray);
        }
        if (dataArrayALL.isEmpty()) {
            throw exception(ERP_PRODUCTIVE_ORDER_NOT_EXISTS);
        }

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

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

    /**
     * 处理数据，区分新增和更新
     */
    private ProcessingResult processData(JSONArray dataArray, OftenEnum.FuncnrEnum funcnr) {
        String key = "erp" + funcnr.getFuncnr();
        Map<String, List<String>> numbers = myRedisConfig.numbers(dataArray, key, funcnr.getDatakey());
        List<String> allnumbers = numbers.get("all");
        List<String> comnumbers = numbers.get("com");
        List<ErpProductiveOrderDO> toUpdate = new ArrayList<>();
        List<ErpProductiveOrderDO> toInsert = new ArrayList<>();

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataJson = dataArray.getJSONObject(i);
            if (dataJson != null) {
                String number = dataJson.getString("BUKRS").trim();
                if (number != null) {
                    ErpProductiveOrderDO DO = new ErpProductiveOrderDO();
//                    DO.setName(dataJson.getString("BUTXT"));
//                    DO.setNumber(number);
//                    DO.setCurrency(dataJson.getString("WAERS"));
                    if (comnumbers.contains(number)) {
                        // 更新
                        toUpdate.add(DO);
                    } else {
                        // 新增
                        toInsert.add(DO);
                    }
                }
            }
        }

        return new ProcessingResult(toUpdate, toInsert, key, allnumbers);
    }

    /**
     * 批量保存数据
     */
    private void saveData(ProcessingResult result) {
        // 批量新增和更新
        if (!result.toInsert.isEmpty()) {
            erpProductiveOrderMapper.insertBatch(result.toInsert);
        }
        if (!result.toUpdate.isEmpty()) {
            erpProductiveOrderMapper.updateBatch(result.toUpdate);
        }
        myRedisConfig.updateRedisCache(result.key, result.allnumbers);
    }

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

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