package cn.cecep.talroad.controller.analysis;

import cn.cecep.talroad.common.core.domain.R;
import cn.cecep.talroad.common.core.exception.CommonException;
import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.controller.BasesController;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.log.annotation.Log;
import cn.cecep.talroad.common.log.enums.BusinessType;
import cn.cecep.talroad.common.security.annotation.RequiresPermissions;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.analysis.SRaAbNalysisLowCar;
import cn.cecep.talroad.feign.BaseRegionService;
import cn.cecep.talroad.service.analysis.ISRaAbNalysisLowCarService;
import cn.cecep.talroad.vo.EChartsVO;
import cn.cecep.talroad.vo.analysis.SRaAbNalysisLowCarVo;
import cn.cecep.talroad.vo.query.analysis.SRaAbNalysisLowCarQuery;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;


/**
 * * 开发公司：中节能天融科技有限公司
 * 管控期车辆异常分析Controller 控制层
 *
 * @author szhpt
 * @date 2023-03-24
 */
@Api(tags = "企业车辆进出厂异常分析")
@RestController
@RequestMapping("/low/car")
public class SRaAbNalysisLowCarController extends BasesController {
    @Autowired
    private ISRaAbNalysisLowCarService sRaAbNalysisLowCarService;
    @Autowired
    @Qualifier("baseRegionService")
    private BaseRegionService baseRegionService;

    /**
     * 查询管控期车辆异常分析列表
     */
    @ApiOperation(value = "企业车辆进出厂异常分析-list")
    @GetMapping("/list")
    public AjaxResults<IPage<SRaAbNalysisLowCar>> list(SRaAbNalysisLowCarQuery sRaAbNalysisLowCar) {

        try {
            String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if (r.getCode() == 200) {
                sRaAbNalysisLowCar.setRegionCodes(r.getData());
            }
        } catch (Exception e) {
            System.err.println("获取区域列表失败");
        }

        Page<SRaAbNalysisLowCar> page = new Page<>(sRaAbNalysisLowCar.getPageNum(), sRaAbNalysisLowCar.getPageSize());
        IPage<SRaAbNalysisLowCar> list = sRaAbNalysisLowCarService.page(page, SRaAbNalysisLowCarQuery.createLambdaQueryWrapper(sRaAbNalysisLowCar));
        return AjaxResults.success(list);
    }

    /**
     * 查询管控期车辆异常分析列表
     */
    @ApiOperation(value = "查询管控期车辆异常分析-饼图和折线")
    @GetMapping("/chartData")
    public AjaxResults<EChartsVO> chartData(SRaAbNalysisLowCarQuery sRaAbNalysisLowCar) {
        try {
            String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if (r.getCode() == 200) {
                sRaAbNalysisLowCar.setRegionCodes(r.getData());
            }
        } catch (Exception e) {
            System.err.println("获取区域列表失败");
        }
        long l1 = System.currentTimeMillis();
        List<SRaAbNalysisLowCar> list = sRaAbNalysisLowCarService.list(SRaAbNalysisLowCarQuery.createLambdaQueryWrapper(sRaAbNalysisLowCar));
        long l2 = System.currentTimeMillis();
        System.out.println((l2-l1)/1000);
        EChartsVO eChartsVO = sRaAbNalysisLowCarService.chartData(list, sRaAbNalysisLowCar);

        return AjaxResults.success(eChartsVO);
    }

    /**
     * 导出管控期车辆异常分析列表
     */
    @ApiOperation(value = "导出管控期车辆异常分析")
    @Log(title = "企业车辆进出厂异常分析", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestBody SRaAbNalysisLowCarQuery sRaAbNalysisLowCar) {
        try {
            String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if (r.getCode() == 200) {
                sRaAbNalysisLowCar.setRegionCodes(r.getData());
            }
        } catch (Exception e) {
            System.err.println("获取区域列表失败");
        }
        Calendar calendar = new GregorianCalendar();
        if(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getEndAnalyseTime())){
            calendar.setTime(sRaAbNalysisLowCar.getEndAnalyseTime());
            // 把日期往后增加一天,整数  往后推,负数往前移动
            calendar.add(Calendar.DATE, 1);
            sRaAbNalysisLowCar.setEndAnalyseTime(calendar.getTime());
        }
        List<SRaAbNalysisLowCar> list = sRaAbNalysisLowCarService.selectSRaAbNalysisLowCarList(sRaAbNalysisLowCar);
        ExcelUtil<SRaAbNalysisLowCar> util = new ExcelUtil<>(SRaAbNalysisLowCar.class);
        util.exportExcel(response, list, "企业车辆进出厂异常分析");
    }

    /**
     * 导出管控期车辆异常分析报告
     */
    @ApiOperation(value = "导出管控期车辆异常分析报告")
    @Log(title = "导出管控期车辆异常分析报告", businessType = BusinessType.EXPORT)
    @PostMapping("/exportWordReport")
    public void exportWordReport(HttpServletResponse response,@RequestBody SRaAbNalysisLowCarQuery sRaAbNalysisLowCar) throws TemplateException, IOException {
        try {
            String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if (r.getCode() == 200) {
                sRaAbNalysisLowCar.setRegionCodes(r.getData());
            }
        } catch (Exception e) {
            System.err.println("获取区域列表失败");
        }
        this.sRaAbNalysisLowCarService.exportWordReport(response,sRaAbNalysisLowCar);
    }

    /**
     * 获取管控期车辆异常分析详细信息
     */
    @ApiOperation(value = "获取管控期车辆异常分析详细信息")
    @PostMapping(value = "/{dataId}")
    public AjaxResults<SRaAbNalysisLowCar> getInfo(@PathVariable("id") Integer id) {
        return AjaxResults.success(sRaAbNalysisLowCarService.getById(id));
    }

    /**
     * 新增管控期车辆异常分析
     */
    @ApiOperation(value = "新增管控期车辆异常分析")
    @Log(title = "管控期车辆异常分析", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResults<Boolean> add(@RequestBody SRaAbNalysisLowCar sRaAbNalysisLowCar) {
        return toAjax(sRaAbNalysisLowCarService.save(sRaAbNalysisLowCar));
    }

    /**
     * 修改管控期车辆异常分析
     */
    @ApiOperation(value = "修改管控期车辆异常分析")
    @Log(title = "管控期车辆异常分析", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResults<Boolean> edit(@RequestBody SRaAbNalysisLowCarVo sRaAbNalysisLowCarVo) {
        if (ObjectUtil.isEmpty(sRaAbNalysisLowCarVo)) {
            throw new InvalidParameterException("参数为空");
        }
        if (ObjectUtil.isEmpty(sRaAbNalysisLowCarVo.getDataId())) {
            throw new InvalidParameterException("参数id为空");
        }
        SRaAbNalysisLowCar sRaAbNalysisLowCar = sRaAbNalysisLowCarService.getById(sRaAbNalysisLowCarVo.getDataId());
        if (ObjectUtil.isEmpty(sRaAbNalysisLowCar)) {
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", sRaAbNalysisLowCarVo.getDataId()));
        }
        //赋值
        BeanUtil.copyProperties(sRaAbNalysisLowCarVo, sRaAbNalysisLowCar);
        return toAjax(sRaAbNalysisLowCarService.saveOrUpdate(sRaAbNalysisLowCar));
    }

    /**
     * 删除管控期车辆异常分析
     */
    @ApiOperation(value = "删除管控期车辆异常分析")
    @RequiresPermissions("talroad:car:remove")
    @Log(title = "管控期车辆异常分析", businessType = BusinessType.DELETE)
    @PostMapping("/{dataIds}")
    public AjaxResults<Boolean> remove(@PathVariable String[] dataIds) {
        return toAjax(sRaAbNalysisLowCarService.removeByIds(Arrays.asList(dataIds)));
    }


    /**
     * 近一周进出厂车辆趋势   显示 进厂 和出厂
     */
    @ApiOperation(value = "近一周进出厂车辆趋势折线")
    @GetMapping("/parkChartData")
    public AjaxResults<EChartsVO> parkChartData(SRaAbNalysisLowCarQuery sRaAbNalysisLowCar) {
        String regionCode = "";
        try {
            regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if (r.getCode() == 200) {
                sRaAbNalysisLowCar.setRegionCodes(r.getData());
            }
        } catch (Exception e) {
            logger.info("获取区域列表失败");
        }
        LambdaQueryWrapper<SRaAbNalysisLowCar> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotNull(sRaAbNalysisLowCar.getDataId()), SRaAbNalysisLowCar::getDataId, sRaAbNalysisLowCar.getDataId());
        wrapper.eq(ObjectUtil.isNotNull(sRaAbNalysisLowCar.getFactoryId()), SRaAbNalysisLowCar::getFactoryId, sRaAbNalysisLowCar.getFactoryId());
        wrapper.like(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getFactoryName()), SRaAbNalysisLowCar::getFactoryName, sRaAbNalysisLowCar.getFactoryName());
        wrapper.eq(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getIndustryCategoryName()), SRaAbNalysisLowCar::getIndustryCategoryName, sRaAbNalysisLowCar.getIndustryCategoryName());
        wrapper.likeRight(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getIndustryCategoryCode()), SRaAbNalysisLowCar::getIndustryCategoryCode, sRaAbNalysisLowCar.getIndustryCategoryCode());
        wrapper.eq(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getDistrictName()), SRaAbNalysisLowCar::getDistrictName, sRaAbNalysisLowCar.getDistrictName());
        wrapper.likeRight(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getDistrictCode()), SRaAbNalysisLowCar::getDistrictCode, sRaAbNalysisLowCar.getDistrictCode());
        wrapper.eq(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getPerformanceLevel()), SRaAbNalysisLowCar::getPerformanceLevel, sRaAbNalysisLowCar.getPerformanceLevel());
        wrapper.in(ObjectUtil.isNotEmpty(sRaAbNalysisLowCar.getRegionCodes()), SRaAbNalysisLowCar::getDistrictCode, sRaAbNalysisLowCar.getRegionCodes());
        wrapper.between(SRaAbNalysisLowCar::getAnalyseTime, DateUtils.addDateDays(DateUtils.getNowDate(), -6), DateUtils.getNowDate());
        List<SRaAbNalysisLowCar> list = sRaAbNalysisLowCarService.list(wrapper);

            EChartsVO eChartsVO = sRaAbNalysisLowCarService.parkChartData(list);
            return AjaxResults.success(eChartsVO);


    }
}
