package cn.com.tenlion.systembase.controller.api.school;

import cn.com.tenlion.systembase.listener.ImportExcelListener;
import cn.com.tenlion.systembase.pojo.dtos.excel.ImportFailDto;
import cn.com.tenlion.systembase.pojo.dtos.school.SchoolDTO;
import cn.com.tenlion.systembase.pojo.model.school.SchoolModel;
import cn.com.tenlion.systembase.pojo.vos.school.SchoolVO;
import cn.com.tenlion.systembase.service.handleimportexcel.IHandleImportExcelService;
import cn.com.tenlion.systembase.service.school.ISchoolService;
import cn.com.tenlion.systembase.util.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import ink.wgink.annotation.CheckRequestBodyAnnotation;
import ink.wgink.common.base.DefaultBaseController;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.result.ErrorResult;
import ink.wgink.pojo.result.SuccessResult;
import ink.wgink.pojo.result.SuccessResultData;
import ink.wgink.pojo.result.SuccessResultList;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
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.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SchoolController
 * @Description: 学校
 * @Author: CodeFactory
 * @Date: 2021-10-12 17:11:37
 * @Version: 3.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "学校接口")
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/school")
public class SchoolController extends DefaultBaseController {

    @Autowired
    private ISchoolService schoolService;
    @Autowired
    private IHandleImportExcelService handleImportExcelService;
    private List<ImportFailDto> failDtoList;

    @ApiOperation(value = "新增学校", notes = "新增学校接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("save")
    @CheckRequestBodyAnnotation
    public SuccessResult save(@RequestBody SchoolVO schoolVO) {
        schoolService.save(schoolVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "删除学校", notes = "删除学校接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ids", value = "ID列表，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("remove/{ids}")
    public SuccessResult remove(@PathVariable("ids") String ids) {
        schoolService.remove(Arrays.asList(ids.split("\\_")), ids);
        return new SuccessResult();
    }

    @ApiOperation(value = "修改学校", notes = "修改学校接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "schoolId", value = "学校ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("update/{schoolId}")
    @CheckRequestBodyAnnotation
    public SuccessResult update(@PathVariable("schoolId") String schoolId, @RequestBody SchoolVO schoolVO) {
        schoolService.update(schoolId, schoolVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "学校详情", notes = "学校详情接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "schoolId", value = "学校ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("get/{schoolId}")
        public SchoolDTO get(@PathVariable("schoolId") String schoolId) {
        return schoolService.get(schoolId);
    }

    @ApiOperation(value = "学校列表", notes = "学校列表接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("list")
    public List<SchoolDTO> list() {
        Map<String, Object> params = requestParams();
        return schoolService.list(params);
    }

    @ApiOperation(value = "学校分页列表", notes = "学校分页列表接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
        @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
        @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpage")
    public SuccessResultList<List<SchoolDTO>> listPage(ListPage page) {
        Map<String, Object> params = requestParams();
        page.setParams(params);
        return schoolService.listPage(page);
    }

    @ApiOperation(value = "学校统计", notes = "学校统计接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("count")
    SuccessResultData<Integer> count() {
        Map<String, Object> params = requestParams();
        return new SuccessResultData<>(schoolService.count(params));
    }

    @ApiOperation(value = "导入教育局-请求结果数据", notes = "导入教育局-请求结果数据接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("importexcel")
    public SuccessResultData importExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
        ImportExcelListener listener = new ImportExcelListener(handleImportExcelService, SchoolModel.class);
        File newFile = multipartFileToFile(file);
        ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(newFile);
        ExcelReader excelReader = excelReaderBuilder.build();
        List<ReadSheet> sheets = excelReader.excelExecutor().sheetList();
        for (ReadSheet sheet : sheets) {
            // 读取数据
            ExcelUtil.readExcel(file, sheet.getSheetNo(), 1, listener, SchoolModel.class);
        }
        newFile.delete();

        // 错误集
        List<ImportFailDto> importFailDtoList = listener.getImportFailDtoList();
        if(!importFailDtoList.isEmpty()) {
            failDtoList = importFailDtoList;
            return new SuccessResultData(importFailDtoList.size());
        }
        return new SuccessResultData("success");
    }

    /**
     * 导出失败数据
     * @param response
     *
     */
    @ApiOperation(value = "教育局-请求结果数据导入失败数据", notes = "教育局-请求结果数据导入失败数据接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("exportexcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        String excelName = "教育局-请求结果数据导入失败数据";
        String fileName = URLEncoder.encode(excelName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        String [] headers = {"序号", "流水号", "批次号", "入库时间", "MD5校验码", "业务字段MD5", "分片号",
                "记录状态", "处理状态", "学校名称", "学校类型", "建筑面积", "类别", "教职工人数",
                "学校地址", "行政区划编码", "行政区划", "面积", "失败原因"};
        List<List<String>> listHeader = new ArrayList<>();
        for(String item : headers) {
            List<String> title = new ArrayList<>();
            title.add(item);
            listHeader.add(title);
        }

        List<List<Object>> listData = new ArrayList<>();
        int i = 0;
        for (ImportFailDto dto : failDtoList) {
            i++;
            List<Object> data = new ArrayList<>();
            SchoolModel schoolModel = new SchoolModel();
            BeanUtils.copyProperties(dto.getObject(), schoolModel);
            data.add(i);
            data.add(schoolModel.getSerialNumber());
            data.add(schoolModel.getBatchNumber());
            data.add(schoolModel.getInsertTime());
            data.add(schoolModel.getMd5Check());
            data.add(schoolModel.getBusinessMd5());
            data.add(schoolModel.getSliceNumber());
            data.add(schoolModel.getRecordStatus());
            data.add(schoolModel.getHandleStatus());
            data.add(schoolModel.getSchoolName());
            data.add(schoolModel.getRunningType());
            data.add(schoolModel.getBuildArea());
            data.add(schoolModel.getSchoolType());
            data.add(schoolModel.getWorkersCount());
            data.add(schoolModel.getSchoolAddress());
            data.add(schoolModel.getAreaCode());
            data.add(schoolModel.getAreaName());
            data.add(schoolModel.getArea());
            data.add(dto.getErrMsg());
            listData.add(data);
        }
        EasyExcel.write(response.getOutputStream()).sheet("教育局-请求结果数据导入失败数据").head(listHeader).doWrite(listData);
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}