package com.sptg.gateway.controller.common.excel;

import com.alibaba.excel.metadata.BaseRowModel;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.gateway.service.ExcelService;
import com.sptg.gateway.service.ExcelServiceFactory;
import com.sptg.gateway.util.ExcelUtils;
import com.sptg.permissions.api.entity.ImportExcelError;
import com.sptg.permissions.api.feigns.ImportExcelErrorFeign;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WFT
 * @date 2020/5/29
 * description:表格导出控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/excel/export")
public class ExcelExportController {

    private final ExcelServiceFactory serviceFactory;
    private final ImportExcelErrorFeign excelErrorFeign;

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

    /**
     * 导出表格模板
     * @param flag 标记
     */
    @GetMapping(value = "/template/{flag}")
    public void exportTemplate(@PathVariable(value = "flag")String flag, HttpServletResponse response){
        ExcelService service = this.serviceFactory.getService(flag);
        if (null == service){
            return;
        }
        ExcelUtils.writeExcel(response,new ArrayList<>(0),service);
    }

    /**
     * 导出异常数据
     * @param flag java.lang.String
     * @param response javax.servlet.http.HttpServletResponse
     */
    @GetMapping(value = "/error/data/{flag}")
    public void export(@PathVariable(value = "flag") String flag, HttpServletResponse response){
        Assert.notNull(flag,"flag不能为空");
        //  获取相应Service
        ExcelService service = this.serviceFactory.getService(flag);
        Assert.notNull(service,"参数异常");
        //  获取导入异常的数据
        List<ImportExcelError> excelErrorList = this.excelErrorFeign.getListByFlag(flag);

        List<BaseRowModel> modelList = new ArrayList<>(excelErrorList.size());
        List<Long> idList = new ArrayList<>(excelErrorList.size());
        excelErrorList.forEach(error -> {
            modelList.add(JsonUtils.jsonToPojo(error.getData(), service.getExcelTemplate().getClass()));
            idList.add(error.getId());
        });
        //  导出数据
        ExcelUtils.writeExcel(response,modelList,service);
        //  删除已导出的异常数据
        this.excelErrorFeign.delete(idList);
    }


}
