package com.liquidnet.service.slime.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.kylin.constant.GroupBuyStatusConst;
import com.liquidnet.service.kylin.dto.vo.groupbuy.KylinGroupBuyPartnerOrderListVo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 拼团订单列表导出（EasyExcel，对齐 goblin exportOrderList）。
 */
public final class GroupBuyOrderExcelUtil {

    private GroupBuyOrderExcelUtil() {
    }

    public static void export(List<KylinGroupBuyPartnerOrderListVo> rows, HttpServletResponse response) throws IOException {
        if (CollectionUtils.isEmpty(rows)) {
            return;
        }
        ServletOutputStream outputStream = null;
        try {
            String fileName = DateUtil.Formatter.yyyyMMddHHmmssTrim.format(LocalDateTime.now())
                    .concat(new String(("拼团订单").getBytes("gb2312"), StandardCharsets.ISO_8859_1));
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment;filename=".concat(fileName).concat(ExcelTypeEnum.XLSX.getValue()));
            response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            outputStream = response.getOutputStream();
            EasyExcel.write(outputStream)
                    .head(buildHead())
                    .sheet("拼团订单")
                    .doWrite(buildRows(rows));
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception ignored) {
                }
            }
        }
    }

    private static List<List<String>> buildHead() {
        List<List<String>> head = new ArrayList<>();
        head.add(Collections.singletonList("订单号"));
        head.add(Collections.singletonList("拼团活动"));
        head.add(Collections.singletonList("发起人"));
        head.add(Collections.singletonList("参团人数"));
        head.add(Collections.singletonList("成团人数"));
        head.add(Collections.singletonList("订单金额"));
        head.add(Collections.singletonList("创建时间"));
        head.add(Collections.singletonList("状态"));
        return head;
    }

    private static List<List<String>> buildRows(List<KylinGroupBuyPartnerOrderListVo> list) {
        List<List<String>> rows = new ArrayList<>(list.size());
        for (KylinGroupBuyPartnerOrderListVo vo : list) {
            List<String> row = new ArrayList<>(8);
            row.add(nullToEmpty(vo.getGroupOrderId()));
            row.add(nullToEmpty(vo.getActivityName()));
            row.add(nullToEmpty(vo.getLeaderNickname()));
            row.add(formatProgress(vo.getCurrentCount(), vo.getTargetCount()));
            row.add(vo.getTargetCount() == null ? "" : vo.getTargetCount() + "人");
            row.add(formatAmount(vo.getOrderAmount()));
            row.add(nullToEmpty(vo.getCreatedAt()));
            row.add(statusText(vo.getStatus()));
            rows.add(row);
        }
        return rows;
    }

    private static String formatProgress(Integer current, Integer target) {
        int c = current == null ? 0 : current;
        int t = target == null ? 0 : target;
        return c + "/" + t + "人";
    }

    private static String formatAmount(BigDecimal amount) {
        if (amount == null) {
            return "";
        }
        return amount.setScale(2, RoundingMode.HALF_UP).toPlainString();
    }

    private static String statusText(Integer status) {
        if (status == null) {
            return "";
        }
        if (GroupBuyStatusConst.OrderStatus.PENDING.equals(status)) {
            return "拼团中";
        }
        if (GroupBuyStatusConst.OrderStatus.SUCCESS.equals(status)) {
            return "拼团成功";
        }
        if (GroupBuyStatusConst.OrderStatus.FAILED.equals(status)) {
            return "拼团失败";
        }
        if (GroupBuyStatusConst.OrderStatus.PREPARE.equals(status)) {
            return "待支付发起";
        }
        if (GroupBuyStatusConst.OrderStatus.CANCELLED.equals(status)) {
            return "已取消";
        }
        return String.valueOf(status);
    }

    private static String nullToEmpty(String s) {
        return s == null ? "" : s;
    }
}
