package org.linlinjava.jz.admin.web;

/**
 * @author fuxubing
 */

import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.jz.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.jz.admin.excel.CustomerExcelModel;
import org.linlinjava.jz.admin.service.AdminUploadService;
import org.linlinjava.jz.admin.util.CustomerExcelListener;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * @author fuxubing
 */
@Api(value = "Admin-Import-Controller", description = "导入")
@RestController
@RequestMapping("/admin/upload")
@Validated
public class AdminUploadController {
    @Resource
    private AdminUploadService adminUploadService;

    @RequiresPermissions("admin:upload:uploadExcel")
    @RequiresPermissionsDesc(menu = {"电访中心", "任务导入"}, button = "导入")
    @PostMapping("/uploadExcel")
    public Object uploadExcel(@RequestParam(value = "file") MultipartFile excelFile, @NotNull @RequestParam Integer channelId, @NotNull @RequestParam Integer campaignId) throws IOException {
        //ExcelListener  上面创建的那个类
        CustomerExcelListener listener = new CustomerExcelListener();
        //ExcelModel 上面创建的实体类
        EasyExcel.read(excelFile.getInputStream(), CustomerExcelModel.class, listener).sheet(0).doReadSync();

        List<CustomerExcelModel> datas = listener.getDatas(); //把拿到的数据处理到集合里去(根据所需自行修改)

        List<CustomerExcelModel> modelList = adminUploadService.save(datas, channelId, campaignId);

        datas.clear();//结束后销毁不用的资源
        //System.out.println(datas); //查看销毁后的结果
        List<CustomerExcelModel> failDatas = listener.getFailDatas();
        failDatas.addAll(modelList);

        return ResponseUtil.ok(failDatas);
    }
}
