package com.sckw.mine.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.TenantUtil;
import com.sckw.core.web.response.HttpResult;
import com.sckw.mine.common.OrderServerCommon;
import com.sckw.mine.entity.KwBusinessActionTrack;
import com.sckw.mine.entity.KwBusinessMine;
import com.sckw.mine.entity.KwBusinessMineOrder;
import com.sckw.mine.entity.KwBusinessTransportOrderNo;
import com.sckw.mine.entity.req.CompleteOrderParam;
import com.sckw.mine.entity.req.MineOrderPageListParam;
import com.sckw.mine.entity.req.MineAddParam;
import com.sckw.mine.entity.res.MineOrderDetailRes;
import com.sckw.mine.entity.res.MineOrderPageListRes;
import com.sckw.mine.entity.res.OrderFlowStepRes;
import com.sckw.mine.enums.MineStatusEnum;
import com.sckw.mine.enums.TransportUnderEnum;
import com.sckw.mine.mapper.KwBusinessActionTrackMapper;
import com.sckw.mine.mapper.MineMapper;
import com.sckw.mine.mapper.MineOrderMapper;
import com.sckw.mine.mapper.TransportOrderNoMapper;
import com.sckw.redis.utils.GenOrderCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: Lt
 * @date: 2024-05-27
 */
@Service
public class MineService {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @Autowired
    MineOrderMapper mineOrderMapper;

    @Autowired
    TransportOrderNoMapper transportOrderNoMapper;

    @Autowired
    MineMapper mineMapper;

    @Autowired
    KwBusinessActionTrackMapper kwBusinessActionTrackMapper;

    @Autowired
    private GenOrderCode genOrderCode;

    @Autowired
    OrderServerCommon orderServerCommon;

    /**
     * @Description: 矿山域订单添加
     * @Author: Lt
     * @Date: 2024/5/27 9:43
     */
    public String mineOrderAdd(MineAddParam mineAddParam) throws Exception {
        try {
            Long orderId = new IdWorker(1L).nextId();
            KwBusinessMineOrder kwBusinessMineOrder = BeanUtil.copyProperties(mineAddParam, KwBusinessMineOrder.class);
            //生成订单编号
            String mineOrderNo = orderServerCommon.generatorNum("M", 13);

            //生成物流订单编号- 空了再来封装了
            String usualTransportOrderNo = orderServerCommon.generatorNum("O", 12);
            kwBusinessMineOrder.setId(orderId);
            kwBusinessMineOrder.setMineOrderNo(mineOrderNo);
            kwBusinessMineOrder.setTenantId(TenantUtil.getTenant());   //租户id
            kwBusinessMineOrder.setMineralAggregateId(mineAddParam.getMineralAggregateId());
            kwBusinessMineOrder.setOrderSource(1);
            int insert = mineOrderMapper.insert(kwBusinessMineOrder);
            if (insert > 0) {
                //生成kw_business_transport_order_no
                //如果是自有物流生成物流订单号
                if (mineAddParam.getIsTransport().equals(TransportUnderEnum.ONE.getCode())) {
                    KwBusinessTransportOrderNo kwBusinessTransportOrderNo = new KwBusinessTransportOrderNo();
                    kwBusinessTransportOrderNo.setId(new IdWorker(1L).nextId());
                    kwBusinessTransportOrderNo.setMineOrderId(orderId);
                    kwBusinessTransportOrderNo.setTransportOrderNo(usualTransportOrderNo);
                    transportOrderNoMapper.insert(kwBusinessTransportOrderNo);
                }
                KwBusinessMine kwBusinessMine = new KwBusinessMine();
                kwBusinessMine.setId(new IdWorker(1L).nextId());
                kwBusinessMine.setMineOrderId(orderId);
                kwBusinessMine.setMineVol(mineAddParam.getMineVol());
                kwBusinessMine.setMineWeight(mineAddParam.getMineWeight());
                kwBusinessMine.setPurchaseNum(mineAddParam.getPurchaseNum());
                mineMapper.insert(kwBusinessMine);
            }
            //添加操作记录
            orderServerCommon.saveActionTrack(orderId, mineAddParam.getStatus(), null, "T");

            return "添加成功";
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

    }

    /**
     * @Description: 列表分页查询
     * @Author: Lt
     * @Date: 2024/5/27 14:49
     */
    public HttpResult pageList(MineOrderPageListParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<MineOrderPageListRes> businessTruckPageListRes = mineOrderMapper.mineOrderPageList(param);
        businessTruckPageListRes.forEach(e -> {
            if (ObjectUtils.isNotNull(e.getOrderSource())) {
                e.setOrderSourceStr(e.getOrderSource() == 1 ? "生产自建" : "销售流转");
            }
        });
        return HttpResult.ok(new PageRes<>(new PageInfo<>(businessTruckPageListRes)));
    }

    /**
     * @Description: 订单详情
     * @Author: Lt
     * @Date: 2024/5/27 0027 15:54
     */
    public MineOrderDetailRes detail(String orderId) {
        MineOrderDetailRes kwBusinessMineOrder = mineOrderMapper.selectOrderById(orderId);
        if (ObjectUtils.isNull(kwBusinessMineOrder)) {
            throw new RuntimeException("当前数据不存在");
        }
        if (ObjectUtils.isNotNull(kwBusinessMineOrder.getStatus())) {
            kwBusinessMineOrder.setStatusStr(MineStatusEnum.getNameByCode(kwBusinessMineOrder.getStatus()));
        }
        if (ObjectUtils.isNotNull(kwBusinessMineOrder.getOrderSource())) {
            kwBusinessMineOrder.setOrderSourceStr(kwBusinessMineOrder.getOrderSource() == 1 ? "生产自建" : "销售流转");
        }

        return kwBusinessMineOrder;

    }


    public List<Map<String, Object>> getStatusCountListInSingleQuery() {
        // 查询每个状态的计数
        List<Map<String, Object>> statusCounts = mineOrderMapper.countByStatus();

        // 将查询结果转换为所需的格式
        List<MineStatusEnum> sortedEnums = MineStatusEnum.getSortList();
        List<Map<String, Object>> result = new ArrayList<>();
        for (MineStatusEnum enumItem : sortedEnums) {
            Map<String, Object> statusCount = statusCounts.stream()
                    .filter(c -> enumItem.getCode().equals(c.get("status")))
                    .findFirst()
                    .orElseGet(() -> Map.of("status", enumItem.getCode(), "count", 0));
            result.add(
                    Map.of(
                            "key", enumItem.getMsg(),
                            "value", enumItem.getCode(),
                            "data", statusCount.get("count")
                    )
            );
        }
        return result;
    }

    public List<OrderFlowStepRes> getActionTrackByMineOrderId(String orderId) {
        //TODO 根据订单的work_flow字段决定是哪一个订单流


        // 定义订单的标准流程
        List<MineStatusEnum> orderFlowEnums = MineStatusEnum.getSortList();
        List<OrderFlowStepRes> orderFlowSteps = orderFlowEnums.stream()
                .map(e -> new OrderFlowStepRes(e.getMsg(), "gray"))
                .collect(Collectors.toList());

        // 获取订单的操作记录
        List<KwBusinessActionTrack> actionTracks = kwBusinessActionTrackMapper.findByMainOrderIdOrderByCreateTime(orderId);

        boolean orderCompleted = false;
        int completedStepIndex = -1;

        for (KwBusinessActionTrack actionTrack : actionTracks) {
            if (actionTrack.getStatus().equals(MineStatusEnum.EIGHT.getCode())) {
                orderCompleted = true;
                break;
            }
            for (int i = 0; i < orderFlowSteps.size(); i++) {
                OrderFlowStepRes step = orderFlowSteps.get(i);
                if (step.getName().equals(MineStatusEnum.getNameByCode(actionTrack.getStatus()))) {
                    step.setColor("green");
                    completedStepIndex = i;
                }
            }
        }

        // 设置提前完结步骤
        if (orderCompleted && completedStepIndex != -1) {
            OrderFlowStepRes completedStep = orderFlowSteps.get(completedStepIndex);
            completedStep.setName(completedStep.getName() + "(提前完结)");
            completedStep.setColor("orange");

            for (int i = 0; i < completedStepIndex; i++) {
                orderFlowSteps.get(i).setColor("green");
            }

            for (int i = completedStepIndex + 1; i < orderFlowSteps.size(); i++) {
                orderFlowSteps.get(i).setColor("gray");
            }
        }

        return orderFlowSteps;
    }

    /**
    * @Description: 提前完结
    * @Author: Lt
    * @Date: 2024/5/28 11:26
    */
    public String completeOrder(CompleteOrderParam completeOrderParam)
    {
        KwBusinessMineOrder kwBusinessMineorder = mineOrderMapper.selectById(completeOrderParam.getOrderId());
        if (ObjectUtils.isNull(kwBusinessMineorder))
        {
            throw new RuntimeException("未找到当前订单");
        }
        if(kwBusinessMineorder.getIsTransport() != 2){
            throw new RuntimeException("当前订单不是非自有订单");
        }
        if (kwBusinessMineorder.getStatus().equals(MineStatusEnum.EIGHT.getCode())) {
            throw new RuntimeException("当前订单已完结,请勿重复操作");
        }
        kwBusinessMineorder.setStatus(MineStatusEnum.EIGHT.getCode());
        mineOrderMapper.updateById(kwBusinessMineorder);
        orderServerCommon.saveActionTrack(Long.valueOf(completeOrderParam.getOrderId()), MineStatusEnum.NINE.getCode(), completeOrderParam.getRemark(),"T");

        return "完结成功";


    }


}
