package com.cpp.web.controller.configManager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpp.common.core.domain.R;
import com.cpp.web.domain.station.ElectricField;
import com.cpp.web.domain.station.InverterInfo;
import com.cpp.web.service.station.ElectricFieldService;
import com.cpp.web.service.station.InverterInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


/**
 * idp_inverter_info
 *
 * @author whc
 * @date 2022-03-18 15:49:11
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/inverterinfo")
@Api(value = "inverterinfo", tags = "idp_inverter_info管理")
public class InverterInfoController {
    @Autowired
    InverterInfoService inverterInfoService;
    @Autowired
    ElectricFieldService electricFieldService;

    /**
     * 分页查询
     *
     * @param page         分页对象
     * @param inverterInfo idp_inverter_info
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getInverterInfoPage(Page page, InverterInfo inverterInfo) {
        return R.ok(inverterInfoService.page(page, Wrappers.query(inverterInfo)));
    }

    /**
     * 根据场站编号分页查询
     *
     * @param currentPage
     * @param pageSize
     * @param stationCode
     * @return
     */
    @ApiOperation(value = "根据场站编号分页查询", notes = "分页查询")
    @GetMapping("/getByStationCode")
    public R getByStationCode(Long currentPage,Long pageSize,String stationCode) {
        Page page = new Page(currentPage, pageSize);
        page.setMaxLimit((long) -1);
        return R.ok(inverterInfoService.page(page, inverterInfoService.getByStationCode(stationCode)));
    }

    /**
     * 通过id查询idp_inverter_info
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") String id) {
        return R.ok(inverterInfoService.getById(id));
    }

    /**
     * 新增idp_inverter_info
     *
     * @param inverterInfo idp_inverter_info
     * @return R
     */
    @ApiOperation(value = "新增idp_inverter_info", notes = "新增idp_inverter_info")
    @PostMapping("/save")
    public R save(@RequestBody InverterInfo inverterInfo) {
        return R.ok(inverterInfoService.save(inverterInfo));
    }

    /**
     * 修改idp_inverter_info
     *
     * @param inverterInfo idp_inverter_info
     * @return R
     */
    @ApiOperation(value = "修改idp_inverter_info", notes = "修改idp_inverter_info")
    @PostMapping("/updateById")
    public R updateById(@RequestBody InverterInfo inverterInfo) {
        return R.ok(inverterInfoService.updateById(inverterInfo));
    }

    /**
     * 通过id删除idp_inverter_info
     *
     * @param inverterInfo
     * @return R
     */
    @ApiOperation(value = "通过id删除idp_inverter_info", notes = "通过id删除idp_inverter_info")
    @PostMapping("/remove")
    public R remove(@RequestBody InverterInfo inverterInfo) {
        return R.ok(inverterInfoService.removeById(inverterInfo.getId()));
    }

    /**
     * 根据场站编号查询 返回map格式
     *
     * @param stationCode
     * @return
     */
    @ApiOperation(value = "根据场站编号查询", notes = "分页查询")
    @PostMapping("/findByStationCode")
    public R findByStationCode(String stationCode) {
        List<InverterInfo> inverterInfoList = inverterInfoService.findByStationCode(stationCode);
        List<Map<String, Object>> list = new ArrayList<>();
        for (InverterInfo e : inverterInfoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("label", e.getName());
            map.put("value", e.getId());
            list.add(map);
        }
        return R.ok(list);
    }

    @GetMapping("/all")
    public R findAll() {
        List<InverterInfo> inverterInfoList = inverterInfoService.list();
        List<Map<String, String>> list = new ArrayList<>();
        for (InverterInfo e : inverterInfoList) {
            Map<String, String> map = new HashMap<>();
            map.put("label", e.getName());
            map.put("value", e.getId()+"");
            list.add(map);
        }
        return R.ok(list);
    }

    @GetMapping(value = {"/exportTemplateEvent" })
    public R exportTemplateEvent(HttpServletResponse response) {
        try {
            ExcelWriter writer = ExcelUtil.getWriter(true);
            writer.renameSheet(0, "逆变器信息");
            List<String> headFieldName = Arrays.asList("场站编号","设备名称","制造商","型号","是否样板(1=>是,0=>否)");
            List<List<String>> rowHeather = CollUtil.newArrayList();
            rowHeather.add(headFieldName);
            writer.write(rowHeather, true);
            String fileName = "逆变器信息"+ ".xlsx";
            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out = null;
            out = response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok();
    }

    /**
     * 上传升级文件
     */
    @PostMapping(value = "/uploadNbqTemplate")
    public R uploadNbqTemplate(@RequestParam(value="file") MultipartFile file){
        try (InputStream inputStream = file.getInputStream();) {
            ExcelReader excelReader = ExcelUtil.getReader(inputStream, 0);
            List<Map<String, Object>> readAll = excelReader.readAll();
            if (readAll.size() > 0) {
                List<List<Object>> newList = new ArrayList<>();
                for (Map<String, Object> row : readAll) {
                    Iterator<Map.Entry<String, Object>> rowMap = row.entrySet().iterator();
                    List<Object> tempList = new ArrayList<>();
                    while (rowMap.hasNext()) {
                        Map.Entry<String, Object> entry = rowMap.next();
                        if (entry.getValue() == null) {
                            tempList.add("");
                        } else {
                            tempList.add(entry.getValue());
                        }
                    }
                    newList.add(tempList);
                }
                List<ElectricField> electricFieldList = electricFieldService.list();
                List<InverterInfo> inverterInfoList = new ArrayList<>();
                for (int i = 0; i < newList.size(); i++) {
                    List<Object> objects = newList.get(i);
                    InverterInfo inverterInfo = new InverterInfo();
                    // 验证模板内容
                    if (StrUtil.isBlankIfStr(objects.get(0))) {
                        return R.fail("第" + (i + 1) + "行，场站编号不能为空！");
                    } else {
                        // 判断库中是否存在该编号
                        List<ElectricField> collect = electricFieldList.stream().filter(t -> t.getStationCode().equals(objects.get(0).toString().trim())).collect(Collectors.toList());
                        if (collect.isEmpty()) {
                            return R.fail("第" + (i + 1) + "行，场站编号不存在！");
                        } else {
                            inverterInfo.setStationCode(objects.get(0).toString().trim());
                        }
                    }

                    if (StrUtil.isBlankIfStr(objects.get(1))) {
                        return R.fail("第" + (i + 1) + "行，设备名称不能为空！");
                    } else {
                        inverterInfo.setName(objects.get(1).toString().trim());
                    }
                    if (StrUtil.isBlankIfStr(objects.get(2))) {
                        return R.fail("第" + (i + 1) + "行，制造商不能为空！");
                    } else {
                        inverterInfo.setManufacturer(objects.get(2).toString().trim());
                    }

                    if (StrUtil.isBlankIfStr(objects.get(3))) {
                        return R.fail("第" + (i + 1) + "行，型号不能为空！");
                    } else {
                        inverterInfo.setModelNumber(objects.get(3).toString().trim());
                    }

                    if (StrUtil.isBlankIfStr(objects.get(4))) {
                        return R.fail("第" + (i + 1) + "行，是否样板不能为空！");
                    } else {
                        if (NumberUtil.isNumber(objects.get(4).toString().trim())) {
                            inverterInfo.setSample(objects.get(4).toString().trim());
                        } else {
                            return R.fail("第" + (i + 1) + "行，是否样板不是数值！");
                        }
                    }
                    inverterInfoList.add(inverterInfo);
                }
                inverterInfoService.saveBatch(inverterInfoList);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            log.error("导入风机信息文件失败",e);
            return R.fail("导入逆变器信息文件失败");
        }
        return R.ok();
    }
}
