package com.example.demo.admin.module.user;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.example.demo.admin.common.ResponseDTO;
import com.example.demo.admin.interceptor.AdminInterceptor;
import com.example.demo.expand.excel.ExcelTester;
import com.example.demo.expand.excel.ExcelUserGameRecord;
import com.example.demo.expand.excel.MergeStrategyJoinTable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("admin/excelController")
public class ExcelController {

    @GetMapping("getUserGameRecord")
    public void getUserGameRecord(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //拦截-预处理
        ResponseDTO responseDTO = AdminInterceptor.preHandle(request);
        if (responseDTO != null) return;

        String sheetName = "用户游戏记录";

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        List<ExcelUserGameRecord> dataList = ExcelTester.listUserGameRecordList();
        AbstractMergeStrategy ms1 = new MergeStrategyJoinTable<>(
                dataList, 0, 13,
                (now, last) -> {
                    if (now.getId() == last.getId()) {
                        return 1;
                    }
                    return 0;
                }
        );
        AbstractMergeStrategy ms2 = new MergeStrategyJoinTable<>(
                dataList, 13, 22,
                (now, last) -> {
                    if (now.getId() == last.getId() && now.getDate().equals(last.getDate())) {
                        return 1;
                    }
                    return 0;
                }
        );

        EasyExcel.write(response.getOutputStream(), ExcelUserGameRecord.class)
                .sheet(sheetName)
                .registerWriteHandler(ms1)
                .registerWriteHandler(ms2)
                .doWrite(dataList);
    }
}
