package cn.cecep.talroad.controller.analysis;

import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
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.domain.PcIndustry;
import cn.cecep.talroad.domain.analysis.BasDeviceParamAnalyse;
import cn.cecep.talroad.service.IPcIndustryService;
import cn.cecep.talroad.service.analysis.BasDeviceParamAnalyseService;
import cn.cecep.talroad.vo.query.analysis.BasDeviceParamAnalyseQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.lang.Collections;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author lixianghou
 */
@Api(tags = "参数管理--分析设置")
@RestController("basDeviceParamAnalyseNewController")
@RequestMapping("/deviceParamAnalyseAnalysis")
public class BasDeviceParamAnalyseController {

    @Autowired
    @Qualifier("basDeviceParamAnalyseNewService")
    private BasDeviceParamAnalyseService service;
    @Autowired
    private IPcIndustryService industryService;

    @ApiOperation(value = "查询分析设置列表")
    @GetMapping("/list")
    public AjaxResults<IPage<BasDeviceParamAnalyse>> list(BasDeviceParamAnalyseQuery query){
        Page<BasDeviceParamAnalyse> page = new Page<>(query.getPageNum(), query.getPageSize());
        IPage<BasDeviceParamAnalyse> list = service.page(page, BasDeviceParamAnalyseQuery.createLambdaQueryWrapper(query)
                        .last(" ORDER BY update_time DESC nulls last,id")
                /*.orderByDesc(BasDeviceParamAnalyse.COL_UPDATE_TIME).orderByDesc(BasDeviceParamAnalyse.COL_ID)*/);
//        List<IPcIndustryService> listIndustry = service.selectIndustry();
        List<PcIndustry> industries = industryService.list();
        Map<String, String> collect = industries.stream().collect(Collectors.toMap(PcIndustry::getIndusCode, PcIndustry::getIndusName));
        list.getRecords().forEach(item -> {
            item.setIndustryName(collect.get(item.getIndustry()));
        });
        return AjaxResults.success(list);
    }

    @ApiOperation(value = "导出分析设置")
    @Log(title = "导出分析设置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody BasDeviceParamAnalyseQuery query) {
        query.setPageSize(Integer.MAX_VALUE);
        List<BasDeviceParamAnalyse> list = service.list(BasDeviceParamAnalyseQuery.createLambdaQueryWrapper(query)
                .last(" ORDER BY update_time DESC nulls last,id"));
        List<PcIndustry> industries = industryService.list();
        Map<String, String> collect = industries.stream().collect(Collectors.toMap(PcIndustry::getIndusCode, PcIndustry::getIndusName));
        list.forEach(item -> {
            item.setDataType(item.getDataType().trim());
            item.setIndustryName(collect.get(item.getIndustry()));
        });
        ExcelUtil<BasDeviceParamAnalyse> util = new ExcelUtil<>(BasDeviceParamAnalyse.class);
        util.hideColumnNative(0);
        util.exportExcel(response, list, "分析设置列表");
    }
    @ApiOperation(value = "修改分析设置")
    @Log(title = "修改分析设置", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public void update(@RequestBody BasDeviceParamAnalyse bean) {
        bean.setUpdateTime(new Date());
         service.updateById(bean);
    }
    @ApiOperation(value = "导入")
    @PostMapping("/import")
    @Log(title = "导入---批量修改分析设置", businessType = BusinessType.IMPORT)
    public AjaxResults<Boolean> importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BasDeviceParamAnalyse> util = new ExcelUtil<>(BasDeviceParamAnalyse.class);
        List<BasDeviceParamAnalyse> voList = util.importExcel(file.getInputStream());
        List<BasDeviceParamAnalyse> datas = voList.stream().filter(v -> v.getId()!=null)
                .filter(v-> !StringUtils.isAllBlank(v.getDeviceParamUnit(),v.getContourEw(),
                        v.getDataLogicFluctuateEw(),v.getDataLogicDeficiencyEw(),v.getDataLogicAbnormalEw())).collect(Collectors.toList());
        if(Collections.isEmpty(datas)){
            return AjaxResults.success(true);
        }
        int quantityPerTime=2500;
        int limit=(datas.size()+quantityPerTime-1)/quantityPerTime;
        //分组
        List<List<BasDeviceParamAnalyse>> dataList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a ->
                datas.stream().skip(a * quantityPerTime).limit(quantityPerTime).parallel().collect(Collectors.toList())).collect(Collectors.toList());
        //每组 quantityPerTime 条批次
        for (List<BasDeviceParamAnalyse> d : dataList) {
            d.forEach(v->{
                v.setUpdateTime(new Date());
            });
            service.updateBatchSelective(d);
        }
        return AjaxResults.success(true);
    }
}
