package cn.van.business.util;

import cn.van.business.enums.ValidCodeConverter;
import cn.van.business.model.jd.OrderRow;
import cn.van.business.repository.OrderRowRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

import static cn.van.business.util.WXUtil.getRemarkFromJdid;
import static cn.van.business.util.WXUtil.getWxidFromJdid;


/**
 * @author Leo
 * @version 1.0
 * @create 2024/11/29 11:43
 * @description：
 */
@Service
public class OrderUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OrderRowRepository orderRowRepository;
    @Autowired
    private WXUtil wxUtil;
    //标记唯一订单行：订单+sku维度的唯一标识
    private static final String ORDER_ROW_KEY = "jd:order:row:";
    private static final Logger logger = LoggerFactory.getLogger(OrderUtil.class);

    /**
     * 手动调用 将订单发送到微信
     */
    @Async("threadPoolTaskExecutor")
    public void orderToWx(OrderRow orderRow, Boolean isAutoFlush) {
        // 获取订单当前状态
        Integer newValidCode = orderRow.getValidCode();
        String oldValidCode = redisTemplate.opsForValue().get(ORDER_ROW_KEY + orderRow.getId());

        // 检查Redis中是否有旧的状态码，没有的话赋予默认值
        Integer lastValidCode = oldValidCode != null ? Integer.parseInt(oldValidCode) : -100;

        // 这里使用了逻辑非(!)操作符来简化条件判断
        if (!isAutoFlush || !lastValidCode.equals(newValidCode)) {
            // 当 isAutoFlush 为 false 或状态确实有变化时，进行消息发送
            String content = getFormattedOrderInfo(orderRow, lastValidCode);
            String wxId = getWxidFromJdid(orderRow.getUnionId().toString());
            if (Util.isNotEmpty(wxId)) {
                wxUtil.sendTextMessage(wxId, content, 1, wxId, false);
            }
        }

        // 更新 Redis 状态值
        redisTemplate.opsForValue().set(ORDER_ROW_KEY + orderRow.getId(), String.valueOf(orderRow.getValidCode()));
        //logger.info("订单状态：{}  订单号：{}  sku：{}", orderRow.getValidCode(), orderRow.getOrderId(), orderRow.getSkuName());

    }

    /**
     * 手动调用 将订单发送到微信 批量
     */
    @Async("threadPoolTaskExecutor")
    public void orderToWxBatch(List<OrderRow> orderRowList) {
        if (!orderRowList.isEmpty()) {
            int i = 1;
            String wxId = getWxidFromJdid(orderRowList.get(0).getUnionId().toString());
            StringBuilder content = new StringBuilder();
            content.append("批量订单：\n\r ").append(" 共 ").append(orderRowList.size()).append("单 \r");
            List<OrderRow> filterList = orderRowList.stream().filter(orderRow -> orderRow.getValidCode() != 2
                    && orderRow.getValidCode() != 3).toList();
            content.append("移除 拆单或者取消 的订单, 共 ").append(filterList.size()).append("单: \n\r");
            for (OrderRow orderRow : filterList) {
                content.append("\r\n");
                content.append(i++).append("、");
                content.append(getFormattedOrderInfoBatch(orderRow));

            }
            if (Util.isNotEmpty(wxId)) {
                wxUtil.sendTextMessage(wxId, content.toString(), 1, wxId, false);
            }

        }

    }


    /**
     * 将数据库订单转化成微信所需要文本
     */
    public String getFormattedOrderInfo(OrderRow orderRow, Integer oldValidCode) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ValidCodeConverter converter = new ValidCodeConverter();
        Long unionId = orderRow.getUnionId();
        String remarkFromJdid = getRemarkFromJdid(String.valueOf(unionId));
        StringBuilder orderInfo = new StringBuilder()
                .append(" ").append(getEmjoy(orderRow.getValidCode())).append(" ")
                .append(converter.getCodeDescription(orderRow.getValidCode())).append("\r");

        //if (oldValidCode != -100 && !oldValidCode.equals(orderRow.getValidCode())) {
        //    orderInfo.insert(0, "从 ：" + getEmjoy(oldValidCode) + " "
        //        + converter.getCodeDescription(oldValidCode) + "\r变成  "
        //        + getEmjoy(orderRow.getValidCode()) + " "
        //        + converter.getCodeDescription(orderRow.getValidCode()) + "\r\n");
        //}

        orderInfo
                //+ "订单+sku：" + orderRow.getId() + "\r"
                .append("京粉备注：").append(remarkFromJdid).append("\r")
                .append("订单：").append(orderRow.getOrderId()).append("  (")
                .append(orderRow.getPlus() == 1 ? "plus" : "非plus").append(")\r")
                .append("名称：").append(orderRow.getSkuName()).append("\r\n")
                //+ "商品单价：" + orderRow.getPrice() + "\r"
                //+ "商品数量：" + orderRow.getSkuNum() + "\r"
                //+ "商品总价：" + (orderRow.getPrice() * orderRow.getSkuNum()) + "\r"
                .append("计佣金额：").append(orderRow.getEstimateCosPrice()).append("\r")
                //+ "金额：" + orderRow.getActualCosPrice() + "\r"
                .append("比例：").append(orderRow.getCommissionRate()).append("\r")
                .append("[Packet] 佣金：").append(orderRow.getEstimateFee()).append("\r\n")
                .append("下单：").append(formatter.format(orderRow.getOrderTime())).append("\r")
                .append("完成：").append(orderRow.getFinishTime() != null
                        ? formatter.format(orderRow.getFinishTime())
                        : "未完成").append("\r");

        return orderInfo.toString();
    }


    public String getEmjoy(Integer status) {
        return switch (status) {
            //[爱心]已付款
            case 16 -> "[爱心]";
            //[Wow] 待付款
            case 15 -> "[Wow]";
            //[心碎]已取消
            case 2, 3 -> "[心碎]";
            //[亲亲] 已完成
            case 17 -> "[亲亲]";
            //[Broken] 违规
            case 27, 28 -> "[Broken]";
            default -> "";
        };
    }


    /**
     * 将数据库订单转化成微信所需要文本 简洁版
     */
    public String getFormattedOrderInfoBatch(OrderRow orderRow) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ValidCodeConverter converter = new ValidCodeConverter();
        Long unionId = orderRow.getUnionId();
        String remarkFromJdid = getRemarkFromJdid(String.valueOf(unionId));

        //+ "订单+sku：" + orderRow.getId() + "\r"
        //+ "商品单价：" + orderRow.getPrice() + "\r"
        //+ "商品数量：" + orderRow.getSkuNum() + "\r"
        //+ "商品总价：" + (orderRow.getPrice() * orderRow.getSkuNum()) + "\r"
        //+ "计佣金额：" + orderRow.getEstimateCosPrice() + "\r"
        //+ "金额：" + orderRow.getActualCosPrice() + "\r"
        //+ "比例：" + orderRow.getCommissionRate() + "\r"
        //if (oldValidCode != -100) {
        //    if (!oldValidCode.equals(orderRow.getValidCode()))
        //        orderInfo = "从 ：" + (converter.getCodeDescription(oldValidCode)) + "\r变成  " +
        //                (converter.getCodeDescription(orderRow.getValidCode())) + "\r\n" + orderInfo;
        //}


        return "订单：" + orderRow.getOrderId() + "  (" + (orderRow.getPlus() == 1 ? "plus" : "非plus") + ")\r"
               +"京粉备注："+ remarkFromJdid + "\r"

                +"状态：" + (converter.getCodeDescription(orderRow.getValidCode())) + "\r"

                + "名称：" + orderRow.getSkuName() + "\r\n"
                //+ "商品单价：" + orderRow.getPrice() + "\r"
                //+ "商品数量：" + orderRow.getSkuNum() + "\r"
                //+ "商品总价：" + (orderRow.getPrice() * orderRow.getSkuNum()) + "\r"
                //+ "计佣金额：" + orderRow.getEstimateCosPrice() + "\r"

                //+ "金额：" + orderRow.getActualCosPrice() + "\r"
                //+ "比例：" + orderRow.getCommissionRate() + "\r"
                + "佣金：" + orderRow.getEstimateFee() + "\r\n"

                + "下单：" + formatter.format(orderRow.getOrderTime()) + "\r"
                + "完成：" + (orderRow.getFinishTime() != null ? formatter.format(orderRow.getFinishTime()) : "未完成") + "\r";
    }
}
