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


import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.gci.boot.common.util.ValidatorUtil;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.exception.GciBootException;
import com.gci.boot.modules.driver.vo.DriverImportVO;
import com.gci.boot.modules.vehicles.vo.InsuranceImportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
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 org.springframework.web.multipart.MultipartHttpServletRequest;

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.MinioUtils;
import com.gci.boot.common.util.ZipUtil;
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.TbInsurance;
import com.gci.boot.modules.vehicles.service.ITbInsuranceRemindService;
import com.gci.boot.modules.vehicles.service.ITbInsuranceService;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 保险信息 前端控制器
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-21
 */
@Slf4j
@RestController
@RequestMapping("/vehicles/insurance")
public class TbInsuranceController {

	@Autowired
	private ITbInsuranceService tbInsuranceService;
	@Autowired
    private MinioUtils minioUtils;

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

	@Autowired
	private ITbInsuranceRemindService insuranceRemindService;

	@AddSysLog(value = "保险信息-列表查询")
	@GetMapping("/list")
	@DataPermission(item="tb_insurance.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbInsuranceMapper.selectList"})
	public Result<?> list(TbInsurance item) {
		LambdaQueryWrapper<TbInsurance> queryWrapper = QueryGenerator.initQueryWrapper(TbInsurance.class, item);
		queryWrapper.ge(item.getCompulsoryValidTimeStart()!=null,TbInsurance::getCompulsoryValidTime, item.getCompulsoryValidTimeStart());
		queryWrapper.le(item.getCompulsoryValidTimeEnd()!=null,TbInsurance::getCompulsoryValidTime, item.getCompulsoryValidTimeEnd());
		queryWrapper.ge(item.getCommercialValidTimeStart()!=null,TbInsurance::getCommercialValidTime, item.getCommercialValidTimeStart());
		queryWrapper.le(item.getCommercialValidTimeEnd()!=null,TbInsurance::getCommercialValidTime, item.getCommercialValidTimeEnd());
		queryWrapper.orderByDesc(TbInsurance::getCreateTime);
		List<TbInsurance> list = tbInsuranceService.list(queryWrapper);
		for (TbInsurance tbInsurance : list) {
			tbInsurance.init();
		}
		return Result.ok(list);
	}

	@AddSysLog(value = "保险信息-分页查询")
	@GetMapping("/page")
	@DataPermission(item="tb_insurance.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbInsuranceMapper.selectPage"})
	public Result<?> page(TbInsurance item,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
						  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

		LambdaQueryWrapper<TbInsurance> queryWrapper = QueryGenerator.initQueryWrapper(TbInsurance.class, item);
		queryWrapper.ge(item.getCompulsoryValidTimeStart()!=null,TbInsurance::getCompulsoryValidTime, item.getCompulsoryValidTimeStart());
		queryWrapper.le(item.getCompulsoryValidTimeEnd()!=null,TbInsurance::getCompulsoryValidTime, item.getCompulsoryValidTimeEnd());
		queryWrapper.ge(item.getCommercialValidTimeStart()!=null,TbInsurance::getCommercialValidTime, item.getCommercialValidTimeStart());
		queryWrapper.le(item.getCommercialValidTimeEnd()!=null,TbInsurance::getCommercialValidTime, item.getCommercialValidTimeEnd());
		queryWrapper.orderByDesc(TbInsurance::getCreateTime);
		Page<TbInsurance> page = new Page<TbInsurance>(pageNo, pageSize);
		IPage<TbInsurance> pageList = tbInsuranceService.page(page,queryWrapper);
		for (TbInsurance tbInsurance : pageList.getRecords()) {
			tbInsurance.init();
		}
		return Result.ok(pageList);
	}

	@AddSysLog(value = "保险信息-新增")
	@PostMapping("/add")
	public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbInsurance item){
		if(!"1".equals(item.getHasCompulsoryInsurance())&&!"1".equals(item.getHasCommercialInsurance())) {
			return Result.error("交强险和商业保险不能都为空");
		}
		String error = tbInsuranceService.checkItem(item);
		if(StringUtils.hasLength(error)) {
			return Result.error(error);
		}
		if("1".equals(item.getHasCommercialInsurance())) {
			item.setCommercialCompanyId(item.getCompulsoryCompanyId());
			item.setCommercialStartTime(item.getCompulsoryStartTime());
			item.setCommercialValidTime(item.getCompulsoryValidTime());
		}
		tbInsuranceService.save(item);
		insuranceRemindService.updateRemind();
		return Result.ok();
	}

	@AddSysLog(value = "保险信息-编辑")
	@PutMapping("/edit")
	public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbInsurance item){
		if(!"1".equals(item.getHasCompulsoryInsurance())&&!"1".equals(item.getHasCommercialInsurance())) {
			return Result.error("交强险和商业保险不能都为空");
		}
		String error = tbInsuranceService.checkItem(item);
		if(StringUtils.hasLength(error)) {
			return Result.error(error);
		}
		if("1".equals(item.getHasCommercialInsurance())) {
			item.setCommercialCompanyId(item.getCompulsoryCompanyId());
			item.setCommercialStartTime(item.getCompulsoryStartTime());
			item.setCommercialValidTime(item.getCompulsoryValidTime());
		}
		tbInsuranceService.updateById(item);
		insuranceRemindService.updateRemind();
		return Result.ok();
	}

	@AddSysLog(value = "保险信息-删除")
	@DeleteMapping("/delete")
	public Result<?> delete(TbInsurance item){
		tbInsuranceService.removeById(item.getId());
		return Result.ok();
	}



	/**
	 * 导入模板下载
	 */
	@AddSysLog(value = "保险信息-导入模板下载")
	@GetMapping("/V2/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("/V2/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(!ValidatorUtil.isExcelFile(file)){
			return Result.error("导入文件必须为excel!");
		}
		try(InputStream input = file.getInputStream()) {
			List<InsuranceImportVO> list = EasyExcel.read(input).head(InsuranceImportVO.class).sheet().doReadSync();
			return tbInsuranceService.listImport(list);
		}catch (IOException e){
			log.error(e.getMessage(), e);
			return Result.error("导入错误！");
		}
	}

	/**
	 * 导入错误信息下载
	 */
	@AddSysLog(value = "保险信息-导入失败文件下载")
	@GetMapping("/V2/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(CommonConstant.INSURANCE_IMPORT_FAIL_EXCEL_NAME, "utf-8"));
			response.setContentType("application/x-xls;");
			response.setHeader("content-type", "application/octet-stream");
			IoUtil.copy(inputStream, outputStream);
		}catch (IORuntimeException e){
			e.printStackTrace();
			throw new GciBootException("文件不存在!");
		}catch (Exception e) {
			e.printStackTrace();
			throw new GciBootException("下载导入错误下信息失败!");
		} finally {
			FileUtil.del(file);
		}
	}



    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        return Result.ok(minioUtils.uploadFileValid(file, FileExtension.getCommonFileTypes()));
    }

	/**
	 *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
	 * @param response
	 */
    @AddSysLog(value = "保险信息-导出")
	@GetMapping("/simple/export")
	@DataPermission(item="tb_insurance.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbInsuranceMapper.selectList"})
	public Result<?> export(TbInsurance 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<TbInsurance> list = (List<TbInsurance>)result.getResult();
			EasyExcel.write(output, TbInsurance.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_insurance.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbInsuranceMapper.selectPage"})
	public Result<?> multiExport(TbInsurance 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, TbInsurance.class).build()) {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
				for (int i = 0; i < pages; i++) {
					Result<?> result = page(item,i+1, 10);
					IPage<TbInsurance> page = (IPage<TbInsurance>)result.getResult();
					List<TbInsurance> 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;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			try(InputStream input = file.getInputStream()) {
				List<TbInsurance> list = EasyExcel.read(input).head(TbInsurance.class).sheet().doReadSync();
				log.info("数据量：{}",list.size());
				tbInsuranceService.saveBatch(list);
			}catch (IOException e){
				log.error(e.getMessage(), e);
				return Result.error("导入错误！");
			}
		}
		return Result.ok();
	}

    //保险附件批量上传
	@PostMapping("/uploadFiles")
    public Result<?> uploadFiles(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        minioUtils.checkType(file, FileExtension.COM.getNameList());
        int count = 0;
        try {
			InputStream inputStream = file.getInputStream();
			String path = "template/"+System.currentTimeMillis();
			ClassPathResource xlsx = new ClassPathResource(path);
			ZipUtil.unzip(inputStream, xlsx.getPath());
			File folder = new File(xlsx.getPath());
			Map<String,File> fileMap = new HashMap<>();
	        if (folder.isDirectory()) {
	        	readFile(folder,fileMap);
	        }
	        String type = "1";
	        if(file.getOriginalFilename().contains("商业保险")||file.getOriginalFilename().contains("商业险")) {
	        	type = "0";
	        }
	        count = tbInsuranceService.uploadFiles(fileMap, type);
		} catch (IOException e) {
			log.error("保险附件上传失败：", e);
            return Result.error("保险附件上传失败！");
		}

        return Result.ok("成功上传"+count+"个附件");
    }

	private void readFile(File folder,Map<String,File> fileMap) {
		File[] files = folder.listFiles();
        for (File f : files) {
            if (f.isFile()) {
            	fileMap.put(f.getName().toUpperCase(), f);
            }else if (f.isDirectory()) {
            	readFile(f,fileMap);
            }
        }
	}

}
