package shop.alien.store.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.LifeUserExpertOrder;
import shop.alien.entity.store.vo.LifeUserExpertOrderVo;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.LifeUserExpertOrderMapper;
import shop.alien.store.service.LifeUserExpertOrderService;
import shop.alien.util.common.ListToPage;
import shop.alien.util.type.LifeNoticeUtil;

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;

/**
 * <p>
 * 达人订单表 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-02-19
 */
@Service
@RequiredArgsConstructor
public class LifeUserExpertOrderServiceImpl extends ServiceImpl<LifeUserExpertOrderMapper, LifeUserExpertOrder> implements LifeUserExpertOrderService {

    private final LifeUserExpertOrderMapper lifeUserExpertOrderMapper;
    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    @Override
    public IPage<LifeUserExpertOrderVo> getExpertOrderList(int page, int size, String orderNo, String storeName) {
        QueryWrapper<LifeUserExpertOrderVo> wrapper = new QueryWrapper<>();
        wrapper.eq("orders.delete_flag", 0);
        wrapper.like(StringUtils.isNotEmpty(orderNo), "orders.orderNo", orderNo);
        wrapper.like(StringUtils.isNotEmpty(storeName), "store.store_name", storeName);
        wrapper.orderByDesc("actualPlayCount");
        wrapper.orderByDesc("actual_gmv");
        return lifeUserExpertOrderMapper.getExpertOrderList(new Page<>(page, size), wrapper);
    }

    @Override
    public List<LifeUserExpertOrderVo> getExpertOrderDetails(Long expertId) {
        return lifeUserExpertOrderMapper.getExpertOrderDetails(expertId);
    }

    @Override
    public IPage<LifeUserExpertOrderVo> getPromotionOrderInfoList(Long expertId, int page, int size) {
        List<LifeUserExpertOrderVo> data=lifeUserExpertOrderMapper.getPromotionOrderInfoList(expertId);
            return ListToPage.setPage(data, page, size);
//        return lifeUserExpertOrderMapper.getPromotionOrderInfoList(expertId);
    }

    @Override
    public List<Map<String, Object>> fetchExpertOrderInfo(Long expertId, String orderId) {
        LifeUserExpertOrderVo lifeUserExpertOrderVos = lifeUserExpertOrderMapper.fetchExpertOrderInfo(expertId, orderId);
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (lifeUserExpertOrderVos == null) {
            return dataList;
        }

        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> zijinliuxiang = new ArrayList<>();

        // 填充订单基本信息
        resultMap.put("id", lifeUserExpertOrderVos.getId());
        resultMap.put("orderNo", lifeUserExpertOrderVos.getOrderNo());
        resultMap.put("storeName", lifeUserExpertOrderVos.getStoreName());
        resultMap.put("orderMoney", lifeUserExpertOrderVos.getOrderMoney());
        resultMap.put("accountMoney", lifeUserExpertOrderVos.getAccountMoney());
        resultMap.put("orderTime", lifeUserExpertOrderVos.getOrderTime());
        resultMap.put("firstPaymentTime", lifeUserExpertOrderVos.getFirstPaymentTime());
        resultMap.put("orderPlayCount", lifeUserExpertOrderVos.getOrderPlayCount());
        resultMap.put("orderGmv", lifeUserExpertOrderVos.getOrderGmv());
        resultMap.put("actualPlayCount", lifeUserExpertOrderVos.getActualPlayCount());
        resultMap.put("statusName", lifeUserExpertOrderVos.getStatusName());
        resultMap.put("actualGmv", lifeUserExpertOrderVos.getActualGmv());
        resultMap.put("completedOrdersNumber", lifeUserExpertOrderVos.getCompletedOrdersNumber());
        resultMap.put("storeVisitViewCount", lifeUserExpertOrderVos.getStoreVisitViewCount());
        resultMap.put("firstFundsButton", lifeUserExpertOrderVos.getFirstFundsButton());
        resultMap.put("endFundsButton", lifeUserExpertOrderVos.getEndFundsButton());
        resultMap.put("name", lifeUserExpertOrderVos.getName());

        // 处理购买套餐状态
        Map<String, Object> buyMap = new HashMap<>();
        if (lifeUserExpertOrderVos.getOrderTime() != null) {
            buyMap.put("title", "购买套餐");
            buyMap.put("time", lifeUserExpertOrderVos.getOrderTime());
            buyMap.put("status", 1);
        } else {
            buyMap.put("title", "购买套餐");
            buyMap.put("status", 0);
        }
        zijinliuxiang.add(buyMap);

        // 处理首次平台打款状态
        Map<String, Object> firstPayMap = new HashMap<>();
        if (lifeUserExpertOrderVos.getFirstPaymentTime() != null) {
            firstPayMap.put("title", "首次平台打款");
            firstPayMap.put("time", lifeUserExpertOrderVos.getFirstPaymentTime());
            firstPayMap.put("status", 1);
            firstPayMap.put("amount", lifeUserExpertOrderVos.getAccountMoney());
        } else {
            firstPayMap.put("title", "平台打款");
            firstPayMap.put("status", 0);
        }
        zijinliuxiang.add(firstPayMap);

        // 处理发布作品状态
        Map<String, Object> pullMap = new HashMap<>();
        if (lifeUserExpertOrderVos.getEarliestCreatedTime() != null) {
            pullMap.put("title", "发布作品");
            pullMap.put("time", lifeUserExpertOrderVos.getEarliestCreatedTime());
            pullMap.put("status", 1);
        } else {
            pullMap.put("title", "发布作品");
            pullMap.put("status", 0);
        }
        zijinliuxiang.add(pullMap);


        // 处理达人完成任务状态
        Map<String, Object> completeMap = new HashMap<>();
        if (lifeUserExpertOrderVos.getCompleteTime() != null) {
            completeMap.put("title", "达人完成任务");
            completeMap.put("time", lifeUserExpertOrderVos.getCompleteTime());
            completeMap.put("status", 1);
        } else {
            completeMap.put("title", "达人完成任务");
            completeMap.put("status", 0);
        }
        zijinliuxiang.add(completeMap);

        // 处理尾次平台打款状态
        Map<String, Object> finalPayMap = new HashMap<>();
        if (lifeUserExpertOrderVos.getFinalPaymentTime() != null) {
            finalPayMap.put("title", "尾次平台打款");
            finalPayMap.put("time", lifeUserExpertOrderVos.getFinalPaymentTime());
            finalPayMap.put("status", 1);
            finalPayMap.put("amount", lifeUserExpertOrderVos.getAccountMoney());
        } else {
            finalPayMap.put("title", "平台打款");
            finalPayMap.put("status", 0);
        }
        zijinliuxiang.add(finalPayMap);

        // 将资金流向信息添加到结果 Map 中
        resultMap.put("zijinliuxiang", zijinliuxiang);

        // 将结果 Map 添加到数据列表中
        dataList.add(resultMap);

        return dataList;
    }

    @Override
    public List<LifeUserExpertOrderVo> getTalentPromotionOrder(String orderId, String expertId) {
        return lifeUserExpertOrderMapper.getTalentPromotionOrder(expertId, orderId);
    }

    @Override
    public Map<String, Object> getApplicationFunds(String buttonType, String buttonStatus ,String orderNo,String userPhone ) {
        Map<String, Object> resultMap = new HashMap<>();
        //buttonType 0: 首次打款 1: 尾次打款  buttonStatus  0未点击  1已点击审核中  2已点击审核通过
        if ("0".equals(buttonType)){
            String firstButton = "1";
            String endButton = "";
            lifeUserExpertOrderMapper.updateButton(firstButton,endButton,orderNo);
            resultMap.put("firstButton", buttonStatus);
            return resultMap;
        } else if ("1".equals(buttonType)) {
            String endButton = "1";
            String firstButton = "";
            lifeUserExpertOrderMapper.updateButton(firstButton,endButton,orderNo);
            resultMap.put("endButton", buttonStatus);
            LifeNotice lifeMessage = new LifeNotice();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = LocalDateTime.now().format(formatter);
            String text = "您在" + formattedDate + "提交的申请尾款信息，已提交至平台审核，1-3个工作日会将审核结果发送到您应用内的消息-通知中，请注意查收。";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", text);
            lifeMessage.setReceiverId("user_" + userPhone);
            lifeMessage.setTitle("申请尾款通知");
            lifeMessage.setContext(jsonObject.toJSONString());
            lifeMessage.setNoticeType(1);
            lifeMessage.setIsRead(0);
            lifeMessage.setDeleteFlag(0);
            lifeMessage.setSenderId("system");
            lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
            lifeNoticeMapper.insert(lifeMessage);
            return resultMap;
        }
        return resultMap;
    }
}
