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


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

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

import com.gci.boot.annotation.permission.DataPermission;

import org.apache.commons.collections.CollectionUtils;
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.util.BeanUtilsCopy;
import com.gci.boot.common.util.MinioUtils;
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.projects.entity.TbVehicleCheck;
import com.gci.boot.modules.projects.service.IProjectsService;
import com.gci.boot.modules.projects.service.ITbVehicleCheckDetailService;
import com.gci.boot.modules.projects.service.ITbVehicleCheckProjectService;
import com.gci.boot.modules.projects.service.ITbVehicleCheckService;
import com.gci.boot.modules.projects.vo.TbVehicleCheckVo;

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

/**
 * <p>
 * 车辆验收管理 前端控制器
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-11
 */
@Slf4j
@RestController
@RequestMapping("/projects/vehicleCheck")
public class TbVehicleCheckController {

	@Autowired
	private ITbVehicleCheckService tbVehicleCheckService;
	@Autowired
	private ITbVehicleCheckProjectService tbVehicleCheckProjectService;
	@Autowired
	private ITbVehicleCheckDetailService tbVehicleCheckDetailService;
	@Autowired
    private MinioUtils minioUtils;
	@Autowired
	private IProjectsService projectsService;

	@AddSysLog(value = "车辆验收管理-列表查询")
	@GetMapping("/list")
	//采购交车没有项目id
	//@DataPermission(item="tb_vehicle_check.projectId", sqlIds = {"com.gci.boot.modules.projects.mapper.TbVehicleCheckMapper.selectList"})
	public Result<?> list(TbVehicleCheck item) {
		if(!StringUtils.hasLength(item.getCheckType())) {
			item.setCheckType("1");
		}
		LambdaQueryWrapper<TbVehicleCheck> queryWrapper = QueryGenerator.initQueryWrapper(TbVehicleCheck.class, item);
		if(StringUtils.hasLength(item.getPlateNumber())||StringUtils.hasLength(item.getFrameNumber())) {
			String where = "";
			if(StringUtils.hasLength(item.getPlateNumber())) {
				where += " and cd.plate_number like '%"+item.getPlateNumber()+"%'";
			}
			if(StringUtils.hasLength(item.getFrameNumber())) {
				where += " and cd.frame_number like '%"+item.getFrameNumber()+"%'";
			}
			String sql = "select 1 from tb_vehicle_check_detail cd where tb_vehicle_check.id = cd.check_id "+where;
			queryWrapper.exists(sql);
		}
		if("1".equals(item.getCheckType())) {
			queryWrapper.orderByAsc(TbVehicleCheck::getStatus);
		}else {
			//采购交车没有项目id
			List<String> listProjectIds = projectsService.queryProjectListOfUser();
			queryWrapper.in(CollectionUtils.isNotEmpty(listProjectIds),TbVehicleCheck::getProjectId, listProjectIds);
			queryWrapper.orderByAsc(TbVehicleCheck::getReceiveStatus);
		}
		queryWrapper.orderByDesc(TbVehicleCheck::getCreateTime);
		List<TbVehicleCheck> list = tbVehicleCheckService.list(queryWrapper);
		tbVehicleCheckService.initItem(list);
		for(TbVehicleCheck template:list) {
			tbVehicleCheckDetailService.getVehiclesByCheckId(template);
			tbVehicleCheckProjectService.getProjectsByCheckId(template);
			template.setVehicleCount(template.getVehicleList().size());
		}
		return Result.ok(list);
	}

	@AddSysLog(value = "车辆验收管理-分页查询")
	@GetMapping("/page")
	//采购交车没有项目id
	//@DataPermission(item="tb_vehicle_check.projectId", sqlIds = {"com.gci.boot.modules.projects.mapper.TbVehicleCheckMapper.selectPage"})
	public Result<?> page(TbVehicleCheck item,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
						  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		if(!StringUtils.hasLength(item.getCheckType())) {
			item.setCheckType("1");
		}
		LambdaQueryWrapper<TbVehicleCheck> queryWrapper = QueryGenerator.initQueryWrapper(TbVehicleCheck.class, item);
		if(StringUtils.hasLength(item.getPlateNumber())||StringUtils.hasLength(item.getFrameNumber())) {
			String where = "";
			if(StringUtils.hasLength(item.getPlateNumber())) {
				where += " and cd.plate_number like '%"+item.getPlateNumber()+"%'";
			}
			if(StringUtils.hasLength(item.getFrameNumber())) {
				where += " and cd.frame_number like '%"+item.getFrameNumber()+"%'";
			}
			String sql = "select 1 from tb_vehicle_check_detail cd where tb_vehicle_check.id = cd.check_id "+where;
			queryWrapper.exists(sql);
		}
		if("1".equals(item.getCheckType())) {
			queryWrapper.orderByAsc(TbVehicleCheck::getStatus);
		}else {
			//采购交车没有项目id
			List<String> listProjectIds = projectsService.queryProjectListOfUser();
			queryWrapper.in(CollectionUtils.isNotEmpty(listProjectIds),TbVehicleCheck::getProjectId, listProjectIds);
			queryWrapper.orderByAsc(TbVehicleCheck::getReceiveStatus);
		}
		queryWrapper.orderByDesc(TbVehicleCheck::getCreateTime);
		Page<TbVehicleCheck> page = new Page<TbVehicleCheck>(pageNo, pageSize);
		IPage<TbVehicleCheck> pageList = tbVehicleCheckService.page(page,queryWrapper);
		tbVehicleCheckService.initItem(pageList.getRecords());
		for(TbVehicleCheck template:pageList.getRecords()) {
			//获取租赁收车
			tbVehicleCheckService.getChildren(template);
			tbVehicleCheckDetailService.getVehiclesByCheckId(template);
			tbVehicleCheckProjectService.getProjectsByCheckId(template);
			template.setVehicleCount(template.getVehicleList().size());
		}
		return Result.ok(pageList);
	}

	@AddSysLog(value = "车辆验收管理-新增")
	@PostMapping("/add")
	public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbVehicleCheck item){
		if(!StringUtils.hasLength(item.getCheckType())) {
			return Result.error("验收类型不能为空");
		}
		String error = tbVehicleCheckService.saveItem(item);
		return Result.ok("操作成功。"+error);
	}

	@AddSysLog(value = "车辆验收管理-编辑")
	@PutMapping("/edit")
	public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbVehicleCheck item){
		String error = tbVehicleCheckService.saveItem(item);
		return Result.ok("操作成功。"+error);
	}

	@AddSysLog(value = "车辆验收管理-删除")
	@DeleteMapping("/delete")
	public Result<?> delete(TbVehicleCheck item){
		tbVehicleCheckService.removeById(item.getId());
		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.getCommonFileTypes()));
    }

	/**
	 *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
	 * @param response
	 */
    @AddSysLog(value = "车辆验收管理-导出")
	@GetMapping("/simple/export")
	@DataPermission(item="tb_vehicle_check.projectId", sqlIds = {"com.gci.boot.modules.projects.mapper.TbVehicleCheckMapper.selectList"})
	public Result<?> export(TbVehicleCheck 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<TbVehicleCheck> list = (List<TbVehicleCheck>)result.getResult();
			if("2".equals(item.getCheckType())) {
				List<TbVehicleCheckVo> list2 = new ArrayList<>();
				for(TbVehicleCheck src:list) {
					TbVehicleCheckVo vo = new TbVehicleCheckVo();
					BeanUtilsCopy.copyBeanProp(vo, src);
					list2.add(vo);
				}
				EasyExcel.write(output, TbVehicleCheckVo.class).sheet("sheet1").doWrite(list2);
			}else {
				EasyExcel.write(output, TbVehicleCheck.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_vehicle_check.projectId", sqlIds = {"com.gci.boot.modules.projects.mapper.TbVehicleCheckMapper.selectPage"})
	public Result<?> multiExport(TbVehicleCheck 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, TbVehicleCheck.class).build()) {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
				for (int i = 0; i < pages; i++) {
					Result<?> result = page(item,i+1, 10);
					IPage<TbVehicleCheck> page = (IPage<TbVehicleCheck>)result.getResult();
					List<TbVehicleCheck> 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();
	}

}
