package com.zksy.park.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.core.domain.Result;
import com.zksy.park.domain.SmartEmployment;
import com.zksy.park.listener.SmartEmploymentListener;
import com.zksy.park.mapper.SmartEmploymentMapper;
import com.zksy.park.service.SmartEmploymentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 智慧用工
 */
@Service
public class SmartEmploymentServiceImpl extends ServiceImpl<SmartEmploymentMapper, SmartEmployment> implements SmartEmploymentService {

    @Override
    public void exportExcel(HttpServletResponse response) {
        String fileName = "智慧用工.xlsx";
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + encodedFileName);

            try (ServletOutputStream out = response.getOutputStream()) {
                ExcelWriter excelWriter = EasyExcel.write(out, SmartEmployment.class).build();
                WriteSheet sheet = EasyExcel.writerSheet("智慧用工").build();

                int pageNum = 1;
                int pageSize = 1000;
                List<SmartEmployment> pageData;

                do {
                    Page<SmartEmployment> page = new Page<>(pageNum, pageSize);
                    Page<SmartEmployment> result = this.page(page); // MyBatis-Plus 分页查询
                    pageData = result.getRecords();

                    if (pageData != null && !pageData.isEmpty()) {
                        excelWriter.write(pageData, sheet);
                    }
                    pageNum++;
                } while (pageData != null && !pageData.isEmpty());

                excelWriter.finish();
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("导出Excel数据失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Object> importExcel(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.endsWith(".xlsx")) {
            return Result.error("请上传 Excel 文件(.xlsx)");
        }

        try {
            EasyExcel.read(file.getInputStream(), SmartEmployment.class,
                            new SmartEmploymentListener(this)) // 把 ServiceImpl 传进去
                    .sheet()
                    .doRead();

            return Result.ok("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入 Excel 失败：" + e.getMessage());
        }
    }
}
