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


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.annotation.Query.handle.QueryGenerator;
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.vo.Result;
import com.gci.boot.modules.vehicles.entity.TbAnnualInspectionInfo;
import com.gci.boot.modules.vehicles.entity.TbAnnualInspectionRemind;
import com.gci.boot.modules.vehicles.query.AnnualInspectionInfoQuery;
import com.gci.boot.modules.vehicles.query.AnnualInspectionRemindQuery;
import com.gci.boot.modules.vehicles.service.ITbAnnualInspectionInfoService;
import com.gci.boot.modules.vehicles.service.ITbAnnualInspectionRemindService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

/**
 * <p>
 * 年检提醒 前端控制器
 * </p>
 *
 * @author 2464
 * @since 2023-11-16
 */
@RestController
@RequestMapping("/vehicles/annualInspectionRemind")
public class TbAnnualInspectionRemindController {
    @Autowired
    private ITbAnnualInspectionRemindService iTbAnnualInspectionRemindService;
    @Autowired
    private ITbAnnualInspectionInfoService iTbAnnualInspectionInfoService;

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog(value = "年检提醒-分页列表查询")
    @GetMapping(value = "/list")
    @DataPermission(item = "tv.projectId",sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbAnnualInspectionRemindMapper.pageBuild"})
    public Result<?> queryPageList(AnnualInspectionRemindQuery query,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<TbAnnualInspectionRemind> page = new Page<TbAnnualInspectionRemind>(pageNo, pageSize);
        LambdaQueryWrapper<TbAnnualInspectionRemind> lambdaQueryWrapper = QueryGenerator.initQueryWrapper(TbAnnualInspectionRemind.class,query);
        IPage<TbAnnualInspectionRemind> pageList = iTbAnnualInspectionRemindService.pageBuild(page, lambdaQueryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     */
//    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody TbAnnualInspectionRemind tbAnnualInspectionRemind) {
        iTbAnnualInspectionRemindService.save(tbAnnualInspectionRemind);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     */
//    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody TbAnnualInspectionRemind tbAnnualInspectionRemind) {
        iTbAnnualInspectionRemindService.updateById(tbAnnualInspectionRemind);
        return Result.ok("编辑成功！");
    }

    /**
     * 删除
     */
//    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        iTbAnnualInspectionRemindService.removeById(id);
        return Result.ok("删除成功！");
    }

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

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

    /**
     * 导出
     */
    @AddSysLog(value = "年检提醒-导出")
    @GetMapping("/export")
    @DataPermission(item = "g.projectId",sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbAnnualInspectionInfoMapper.remindList"})
    public Result<?> remindListExport(HttpServletResponse response, AnnualInspectionRemindQuery 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<TbAnnualInspectionRemind> page = new Page<TbAnnualInspectionRemind>(1, -1);
            LambdaQueryWrapper<TbAnnualInspectionRemind> lambdaQueryWrapper = QueryGenerator.initQueryWrapper(TbAnnualInspectionRemind.class, query);
            IPage<TbAnnualInspectionRemind> pageList = iTbAnnualInspectionRemindService.pageBuild(page, lambdaQueryWrapper);
            ExportParams exportParams = new ExportParams();
            exportParams.setDictHandler(new MyExcelDictHandleImpl());
            Workbook sheets = ExcelExportUtil.exportExcel(exportParams, TbAnnualInspectionRemind.class, pageList.getRecords());
            sheets.write(output);
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }

    /**
     * 根据infoId获取年检信息
     */
    @GetMapping("/getByInfoId")
    public Result<?> getByInfoId (@RequestParam(name = "infoId")String infoId) {
        TbAnnualInspectionInfo info = iTbAnnualInspectionInfoService.getById(infoId);
        if(Objects.nonNull(info) && Objects.nonNull(info.getValidityPeriod())){
            info.setValidityPeriod(DateUtil.offset(info.getValidityPeriod(), DateField.YEAR,1));
        }
        return Result.ok(info);
    }

}
