package com.sptg.gateway.controller.common;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.gateway.service.CsvService;
import com.sptg.gateway.service.CsvServiceFactory;
import com.sptg.permissions.api.entity.ImportExcelError;
import com.sptg.permissions.api.feigns.ImportExcelErrorFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WFT
 * @date 2020/6/11
 * description:
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/csv")
public class CsvController {

    private final CsvServiceFactory factory;
    private final ImportExcelErrorFeign errorFeign;

    @GetMapping(value = "/import/{flag}")
    public ModelAndView importPage(@PathVariable(value = "flag") String flag){
        ModelAndView modelAndView = new ModelAndView("common/csv-import");
        modelAndView.addObject("flag",flag);
        return modelAndView;
    }

    @PostMapping(value = "/import")
    public ResultBean<?> upload(@RequestParam("file") MultipartFile multipartFile,String flag){
        Assert.hasText(flag,"标识不能为空");
        Assert.notNull(multipartFile,"参数异常");
        this.factory.getService(flag).read(multipartFile,this.errorFeign);
        return ResultBean.ok();
    }

    @GetMapping(value = "/export/error/{flag}")
    public void exportError(@PathVariable(value = "flag") String flag, HttpServletResponse response){
        //  获取异常数据
        List<ImportExcelError> dataList = this.errorFeign.getListByFlag(flag);
        if (null != dataList){
            OutputStream stream = null;
            try {
                stream = response.getOutputStream();
                CsvService service = this.factory.getService(flag);

                String fileName = new String((service.getTemplateName() + "[异常数据]" + ".csv").getBytes(), StandardCharsets.ISO_8859_1);
//                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                //  导出数据
                StringBuffer buffer = new StringBuffer();
                //  设置表头
                List<String> headerList = service.getHeaderList();
                headerList.forEach(header -> buffer.append(header).append(","));
                buffer.append("失败原因");
                //  换行
                buffer.append("\r\n");

                List<Long> idList = new ArrayList<>(dataList.size());
                //  遍历数据
                for (int i = 0; i < dataList.size(); i++){
                    //  每10条记录写出一次
                    if (i % 10 == 0){
                        stream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                        stream.flush();
                        buffer.delete(0,buffer.length());
                    }
                    //  得到异常数据
                    ImportExcelError excelError = dataList.get(i);
                    String[] array = excelError.getData().split(",", -1);
                    for (String data : array){
                        buffer.append(data).append(",");
                    }
                    //  写出异常原因
                    buffer.append(excelError.getError());
                    //  换行
                    buffer.append("\r\n");
                    idList.add(excelError.getId());
                }
                stream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                stream.flush();
                this.errorFeign.delete(idList);
            } catch (IOException e){
                log.error(e.getMessage());
            } finally {
                if (null != stream){
                    try {
                        stream.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @GetMapping(value = "/export/template/{flag}")
    public void exportTemplate(@PathVariable(value = "flag") String flag, HttpServletResponse response){
        CsvService service = this.factory.getService(flag);
        OutputStream stream = null;
        try {
            stream = response.getOutputStream();
            String fileName = new String((service.getTemplateName() + ".csv").getBytes(), StandardCharsets.ISO_8859_1);
//            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            //  设置表头
            StringBuffer buffer = new StringBuffer();
            List<String> headerList = service.getHeaderList();
            headerList.forEach(header -> buffer.append(header).append(","));
            buffer.deleteCharAt(buffer.length() - 1).append("\r\n");
            //  写出数据
            stream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
            stream.flush();
        }catch (IOException e){
            log.error(e.getMessage());
        }finally {
            if (null != stream){
                try {
                    stream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

}
