package org.gyk.modules.lssj.yasuojishuju.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.gyk.modules.lssj.yasuojishuju.entity.CxcSssjYasuoji;
import org.gyk.modules.lssj.yasuojishuju.mapper.YasuojiMapper;
import org.gyk.modules.lssj.yasuojishuju.service.IYasuojiLssjService;
import org.gyk.modules.sssj.controller.GykController;
import org.gyk.modules.sssj.util.sssjTools;
import org.gyk.modules.sz.jldxx.entity.CxcSssjSzJldxx;
import org.gyk.modules.sz.jldxx.mapper.CxcSssjSzJldxxMapper;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description: 报警历史记录
* @Author: jeecg-boot
* @Date:   2021-03-17
* @Version: V1.0
*/
@Api(tags="报警历史记录")
@RestController
@RequestMapping("/Yasuojlssj")
@Slf4j
public class YasuojiLssjController extends GykController{
   @Autowired
   private IYasuojiLssjService yasuojiLssjService;
   @Autowired(required = false)
   private YasuojiMapper yasuojiMapper;
   @Autowired(required = false)
   private CxcSssjSzJldxxMapper cxcSssjSzJldxxMapper;

//   /**
//    *   添加
//    *
//    * @param cxcSssjYasuojiBjls
//    * @return
//    */
//   @AutoLog(value = "报警历史记录-添加")
//   @ApiOperation(value="报警历史记录-添加", notes="报警历史记录-添加")
//   @PostMapping(value = "/add")
//   public Result<?> add(@RequestBody CxcSssjYasuojiBjls cxcSssjYasuojiBjls) {
//       yasuojiBaojLssjService.save(cxcSssjYasuojiBjls);
//       return Result.ok("添加成功！");
//   }
//
//   /**
//    *  编辑
//    *
//    * @param cxcSssjYasuojiBjls
//    * @return
//    */
//   @AutoLog(value = "报警历史记录-编辑")
//   @ApiOperation(value="报警历史记录-编辑", notes="报警历史记录-编辑")
//   @PutMapping(value = "/edit")
//   public Result<?> edit(@RequestBody CxcSssjYasuojiBjls cxcSssjYasuojiBjls) {
//       yasuojiBaojLssjService.updateById(cxcSssjYasuojiBjls);
//       return Result.ok("编辑成功!");
//   }
//
//   /**
//    *   通过id删除
//    *
//    * @param id
//    * @return
//    */
//   @AutoLog(value = "报警历史记录-通过id删除")
//   @ApiOperation(value="报警历史记录-通过id删除", notes="报警历史记录-通过id删除")
//   @DeleteMapping(value = "/delete")
//   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//       yasuojiBaojLssjService.removeById(id);
//       return Result.ok("删除成功!");
//   }
//
//   /**
//    *  批量删除
//    *
//    * @param ids
//    * @return
//    */
//   @AutoLog(value = "报警历史记录-批量删除")
//   @ApiOperation(value="报警历史记录-批量删除", notes="报警历史记录-批量删除")
//   @DeleteMapping(value = "/deleteBatch")
//   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//       this.yasuojiBaojLssjService.removeByIds(Arrays.asList(ids.split(",")));
//       return Result.ok("批量删除成功!");
//   }

//   /**
//    * 通过id查询
//    *
//    * @param id
//    * @return
//    */
//   @AutoLog(value = "报警历史记录-通过id查询")
//   @ApiOperation(value="报警历史记录-通过id查询", notes="报警历史记录-通过id查询")
//   @GetMapping(value = "/queryById")
//   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
//       CxcSssjYasuojiBjls cxcSssjYasuojiBjls = yasuojiBaojLssjService.getById(id);
//       if(cxcSssjYasuojiBjls ==null) {
//           return Result.error("未找到对应数据");
//       }
//       return Result.ok(cxcSssjYasuojiBjls);
//   }

    @RequestMapping("/listByZcAndJzh")
    public IPage<Map<String,String>> listByZcAndJzh(@RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "zhanc") String zhanc, @RequestParam(value = "jzh") String jzh, @RequestParam(name = "startTime", required = false) String startTime,
                                   @RequestParam(name = "endTime", required = false) String endTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        List<Map<String,String>> listsj=new ArrayList<>();

        LambdaQueryWrapper<CxcSssjYasuoji> lmq = Wrappers.lambdaQuery();
        lmq.between(CxcSssjYasuoji::getRq,startTime,endTime);
        lmq.eq(CxcSssjYasuoji::getStationName,zhanc);
        lmq.eq(CxcSssjYasuoji::getJizuHao,jzh);
        lmq.orderByAsc(CxcSssjYasuoji::getRq);

        IPage<CxcSssjYasuoji> iPage = new Page<>(pageNo,pageSize);
        IPage<CxcSssjYasuoji> list = yasuojiMapper.selectPage(iPage,lmq);

        if (list.getRecords().size()>0) {
            list.getRecords().forEach(item->{
                String shuju = item.getShuju();
                Map<String,String> mapshuju = sssjTools.splitStringToMap(shuju);
                mapshuju.put("日期",item.getRq().format(df));

                listsj.add(mapshuju);

            });
        }

        IPage<Map<String,String>> page = new Page<>(pageNo,pageSize);
        page.setRecords(listsj);
        page.setTotal(list.getTotal());

        return page;
    }

    @RequestMapping("/getByZcAndJzh")
    public Map<String,List<String>> getByZcAndJzh( @RequestParam(value = "zhanc") String zhanc, @RequestParam(value = "jzh") String jzh,@RequestParam(value = "csname") String csname) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter df2 = DateTimeFormatter.ofPattern("HH:mm:ss");
        DecimalFormat fnum   =   new   DecimalFormat( "##0.00");
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.plusHours(-8);

        List<String> listrq=new ArrayList<>();
        List<String> listsj=new ArrayList<>();

        LambdaQueryWrapper<CxcSssjSzJldxx> qw =new LambdaQueryWrapper<>();
        qw.eq(CxcSssjSzJldxx::getStationId,zhanc);
        qw.eq(CxcSssjSzJldxx::getJldlx,4);
        List<CxcSssjSzJldxx> cxcSssjSzJldxx = cxcSssjSzJldxxMapper.selectList(qw);
        if (cxcSssjSzJldxx.size()>0 ) {
            String zhancname = cxcSssjSzJldxx.get(0).getStationName();

//        log.info("zhanc:"+cxcSssjSzJldxx.get(0).getStationName()+ " jzh:"+jzh);

            LambdaQueryWrapper<CxcSssjYasuoji> lmq = Wrappers.lambdaQuery();
            lmq.between(CxcSssjYasuoji::getRq,startTime.format(df),endTime.format(df));
            lmq.eq(CxcSssjYasuoji::getStationName,zhancname);
            lmq.eq(CxcSssjYasuoji::getJizuHao,jzh);
            lmq.orderByAsc(CxcSssjYasuoji::getRq);

            List<CxcSssjYasuoji> list = yasuojiMapper.selectList(lmq);

            if (list.size()>0) {
                list.forEach(item->{
                    String shuju = item.getShuju();
                    Map<String,String> mapshuju = sssjTools.splitStringToMap(shuju);
//                mapshuju.put("日期",item.getRq().format(df));

                    listrq.add(item.getRq().format(df2));
                    float ls = Float.parseFloat(mapshuju.get(csname));
//                    String tmp = fnum.format(ls);
//                    log.info("hi:"+tmp);
                    listsj.add(fnum.format(ls));
                });
            }
        }

        Map<String,List<String>> map = new HashMap<>();
        map.put("rq",listrq);
        map.put("shuju",listsj);

        return map;
    }

    /**
     * 导出Excel-动态头写入
     *
     * @param response response
     */
    @GetMapping("/Export")
    public void dynamicHeadExport(HttpServletResponse response,@RequestParam(value = "zhanc") String zhanc, @RequestParam(value = "jzh") String jzh, @RequestParam(name = "startTime", required = false) String startTime,
                                  @RequestParam(name = "endTime", required = false) String endTime) throws IOException {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DecimalFormat fnum   =   new   DecimalFormat( "##0.0000");

//        log.info("hi:"+jzh);

        // 设置动态头
        List<List<String>> headList = new ArrayList<>();
        List<String> head = sssjTools.getYasuojshujuBt(zhanc,jzh).get("title");
        List<String> headbt = new ArrayList<>();
        head.forEach(item->{
            List<String> bt = new ArrayList<>();
            String ls = item.replace("*","");
            bt.add(ls);
            headbt.add(ls);
            headList.add(bt);
        });
            /*         简单的添加标题示例    **********************
            List<String> head0 = new ArrayList<>();
            head0.add("个人信息");
            head0.add("用户名");
            List<String> head1 = new ArrayList<>();
            head1.add("个人信息");
            head1.add("年龄");
            List<String> head2 = new ArrayList<>();
            head2.add("个人信息");
            head2.add("地址");
            headList.add(head0);
            headList.add(head1);
            headList.add(head2);

             */

        LambdaQueryWrapper<CxcSssjYasuoji> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(CxcSssjYasuoji::getRq, startTime,endTime);
        queryWrapper.eq(CxcSssjYasuoji::getStationName,zhanc);
        queryWrapper.eq(CxcSssjYasuoji::getJizuHao,jzh);
        queryWrapper.orderByAsc(CxcSssjYasuoji::getRq);
        List<CxcSssjYasuoji> list = yasuojiLssjService.list(queryWrapper);

//        List<YasuojiJcxx> ysjxx=sssjTools.ysjGykbz;
//        Map<String,String> getidbyname = new HashMap<>();
//        ysjxx.forEach(item->{
//            String[] tmpstr = item.getJldName().split("\\*");
//            if (tmpstr[1].equals("四号机组") && item.getStationName().equals("文二联增压站")) {
//                getidbyname.put(tmpstr[2],item.getGykbz());
//            }
//        });

        // 获取动态数据
        List<List<Object>> dataList = new ArrayList<>();

//        Map<String,String> mapdata = new HashMap<>();
        list.forEach(item->{
            String shuju = item.getShuju();
            Map<String,String> mapshuju = sssjTools.splitStringToMap(shuju);
//            mapshuju.forEach((k,v)->{
//                mapdata.put(k+item.getRq(),v);
//            });
            List<Object> data = new ArrayList<>();
            for(int i=0;i<headbt.size();i++) {
                String tmpstr=headbt.get(i);  //获取的是压缩机参数名
//                String tmpid = getidbyname.get(tmpstr);
                if (tmpstr.equals("日期")) {
                    data.add(item.getRq().format(df));
                } else {
                    String val = mapshuju.get(tmpstr);
                    float floatval = (val==null)? 0.0000f : Float.parseFloat(val);
//                    String lastval =fnum.format(floatval);
                    if (Math.abs(floatval-0.0f)<0.00001f) {
                        data.add("0");
                    } else {
                        data.add(floatval);
                    }
                }
//                log.info("hi:"+data.toString());
            }
            dataList.add(data);
        });

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode(zhanc, "utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xls");

        // 先仅仅写入头，再以不写入头的方式写入数据
        EasyExcel.write(response.getOutputStream()).head(headList).sheet(jzh).doWrite(dataList);
    }

}
