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


import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
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.log.annotation.AddSysLog;
import com.gci.boot.common.util.ValidatorUtil;
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.modules.driver.vo.DriverImportVO;
import com.gci.boot.modules.vehicles.entity.TbRefuelChargeRecord;
import com.gci.boot.modules.vehicles.service.ITbRefuelChargeRecordService;
import com.gci.boot.modules.vehicles.vo.AttachmentDetailVO;
import com.gci.boot.modules.vehicles.vo.TbRefuelChargeRecordImportVo;
import com.gci.boot.modules.vehicles.vo. TbRefuelChargeRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 加油充电登记 前端控制器
 * </p>
 *
 * @author admin
 * @since 2023-11-30
 */
@Slf4j
@RestController
@RequestMapping("/gis/refuelChargeRecord")
public class TbRefuelChargeRecordController {

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

	@AddSysLog(value = "加油充电登记-列表查询")
	@GetMapping("/list")
	@DataPermission(item="tb_refuel_charge_record.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbRefuelChargeRecordMapper.selectList"},stringIn = true)
	public Result<?> list(TbRefuelChargeRecord item) {
		LambdaQueryWrapper<TbRefuelChargeRecord> queryWrapper = QueryGenerator.initQueryWrapper(TbRefuelChargeRecord.class, item);
		queryWrapper.ge(item.getDateStart()!=null,TbRefuelChargeRecord::getRecordDate, item.getDateStart());
		queryWrapper.le(item.getDateEnd()!=null,TbRefuelChargeRecord::getRecordDate, item.getDateEnd());
		queryWrapper.orderByDesc(TbRefuelChargeRecord::getCreateTime);
		List<TbRefuelChargeRecord> list = refuelChargeRecordService.list(queryWrapper);
		return Result.ok(list);
	}

	@AddSysLog(value = "加油充电登记-分页列表查询")
	@GetMapping("/page")
	@DataPermission(item="tb_refuel_charge_record.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbRefuelChargeRecordMapper.selectPage"})
    public Result<?> page(TbRefuelChargeRecord item,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
						  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

		LambdaQueryWrapper<TbRefuelChargeRecord> queryWrapper = QueryGenerator.initQueryWrapper(TbRefuelChargeRecord.class, item);
		queryWrapper.ge(item.getDateStart()!=null,TbRefuelChargeRecord::getRecordDate, item.getDateStart());
		queryWrapper.le(item.getDateEnd()!=null,TbRefuelChargeRecord::getRecordDate, item.getDateEnd());
		queryWrapper.orderByDesc(TbRefuelChargeRecord::getCreateTime);
		Page<TbRefuelChargeRecord> page = new Page<TbRefuelChargeRecord>(pageNo, pageSize);
		IPage<TbRefuelChargeRecord> pageList = refuelChargeRecordService.page(page,queryWrapper);
		return Result.ok(pageList);
	}

	@AddSysLog(value = "加油充电登记-添加")
	@PostMapping("/add")
	public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbRefuelChargeRecord item){
		refuelChargeRecordService.saveItem(item);
		return Result.ok();
	}

	@AddSysLog(value = "加油充电登记-编辑")
	@PutMapping("/edit")
	public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbRefuelChargeRecord item){
		refuelChargeRecordService.saveItem(item);
		return Result.ok();
	}
	
	@AddSysLog(value = "加油充电登记-删除")
	@DeleteMapping("/delete")
	public Result<?> delete(TbRefuelChargeRecord item){
		refuelChargeRecordService.removeById(item.getId());
		return Result.ok();
	}

	/**
	 *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
	 * @param response
	 */
    @AddSysLog(value = "加油充电登记-导出")
	@GetMapping("/simple/export")
    @DataPermission(item="tb_refuel_charge_record.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbRefuelChargeRecordMapper.selectList"},stringIn = true)
	public Result<?> export(TbRefuelChargeRecord item,HttpServletResponse response){
		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);

			Result<?> result = list(item);
			List<TbRefuelChargeRecord> list = (List<TbRefuelChargeRecord>)result.getResult();

			EasyExcel.write(output, TbRefuelChargeRecord.class).sheet("sheet1").doWrite(list);

		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return Result.error("导出错误！");
		}
		return Result.ok();
	}

    @AddSysLog(value = "加油充电登记-分页导出")
	@GetMapping("/multi/export")
	@DataPermission(item="tb_refuel_charge_record.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbRefuelChargeRecordMapper.selectPage"})
	public Result<?> multiExport(TbRefuelChargeRecord item,HttpServletResponse response){
		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);

			int pages = 1;
			try (ExcelWriter excelWriter = EasyExcel.write(output, TbRefuelChargeRecord.class).build()) {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
				for (int i = 0; i < pages; i++) {
					Result<?> result = page(item,i+1, 10);
					IPage<TbRefuelChargeRecord> page = (IPage<TbRefuelChargeRecord>)result.getResult();
					List<TbRefuelChargeRecord> data = page.getRecords();
					int temp = (int)page.getPages();
					if(pages<temp) {
						pages = temp;
					}
					excelWriter.write(data, writeSheet);
				}
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return Result.error("导出错误！");
		}
		return Result.ok();
	}

	/**
	 * 多次读入
	 * @param request
	 * @return
	 */
	@AddSysLog(value = "加油充电登记-导入")
	@PostMapping("/simple/import")
	public Result<?> simpleImport(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		MultipartFile file = multipartRequest.getFile("file");
		if(!ValidatorUtil.isExcelFile(file)){
			return Result.error("导入文件必须为excel!");
		}
		try(InputStream input = file.getInputStream()) {
			List<TbRefuelChargeRecordImportVo> list = EasyExcel.read(input).head(TbRefuelChargeRecordImportVo.class).sheet().doReadSync();
			if(CollectionUtils.isEmpty(list) || ValidatorUtil.allFieldsAreNullInList(list)){
				return Result.error("导入加油充电登记数据不能为空！请检查导入模板!");
			}
			return refuelChargeRecordService.saveItemBatch(list);
		}catch (IOException e){
			log.error(e.getMessage(), e);
			return Result.error("导入错误！");
		}
	}



	/**
	 * 导入错误信息下载
	 */
	@AddSysLog(value = "加油充电登记-导入错误信息下载")
	@GetMapping("/downFail")
	public Result<?> downFail(HttpServletResponse response,String path) throws IOException {
		// 设置输出的格式
		// 循环取出流中的数据
		String fullPath = failExcel + path;
		try (InputStream stream = ResourceUtil.getStream(fullPath)) {
			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);
			}
			// 下载完成后删除文件
			new Thread(() -> {
				try {
					//延迟 3 秒,避免文件被占用
					Thread.sleep(3000);
					ValidatorUtil.deleteFile(fullPath);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}).start();
		}catch (IORuntimeException e){
			e.printStackTrace();
			return Result.error("文件不存在!");
		}catch (Exception e) {
			e.printStackTrace();
			return Result.error("导出异常!");
		}
		return Result.ok();
	}

}
