package com.gci.boot.modules.driver.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.io.IORuntimeException;
import cn.hutool.core.io.resource.ResourceUtil;
import com.gci.boot.annotation.permission.DataPermission;
import com.gci.boot.common.util.ValidatorUtil;
import com.gci.boot.modules.driver.vo.DriverImportVO;
import com.gci.boot.modules.vehicles.service.IRepairUpkeepImportService;
import com.gci.boot.modules.vehicles.vo.RepairImportVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.util.MinioUtils;
import com.gci.boot.common.vo.Result;
import com.gci.boot.enums.FileExtension;
import com.gci.boot.modules.basedata.service.ITbCustomerArchivesService;
import com.gci.boot.modules.driver.entity.TbDriver;
import com.gci.boot.modules.driver.service.ITbDriverService;
import com.gci.boot.modules.driver.vo.DriverUserVo;
import com.gci.boot.modules.system.vo.LoginUser;

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

/**
 * <p>
 *  司机档案 前端控制器
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-04
 */
@Slf4j
@RestController
@RequestMapping("/driver/driver")
public class TbDriverController {

	@Autowired
	private ITbDriverService driverService;
	@Autowired
    private MinioUtils minioUtils;
	@Autowired
	private ITbCustomerArchivesService tbCustomerArchivesService;
	@Autowired
	private IRepairUpkeepImportService repairUpkeepImportService;
	@Value("${failExcel}")
	private String failExcel;


	@AddSysLog(value = "司机档案-列表查询")
	@GetMapping("/list")
	@DataPermission(item="tb_driver.projectId", sqlIds = {"com.gci.boot.modules.driver.mapper.TbDriverMapper.selectList"},stringIn = true)
	public Result<?> list(TbDriver item) {
		LambdaQueryWrapper<TbDriver> queryWrapper = QueryGenerator.initQueryWrapper(TbDriver.class, item);
		/*LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser!=null) {
			queryWrapper.likeRight(StringUtils.hasLength(sysUser.getOrgCode()),TbDriver::getSysOrgCode, sysUser.getOrgCode());
		}*/
		queryWrapper.ge(item.getEntryTimeStart()!=null,TbDriver::getEntryTime, item.getEntryTimeStart());
		queryWrapper.le(item.getEntryTimeEnd()!=null,TbDriver::getEntryTime, item.getEntryTimeEnd());
		//queryWrapper.eq(TbDriver::getCancelFlag, CommonConstant.STATUS_1);
		queryWrapper.orderByDesc(TbDriver::getCreateTime);
		List<TbDriver> list = driverService.list(queryWrapper);
		return Result.ok(list);
	}

	@AddSysLog(value = "司机档案-分页查询")
	@GetMapping("/page")
	@DataPermission(item="d.projectId", sqlIds = {"com.gci.boot.modules.driver.mapper.TbDriverMapper.pageWithUserInfo"},stringIn = true)
	public Result<?> page(TbDriver item,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
						  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

		LambdaQueryWrapper<TbDriver> queryWrapper = QueryGenerator.initQueryWrapper(TbDriver.class, item);
		/*LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser!=null) {
			queryWrapper.likeRight(StringUtils.hasLength(sysUser.getOrgCode()),TbDriver::getSysOrgCode, sysUser.getOrgCode());
		}*/
		queryWrapper.ge(item.getEntryTimeStart()!=null,TbDriver::getEntryTime, item.getEntryTimeStart());
		queryWrapper.le(item.getEntryTimeEnd()!=null,TbDriver::getEntryTime, item.getEntryTimeEnd());
		queryWrapper.orderByDesc(TbDriver::getCreateTime);
		Page<TbDriver> page = new Page<TbDriver>(pageNo, pageSize);
		//IPage<TbDriver> pageList = driverService.page(page,queryWrapper);
		queryWrapper.like(item.getProjectId()!=null,TbDriver::getProjectId,item.getProjectId());

		//如果是用户身份：需查询所属客户id
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser==null || StringUtils.isEmpty(sysUser.getId())){
			throw new RuntimeException("用户未登录");
		}
		String customerId = tbCustomerArchivesService.getCustomerByUserId(sysUser.getId());
		if(StringUtils.isNotEmpty(customerId)){
			queryWrapper.eq(TbDriver::getCustomerId,customerId);
		}
		IPage<DriverUserVo> pageList = driverService.pageWithUserInfo(page,queryWrapper);
		return Result.ok(pageList);
	}

	@AddSysLog(value = "司机档案-新增")
	@PostMapping("/add")
	public Result<?> add(@RequestBody DriverUserVo item){
		//driverService.save(item);
		driverService.addDriverWithUser(item);
		return Result.ok();
	}

	@AddSysLog(value = "司机档案-编辑")
	@PutMapping("/edit")
	public Result<?> edit(@RequestBody DriverUserVo item){
		//driverService.updateById(item);
		driverService.editDriverWithUser(item);
		return Result.ok();
	}

	@AddSysLog(value = "司机档案-删除")
	@DeleteMapping("/delete")
	public Result<?> delete(TbDriver item){
		//driverService.removeById(item.getId());
		driverService.delete(item.getId());
		return Result.ok();
	}

	/**
	 *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
	 * @param response
	 */
	@AddSysLog(value = "司机档案-导出")
	@GetMapping("/simple/export")
	@DataPermission(item="tb_driver.projectId", sqlIds = {"com.gci.boot.modules.driver.mapper.TbDriverMapper.selectList"})
	public Result<?> export(TbDriver 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<TbDriver> list = (List<TbDriver>)result.getResult();
			EasyExcel.write(output, TbDriver.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(TbDriver 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, DriverUserVo.class).build()) {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
				for (int i = 0; i < pages; i++) {
					Result<?> result = page(item,i+1, 10);
					IPage<DriverUserVo> page = (IPage<DriverUserVo>)result.getResult();
					List<DriverUserVo> 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")
	@DataPermission(item="d.projectId", sqlIds = {"com.gci.boot.modules.driver.mapper.TbDriverMapper.pageWithUserInfo"})
	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<DriverUserVo> list = EasyExcel.read(input).head(DriverUserVo.class).sheet().doReadSync();
				log.info("数据量：{}",list.size());
				//driverService.saveBatch(list);
				driverService.addDriverWithUserBatch(list);
			}catch (IOException e){
				log.error(e.getMessage(), e);
				return Result.error("导入错误！");
			}
		}
		return Result.ok();
	}

	/**
	 * 启用禁用
	 * @param item
	 * @return
	 */
	@AddSysLog(value = "司机档案-启用禁用")
	@PostMapping("/updateStatus")
	public Result<?> updateStatus(@RequestBody TbDriver item){
		driverService.updateStatus(item);
		return Result.ok();
	}

    /**
     * 文件上传
     */
    @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.PIC.getNameList()));
    }


	/**
	 * 导入
	 */
	@AddSysLog(value = "司机档案-导入")
	@PostMapping("/import")
	public Result<?> driverImport(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<DriverImportVO> list = EasyExcel.read(input).head(DriverImportVO.class).sheet().doReadSync();
			if(CollectionUtils.isEmpty(list) || ValidatorUtil.allFieldsAreNullInList(list)){
				return Result.error("导入司机档案数据不能为空！请检查导入模板!");
			}
			return repairUpkeepImportService.driverImport(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();
	}

	/**
	 * 导入模板下载
	 */
	@AddSysLog(value = "司机档案-导入模板下载")
	@GetMapping("/downTemplate")
	public Result<?> 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 (IORuntimeException e){
			e.printStackTrace();
			return Result.error("文件不存在!");
		}catch (Exception e) {
			e.printStackTrace();
			return Result.error("导出异常!");
		}
		return Result.ok();
	}
}
