package com.cpop.clockin.business.controller;

import com.alibaba.excel.EasyExcel;
import com.cpop.clockin.business.bo.EmployeeAttendanceBo;
import com.cpop.clockin.business.service.ClockInRecordService;
import com.cpop.clockin.framework.constant.ClockInConstant;
import com.cpop.core.base.R;
import com.cpop.core.service.RedisService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Yxz
 * @Date: 2024/1/23 21:26
 * @Version: 1.0
 */
@RestController
@Api(tags = "打卡记录接口")
@RequestMapping("/backstage/clockInRecord")
public class ClockInRecordController {
    @Autowired
    private ClockInRecordService clockInRecordService;
    @Autowired
    private RedisService redisService;
    @PostMapping("/upload")
    @ApiOperation("上传钉钉Excel表")
    public R<String> uploadRecord(@RequestParam("file") MultipartFile file) throws IOException, ParseException {
/*        List<ClockInRecordBo> clockInRecordBoList = ;
        // 将对象数据返回给前端*/
        return R.ok(clockInRecordService.uploadRecord(file));
    }

    @GetMapping("/output")
    @ApiOperation("导出表格")
    public void outPut(HttpServletResponse response) throws IOException {
        String manTimeJson = redisService.getCacheObject(ClockInConstant.MAN_TIME_JSON);
        /*byte[] bytes = manTimeJson.getBytes();
        OutputStream outputStream = new FileOutputStream("output.json");
        outputStream.write(bytes);*/

/*        List<ClockInRecordBo> clockInRecordBoList = ;
//        // 将对象数据返回给前端*/

        ObjectMapper objectMapper = new ObjectMapper();
        List<EmployeeAttendanceBo> employeeList = new ArrayList<>();
        try {
            // 将JSON数组转化为Java对象的列表
             employeeList = Arrays.asList(objectMapper.readValue(manTimeJson, EmployeeAttendanceBo[].class));

            // 打印列表中的每个对象
            for (EmployeeAttendanceBo employee : employeeList) {
                System.out.println(employee);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
        String fileName = URLEncoder.encode("事务分发模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), EmployeeAttendanceBo.class).sheet("模板").doWrite(employeeList);


    }
}
