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

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
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.permission.DataPermission;
import com.gci.boot.common.dict.excel.MyExcelDictHandleImpl;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.util.DateUtils;
import com.gci.boot.common.vo.Result;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.modules.basedata.entity.TbVehicle;
import com.gci.boot.modules.basedata.service.ITbVehicleService;
import com.gci.boot.modules.driver.entity.TbDriver;
import com.gci.boot.modules.driver.service.ITbDriverService;
import com.gci.boot.modules.statis.service.VehicleStatisService;
import com.gci.boot.modules.statis.vo.DriverAnalysisVO;
import com.gci.boot.modules.statis.vo.StatisParamVO;
import com.gci.boot.modules.statis.vo.VehicleAnalysisVO;
import com.gci.boot.modules.statis.vo.VehicleStatisVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lyz
 * @date 2023/10/24 9:24
 */
@Api(tags="分析统计")
@Slf4j
@RestController
@RequestMapping("/analysis")
public class VehicleAnalysisController {

    @Autowired
    private ITbVehicleService iTbVehicleService;

    @Autowired
    private ITbDriverService iTbDriverService;

    @Autowired
    private VehicleStatisService vehicleStatisService;

    @AddSysLog(value = "车辆评价-分页列表查询")
    @GetMapping(value = "/vehicle/list")
    @DataPermission(item="tb_vehicle.projectId", sqlIds = {"com.gci.boot.modules.basedata.mapper.TbVehicleMapper.selectPage"})
    public Result<?> vehicleList(TbVehicle vehicle,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) throws ParseException {
        Page<TbVehicle> page = new Page<TbVehicle>(pageNo, pageSize);
        LambdaQueryWrapper<TbVehicle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getProjectId()),TbVehicle::getProjectId,vehicle.getProjectId());
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(vehicle.getPlateNumber()),TbVehicle::getPlateNumber, vehicle.getPlateNumber());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getVehicleBrand()),TbVehicle::getVehicleBrand,vehicle.getVehicleBrand());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getDealer()),TbVehicle::getDealer,vehicle.getDealer());
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(vehicle.getVehicleModel()),TbVehicle::getVehicleModel, vehicle.getVehicleModel());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getVehicleType()),TbVehicle::getVehicleType, vehicle.getVehicleType());
        lambdaQueryWrapper.eq(TbVehicle::getCancelFlag, CommonConstant.DEL_FLAG_0);
        lambdaQueryWrapper.between(vehicle.getDeliveryTimeStart()!=null, TbVehicle::getDeliveryTime, vehicle.getDeliveryTimeStart(), vehicle.getDeliveryTimeEnd());
        lambdaQueryWrapper.orderByAsc(TbVehicle::getProjectId);
        lambdaQueryWrapper.orderByDesc(TbVehicle::getPlateNumber);
        IPage<TbVehicle> pageList = iTbVehicleService.page(page, lambdaQueryWrapper);

        List<TbVehicle>  vehicles  =  pageList.getRecords();
        List<VehicleAnalysisVO> vos = vehicleStatisService.analysisVehicleByListAndTime(vehicles, DateUtils.parseDate("1976-01-01","yyyy-MM-dd"),new Date());
        IPage<VehicleAnalysisVO> results = new Page<>(pageNo,pageSize);
        results.setCurrent(pageList.getCurrent());
        results.setTotal(pageList.getTotal());
        results.setRecords(vos);
        return Result.ok(results);
    }

    @AddSysLog(value = "车辆评价-导出")
    @GetMapping(value = "/vehicle/export")
    @DataPermission(item="tb_vehicle.projectId", sqlIds = {"com.gci.boot.modules.basedata.mapper.TbVehicleMapper.selectList"})
    public Result<?> vehicleExport(TbVehicle vehicle,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req,HttpServletResponse response) throws ParseException {
        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);
            LambdaQueryWrapper<TbVehicle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getProjectId()),TbVehicle::getProjectId,vehicle.getProjectId());
            lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(vehicle.getPlateNumber()),TbVehicle::getPlateNumber, vehicle.getPlateNumber());
            lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getVehicleBrand()),TbVehicle::getVehicleBrand,vehicle.getVehicleBrand());
            lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getDealer()),TbVehicle::getDealer,vehicle.getDealer());
            lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(vehicle.getVehicleModel()),TbVehicle::getVehicleModel, vehicle.getVehicleModel());
            lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(vehicle.getVehicleType()),TbVehicle::getVehicleType, vehicle.getVehicleType());
            lambdaQueryWrapper.eq(TbVehicle::getCancelFlag, CommonConstant.DEL_FLAG_0);
            lambdaQueryWrapper.between(vehicle.getDeliveryTimeStart()!=null, TbVehicle::getDeliveryTime, vehicle.getDeliveryTimeStart(), vehicle.getDeliveryTimeEnd());
            lambdaQueryWrapper.orderByAsc(TbVehicle::getProjectId);
            lambdaQueryWrapper.orderByDesc(TbVehicle::getPlateNumber);
            List<TbVehicle> vehicles = iTbVehicleService.list(lambdaQueryWrapper);
            List<VehicleAnalysisVO> vos = vehicleStatisService.analysisVehicleByListAndTime(vehicles, DateUtils.parseDate("1976-01-01","yyyy-MM-dd"),new Date());
            ExportParams exportParams = new ExportParams();
            exportParams.setDictHandler(new MyExcelDictHandleImpl());
            ExcelExportUtil.exportExcel(exportParams,VehicleAnalysisVO.class,vos).write(output);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return Result.error("导出错误！");
        }
        return Result.ok();
    }


    @AddSysLog(value = "司机画像列表-分页列表查询")
    @GetMapping(value = "/driver/list")
    @DataPermission(item="tb_driver.projectId", sqlIds = {"com.gci.boot.modules.driver.mapper.TbDriverMapper.selectPage"})
    public Result<?> driverList( @RequestParam(name = "projectId",required = false) String projectId,
                                 @RequestParam(name = "name",required = false) String name,
                                 @RequestParam(name = "startTime",required = true) String startTime,
                                 @RequestParam(name = "endTime",required = true) String endTime,
                                 @RequestParam(name = "entryStatus",required = false) String entryStatus,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        Page<TbDriver> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<TbDriver> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(projectId),TbDriver::getProjectId,projectId);
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(name),TbDriver::getName, name);
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(entryStatus),TbDriver::getEntryStatus,entryStatus);
        lambdaQueryWrapper.eq(TbDriver::getDelFlag, CommonConstant.DEL_FLAG_0);
        lambdaQueryWrapper.orderByAsc(TbDriver::getProjectId);
        lambdaQueryWrapper.orderByDesc(TbDriver::getName);
        IPage<TbDriver> pageList = iTbDriverService.page(page, lambdaQueryWrapper);
        List<TbDriver>  drivers  =  pageList.getRecords();
        List<DriverAnalysisVO> vos = vehicleStatisService.analysisDriverByListAndTime(drivers, startTime,endTime);
        IPage<DriverAnalysisVO> results = new Page<>(pageNo,pageSize);
        results.setCurrent(pageList.getCurrent());
        results.setTotal(pageList.getTotal());
        results.setRecords(vos);
        return Result.ok(results);
    }


    @AddSysLog(value = "司机画像列表-导出")
    @GetMapping(value = "/driver/export")
    @DataPermission(item="tb_driver.projectId", sqlIds = {"com.gci.boot.modules.driver.mapper.TbDriverMapper.selectList"})
    public Result<?> driverExport(@RequestParam(name = "projectId",required = false) String projectId,
                                  @RequestParam(name = "name",required = false) String name,
                                  @RequestParam(name = "startTime",required = true) String startTime,
                                  @RequestParam(name = "endTime",required = true) String endTime,
                                  @RequestParam(name = "entryStatus",required = false) String entryStatus,
                                  HttpServletRequest req, 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);
            LambdaQueryWrapper<TbDriver> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(projectId),TbDriver::getProjectId,projectId);
            lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(name),TbDriver::getName, name);
            lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(entryStatus),TbDriver::getEntryStatus,entryStatus);
            lambdaQueryWrapper.eq(TbDriver::getDelFlag, CommonConstant.DEL_FLAG_0);
            lambdaQueryWrapper.orderByAsc(TbDriver::getProjectId);
            lambdaQueryWrapper.orderByDesc(TbDriver::getName);
            List<TbDriver>  drivers  =  iTbDriverService.list(lambdaQueryWrapper);
            List<DriverAnalysisVO> vos = vehicleStatisService.analysisDriverByListAndTime(drivers, startTime,endTime);
            ExportParams exportParams = new ExportParams();
            exportParams.setDictHandler(new MyExcelDictHandleImpl());
            Workbook sheets =ExcelExportUtil.exportExcel(exportParams,DriverAnalysisVO.class,vos);
            sheets.write(output);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return Result.error("导出错误！");
        }
        return Result.ok();

    }
}
