package com.jjt.order.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jjt.common.core.redis.RedisCache;
import com.jjt.common.core.text.Convert;
import com.jjt.common.utils.DateUtils;
import com.jjt.common.utils.StringUtils;
import com.jjt.nccloud.utils.NccloudUtils;
import com.jjt.order.domain.TwinBom;
import com.jjt.order.domain.TwinOrder;
import com.jjt.order.domain.TwinOrderDetail;
import com.jjt.order.mapper.TwinOrderMapper;
import com.jjt.order.service.ITwinBomService;
import com.jjt.order.service.ITwinOrderDetailService;
import com.jjt.order.service.ITwinOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 销售订单信息Service业务层处理
 *
 * @author wukai
 * @date 2025-01-16
 */
@Service
public class TwinOrderServiceImpl implements ITwinOrderService {
    @Resource
    private TwinOrderMapper twinOrderMapper;
    @Resource
    private ITwinBomService bomService;
    @Resource
    private ITwinOrderDetailService detailService;

    /**
     * 查询销售订单信息
     *
     * @param oderId 销售订单信息主键
     * @return 销售订单信息
     */
    @Override
    public TwinOrder selectTwinOrderByOderId(Long oderId) {
        return twinOrderMapper.selectTwinOrderByOderId(oderId);
    }

    /**
     * 查询销售订单信息列表
     *
     * @param twinOrder 销售订单信息
     * @return 销售订单信息
     */
    @Override
    public List<TwinOrder> selectTwinOrderList(TwinOrder twinOrder) {
        return twinOrderMapper.selectTwinOrderList(twinOrder);
    }

    /**
     * 新增销售订单信息
     *
     * @param twinOrder 销售订单信息
     * @return 结果
     */
    @Override
    public int insertTwinOrder(TwinOrder twinOrder) {
        int rows = twinOrderMapper.insertTwinOrder(twinOrder);
        insertTwinOrderDetail(twinOrder);
        return rows;
    }

    /**
     * 修改销售订单信息
     *
     * @param twinOrder 销售订单信息
     * @return 结果
     */
    @Override
    public int updateTwinOrder(TwinOrder twinOrder) {
        twinOrderMapper.deleteTwinOrderDetailByOderId(twinOrder.getOderId());
        insertTwinOrderDetail(twinOrder);
        return twinOrderMapper.updateTwinOrder(twinOrder);
    }

    /**
     * 批量删除销售订单信息
     *
     * @param oderIds 需要删除的销售订单信息主键
     * @return 结果
     */
    @Override
    public int deleteTwinOrderByOderIds(String oderIds) {
        twinOrderMapper.deleteTwinOrderDetailByOderIds(Convert.toStrArray(oderIds));
        return twinOrderMapper.deleteTwinOrderByOderIds(Convert.toStrArray(oderIds));
    }

    /**
     * 删除销售订单信息信息
     *
     * @param oderId 销售订单信息主键
     * @return 结果
     */
    @Override
    public int deleteTwinOrderByOderId(Long oderId) {
        return twinOrderMapper.deleteTwinOrderByOderId(oderId);
    }

    /**
     * 按时间获取订单入库
     *
     * @param localDate 时间
     */
    @Override
    public void getOrder(LocalDate localDate) {
        String req = "{\"pk_org\":\"100101\",\"dbilldate\":\"%s~%s\"}";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime end = start.plusDays(1);
        req = String.format(req, start.format(formatter), end.format(formatter));
        try {
            String jsonStr = NccloudUtils.getData(req);
            JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
            if (!jsonObject.getBool("success")) {
                return;
            }

            List<TwinBom> bomList = bomService.selectTwinBomList(new TwinBom());
            Map<String, TwinBom> bomMap = bomList.stream().collect(Collectors.toMap(TwinBom::getBomCode, o -> o));

            JSONArray jsonArray = jsonObject.getJSONArray("data");
            // 输出 JsonArray 内容
            for (int i = 0; i < jsonArray.size(); i++) {
                TwinOrder twinOrder = new TwinOrder();
                JSONObject obj = jsonArray.getJSONObject(i);
                JSONObject order = obj.getJSONObject("so.so_saleorder");
                //客户号
                twinOrder.setCustomerCode(order.getByPath("ccustomerid.code", String.class));
                //客户名称
                twinOrder.setCustomerName(order.getByPath("ccustomerid.name", String.class));
                twinOrder.setOrderCode(order.getByPath("vbillcode", String.class));
                twinOrder.setOrderDate(DateUtils.parseDate(order.getByPath("dmakedate", String.class)));

                List<TwinOrderDetail> details = new ArrayList<>();
                JSONArray childOrder = obj.getJSONArray("so.so_saleorder_b");
                for (int j = 0; j < childOrder.size(); j++) {
                    JSONObject co = childOrder.getJSONObject(j);
                    TwinOrderDetail detail = new TwinOrderDetail();
                    String bomCode = co.getByPath("cmaterialvid.code", String.class);
                    detail.setUnit(co.getByPath("castunitid.name", String.class));
                    detail.setBomCode(bomCode);
                    detail.setBomName(co.getByPath("cmaterialvid.name", String.class));
                    detail.setColor(co.getByPath("vfree1.name", String.class));
                    detail.setPrice(co.getByPath("nqttaxnetprice", BigDecimal.class));
                    detail.setTotalPrice(co.getByPath("ntaxmny", BigDecimal.class));
                    detail.setNum(co.getByPath("nastnum", BigDecimal.class));
                    detail.setWeight(co.getByPath("nnum", BigDecimal.class));
                    TwinBom bom = bomMap.get(bomCode);
                    if (bom != null) {
                        detail.setBomWeight(bom.getBomWeight());
                        detail.setBomSpec(bom.getBomSpec());
                    }
                    details.add(detail);
                }
                twinOrder.setTwinOrderDetailList(details);
                insertTwinOrder(twinOrder);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 按时间获取订单信息
     *
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TwinOrder> selectTwinOrderListByDate(String start, String end) {
        TwinOrder order = new TwinOrder();
        Map<String, Object> params = new HashMap<>(16);
        params.put("start", start);
        params.put("end", end);
        order.setParams(params);
        List<TwinOrder> list = selectTwinOrderList(order);
        list.forEach(to -> {
            TwinOrderDetail tod = new TwinOrderDetail();
            tod.setOderId(to.getOderId());
            to.setTwinOrderDetailList(detailService.selectTwinOrderDetailList(tod));
        });
        return list;
    }

    /**
     * 新增销售订单明细信息信息
     *
     * @param twinOrder 销售订单信息对象
     */
    public void insertTwinOrderDetail(TwinOrder twinOrder) {
        List<TwinOrderDetail> twinOrderDetailList = twinOrder.getTwinOrderDetailList();
        Long oderId = twinOrder.getOderId();
        if (StringUtils.isNotNull(twinOrderDetailList)) {
            List<TwinOrderDetail> list = new ArrayList<TwinOrderDetail>();
            for (TwinOrderDetail twinOrderDetail : twinOrderDetailList) {
                twinOrderDetail.setOderId(oderId);
                list.add(twinOrderDetail);
            }
            if (list.size() > 0) {
                twinOrderMapper.batchTwinOrderDetail(list);
            }
        }
    }
}
