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


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

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

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.common.log.annotation.AddSysLog;
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.constant.CommonConstant;
import com.gci.boot.modules.basedata.entity.TbVehicleCheckTemplate;
import com.gci.boot.modules.basedata.service.ITbVehicleCheckTemplateProjectService;
import com.gci.boot.modules.basedata.service.ITbVehicleCheckTemplateService;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 车辆验收模板 前端控制器
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-07
 */
@Slf4j
@RestController
@RequestMapping("/basedata/vehicleCheckTemplate")
public class TbVehicleCheckTemplateController {

	@Autowired
	private ITbVehicleCheckTemplateService tbVehicleCheckTemplateService;
	@Autowired
	private ITbVehicleCheckTemplateProjectService tbVehicleCheckTemplateProjectService;


	@AddSysLog(value = "车辆验收模板-列表查询")
	@GetMapping("/list")
	public Result<?> list(TbVehicleCheckTemplate item) {
		LambdaQueryWrapper<TbVehicleCheckTemplate> queryWrapper = QueryGenerator.initQueryWrapper(TbVehicleCheckTemplate.class, item);
		//通过类型区分不同模板
		//queryWrapper.eq(TbVehicleCheckTemplate::getCheckType, item.getCheckType());
		queryWrapper.eq(TbVehicleCheckTemplate::getDelFlag, CommonConstant.DEL_FLAG_0);
		queryWrapper.orderByDesc(TbVehicleCheckTemplate::getCreateTime);
		List<TbVehicleCheckTemplate> list = tbVehicleCheckTemplateService.list(queryWrapper);
		for(TbVehicleCheckTemplate template:list) {
			tbVehicleCheckTemplateProjectService.getProjectsByTemplateId(template);
		}
		return Result.ok(list);
	}

	@AddSysLog(value = "车辆验收模板-分页查询")
	@GetMapping("/page")
	public Result<?> page(TbVehicleCheckTemplate item,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
						  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		LambdaQueryWrapper<TbVehicleCheckTemplate> queryWrapper = QueryGenerator.initQueryWrapper(TbVehicleCheckTemplate.class, item);
		//通过类型区分不同模板
		//queryWrapper.eq(ObjectUtil.isNotEmpty(item.getCheckType()),TbVehicleCheckTemplate::getCheckType, item.getCheckType());
		queryWrapper.eq(TbVehicleCheckTemplate::getDelFlag, CommonConstant.DEL_FLAG_0);
		queryWrapper.orderByDesc(TbVehicleCheckTemplate::getCreateTime);
		Page<TbVehicleCheckTemplate> page = new Page<TbVehicleCheckTemplate>(pageNo, pageSize);
		IPage<TbVehicleCheckTemplate> pageList = tbVehicleCheckTemplateService.page(page,queryWrapper);
		for(TbVehicleCheckTemplate template:pageList.getRecords()) {
			tbVehicleCheckTemplateProjectService.getProjectsByTemplateId(template);
		}
		return Result.ok(pageList);
	}

	@AddSysLog(value = "车辆验收模板-新增")
	@PostMapping("/add")
	public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbVehicleCheckTemplate item){
		if(!StringUtils.hasLength(item.getCheckType())) {
			return Result.error("模板类型不能为空");
		}
		tbVehicleCheckTemplateService.saveItem(item);
		return Result.ok();
	}

	@AddSysLog(value = "车辆验收模板-编辑")
	@PutMapping("/edit")
	public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbVehicleCheckTemplate item){
		tbVehicleCheckTemplateService.saveItem(item);
		return Result.ok();
	}

	@AddSysLog(value = "车辆验收模板-删除")
	@DeleteMapping("/delete")
	public Result<?> delete(TbVehicleCheckTemplate item){

		/*LambdaQueryWrapper<TbVehicleCheckTemplate> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TbVehicleCheckTemplate::getId, item.getId());
		TbVehicleCheckTemplate template = new TbVehicleCheckTemplate();
		template.setDelFlag(CommonConstant.DEL_FLAG_1);
		tbVehicleCheckTemplateService.update(template, queryWrapper);*/

		tbVehicleCheckTemplateService.removeById(item.getId());
		return Result.ok();
	}

	/**
	 *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
	 * @param response
	 */
	@AddSysLog(value = "车辆验收模板-导出")
	@GetMapping("/simple/export")
	public Result<?> export(TbVehicleCheckTemplate 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<TbVehicleCheckTemplate> list = (List<TbVehicleCheckTemplate>)result.getResult();
			EasyExcel.write(output, TbVehicleCheckTemplate.class).sheet("sheet1").doWrite(list);

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

	@AddSysLog(value = "车辆验收模板-分页导出")
	@GetMapping("/multi/export")
	public Result<?> multiExport(TbVehicleCheckTemplate 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, TbVehicleCheckTemplate.class).build()) {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
				for (int i = 0; i < pages; i++) {
					Result<?> result = page(item,i+1, 10);
					IPage<TbVehicleCheckTemplate> page = (IPage<TbVehicleCheckTemplate>)result.getResult();
					List<TbVehicleCheckTemplate> 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<TbVehicleCheckTemplate> list = EasyExcel.read(input).head(TbVehicleCheckTemplate.class).sheet().doReadSync();
				log.info("数据量：{}",list.size());
				tbVehicleCheckTemplateService.saveBatch(list);
			}catch (IOException e){
				log.error(e.getMessage(), e);
				return Result.error("导入错误！");
			}
		}
		return Result.ok();
	}

}
