package com.gci.boot.modules.vehicles.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.gci.boot.common.util.ValidatorUtil;
import com.gci.boot.exception.GciBootException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.annotation.permission.DataPermission;
import com.gci.boot.common.dict.excel.MyExcelDictHandleImpl;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.util.MinioUtils;
import com.gci.boot.common.validated.SaveValidated;
import com.gci.boot.common.validated.UpdateValidated;
import com.gci.boot.common.vo.Result;
import com.gci.boot.enums.FileExtension;
import com.gci.boot.modules.vehicles.entity.TbAnnualInspectionInfo;
import com.gci.boot.modules.vehicles.query.AnnualInspectionInfoQuery;
import com.gci.boot.modules.vehicles.service.ITbAnnualInspectionInfoService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;

/**
 * <p>
 * 年检信息表 前端控制器
 * </p>
 *
 * @author 2464
 * @since 2023-09-20
 */
@RestController
@RequestMapping("/vehicles/annualInspectionInfo")
public class TbAnnualInspectionInfoController {
    @Autowired
    private ITbAnnualInspectionInfoService iTbAnnualInspectionInfoService;
    @Autowired
    private MinioUtils minioUtils;

    @Value("${failExcel}")
    private String failExcel;

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog(value = "年检信息-分页列表查询")
    @GetMapping(value = "/list")
    @DataPermission(item = "tv.projectId",
        sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbAnnualInspectionInfoMapper.pageBuild"})
    public Result<?> queryPageList(AnnualInspectionInfoQuery query,
        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Page<TbAnnualInspectionInfo> page = new Page<TbAnnualInspectionInfo>(pageNo, pageSize);
        IPage<TbAnnualInspectionInfo> pageList = iTbAnnualInspectionInfoService.pageBuild(page, query);
        return Result.ok(pageList);
    }

    @AddSysLog(value = "年检信息-待办")
    @GetMapping(value = "/remindList")
    @DataPermission(item = "g.projectId",
        sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbAnnualInspectionInfoMapper.remindList"})
    public Result<?> remindList(AnnualInspectionInfoQuery query,
        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Page<TbAnnualInspectionInfo> page = new Page<TbAnnualInspectionInfo>(pageNo, pageSize);
        IPage<TbAnnualInspectionInfo> pageList = iTbAnnualInspectionInfoService.remindList(page, query);
        return Result.ok(pageList);
    }

    /**
     * 添加
     */
    @AddSysLog(value = "年检信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbAnnualInspectionInfo tbAnnualInspectionInfo) {
        if (!tbAnnualInspectionInfo.getMiscellaneousFee().add(tbAnnualInspectionInfo.getServiceFee())
            .add(tbAnnualInspectionInfo.getTestingFee()).equals(tbAnnualInspectionInfo.getTotalFee())) {
            return Result.error("费用合计错误！");
        }
        iTbAnnualInspectionInfoService.saveItem(tbAnnualInspectionInfo);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     */
    @AddSysLog(value = "年检信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?>
        edit(@RequestBody @Validated(UpdateValidated.class) TbAnnualInspectionInfo tbAnnualInspectionInfo) {
        if (!tbAnnualInspectionInfo.getMiscellaneousFee().add(tbAnnualInspectionInfo.getServiceFee())
            .add(tbAnnualInspectionInfo.getTestingFee()).equals(tbAnnualInspectionInfo.getTotalFee())) {
            return Result.error("费用合计错误！");
        }
        iTbAnnualInspectionInfoService.updateItem(tbAnnualInspectionInfo);
        return Result.ok("编辑成功！");
    }

    /**
     * 删除
     */
    @AddSysLog(value = "年检信息-删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        iTbAnnualInspectionInfoService.removeItem(id);
        return Result.ok("删除成功！");
    }

    /**
     * 批量删除
     */
    @AddSysLog(value = "年检信息-批量删除")
    // @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        iTbAnnualInspectionInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 获取上一年数据
     */
    @GetMapping("/getLastYear")
    public Result<?> getLastYear(@RequestParam(name = "plateNumber") String plateNumber) {
        TbAnnualInspectionInfo lastYear = iTbAnnualInspectionInfoService.getLastYear(plateNumber);
        return Result.ok(lastYear);
    }

    /**
     * 文件上传
     */
    @AddSysLog(value = "年检信息-文件上传")
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        ArrayList<String> strings = ListUtil.toList(FileExtension.EXE.getNameList());
        strings.addAll(FileExtension.OTH.getNameList());
        return Result.ok(minioUtils.uploadFileValidNotIn(file, strings));
    }

    /**
     * 导出
     */
    @AddSysLog(value = "年检信息-导出")
    @GetMapping("/list/export")
    @DataPermission(item = "tv.projectId",
        sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbAnnualInspectionInfoMapper.pageBuild"})
    public Result<?> listExport(HttpServletResponse response, AnnualInspectionInfoQuery query) {
        try (OutputStream output = response.getOutputStream()) {
            String fileName = "车辆年检.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition",
                "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
            Page<TbAnnualInspectionInfo> page = new Page<TbAnnualInspectionInfo>(1, -1);
            IPage<TbAnnualInspectionInfo> pageList = iTbAnnualInspectionInfoService.pageBuild(page, query);
            ExportParams exportParams = new ExportParams();
            exportParams.setDictHandler(new MyExcelDictHandleImpl());
            ArrayList<String> strings = new ArrayList<>();
            strings.add("逾期类型");
            strings.add("将要逾期天数");
            strings.add("逾期天数");
            strings.add("所属项目");
            strings.add("错误信息");
            exportParams.setExclusions(strings.toArray(new String[0]));
            Workbook sheets =
                ExcelExportUtil.exportExcel(exportParams, TbAnnualInspectionInfo.class, pageList.getRecords());
            sheets.write(output);
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }

    /**
     * 导入模板下载
     */
    @AddSysLog(value = "年检信息-导入模板下载")
    @GetMapping("/list/downImport")
    public void downImport(HttpServletResponse response) throws IOException {
        // 设置输出的格式
        // 循环取出流中的数据
        try (InputStream stream = ResourceUtil.getStream("excelTemplate/年检导入模板.xlsx")) {
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("年检导入模板", "utf-8"));
            response.setContentType("application/x-xls;");
            response.setHeader("content-type", "application/octet-stream");
            byte[] b = new byte[1024 * 10];
            int len;
            while ((len = stream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入
     */
//    @AddSysLog(value = "年检信息-导入")
    @PostMapping("/list/import")
    @DataPermission(item = "A.projectId",
        sqlIds = {"com.gci.boot.modules.projects.mapper.ProjectsMapper.getAllProjects"})
    public Result<?> listImport(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        if(!ValidatorUtil.isExcelFile(file)){
            return Result.error("导入文件必须为excel!");
        }

        return iTbAnnualInspectionInfoService.listImport(file);
    }

    /**
     * 导入错误信息下载
     */
    @AddSysLog(value = "年检信息-导入错误信息下载")
    @GetMapping("/list/downFail")
    public void downFail(HttpServletResponse response,@RequestParam("path")String path) {
        // 设置输出的格式
        File file = FileUtil.file(failExcel + path);
        if (file == null) {
            throw new GciBootException("文件名称错误");
        }
        try (BufferedInputStream inputStream = FileUtil.getInputStream(file); ServletOutputStream outputStream = response.getOutputStream()) {
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("车辆年检导出错误", "utf-8"));
            response.setContentType("application/x-xls;");
            response.setHeader("content-type", "application/octet-stream");
            IoUtil.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new GciBootException("下载导入错误下信息失败!");
        } finally {
            FileUtil.del(file);
        }
    }

    /**
     * 导出
     */
    @AddSysLog(value = "年检信息-导出")
    @GetMapping("/remindList/export")
    @DataPermission(item = "g.projectId",
        sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbAnnualInspectionInfoMapper.remindList"})
    public Result<?> remindListExport(HttpServletResponse response, AnnualInspectionInfoQuery query) {
        try (OutputStream output = response.getOutputStream()) {
            String fileName = "车辆提醒.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition",
                "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
            Page<TbAnnualInspectionInfo> page = new Page<TbAnnualInspectionInfo>(1, -1);
            IPage<TbAnnualInspectionInfo> pageList = iTbAnnualInspectionInfoService.remindList(page, query);
            ExportParams exportParams = new ExportParams();
            exportParams.setDictHandler(new MyExcelDictHandleImpl());
            ArrayList<String> strings = new ArrayList<>();
            strings.add("处理人");
            strings.add("办理日期");
            strings.add("年审地点");
            strings.add("备注");
            strings.add("检测费");
            strings.add("手续费");
            strings.add("杂费");
            strings.add("费用合计");
            strings.add("所属项目");
            strings.add("错误信息");
            exportParams.setExclusions(strings.toArray(new String[strings.size()]));
            exportParams.setAutoSize(true);
            Workbook sheets =
                ExcelExportUtil.exportExcel(exportParams, TbAnnualInspectionInfo.class, pageList.getRecords());
            sheets.write(output);
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }

    @GetMapping(value = "init")
    public Result<?> init() {
        iTbAnnualInspectionInfoService.init();
        return Result.ok();
    }
}
