package com.nantian.cloud.jly.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jly.entity.ConfigureGauge;
import com.nantian.cloud.jly.service.ConfigureGaugeService;
import com.nantian.cloud.jly.vo.util.FileUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 能源计量器具基本信息
 *
 * @author
 * @date 2018-09-27 15:20:44
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/configureGauge")
@Api(value = "configureGauge", tags = "能源计量器具基本信息")
public class ConfigureGaugeController {
    private final ConfigureGaugeService configureGaugeService;
    private final MinioTemplate minioTemplate;


    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param configureGauge 请假审批单
     * @return
     */
    @SysLog("能源计量器具基本信息-分页查询")
    @GetMapping("/page")
    @ApiOperation(value = "查询能源计量器具基本信息", notes = "条件查询能源计量器具基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ConfigureGauge", value = "能源计量器具基本信息", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R pageCmp(Page page, ConfigureGauge configureGauge) {
        configureGauge.setDelFlag("1"); //查询未删除数据
        //return R.ok(configureGaugeService.page(page, Wrappers.query(configureGauge)));
        //ScUser u = SecurityUtils.getUser();
        //configureGauge.setEnterpriseCode(u.getEnterpriseCode());
        return R.ok(configureGaugeService.pageCmp(page, configureGauge));
    }

    /**
     * 分页查询进出用能单位能源计量器具一览表分表
     *
     * @param page           分页对象
     * @param configureGauge
     * @return
     */
    @SysLog("能源计量器具基本信息-分页查询进出用能单位能源计量器具一览表分表")
    @GetMapping("/page1")
    public R pageCmp1(Page page, ConfigureGauge configureGauge) {
        configureGauge.setDelFlag("1"); //查询未删除数据
        configureGauge.setMeterLevel("1"); //查询一级计量器具
        return R.ok(configureGaugeService.pageCmp(page, configureGauge));
    }

    /**
     * 分页查询进出主要次级用能单位能源计量器具一览表分表
     *
     * @param page           分页对象
     * @param configureGauge
     * @return
     */
    @SysLog("能源计量器具基本信息-分页查询进出主要次级用能单位能源计量器具一览表分表")
    @GetMapping("/page2")
    public R pageCmp2(Page page, ConfigureGauge configureGauge) {
        configureGauge.setDelFlag("1"); //查询未删除数据
        configureGauge.setMeterLevel("2"); //查询未删除数据
        return R.ok(configureGaugeService.pageCmp(page, configureGauge));
    }

    /**
     * 分页查询主要用能设备能源计量器具一览表分表
     *
     * @param page           分页对象
     * @param configureGauge
     * @return
     */
    @SysLog("能源计量器具基本信息-分页查询主要用能设备能源计量器具一览表分表")
    @GetMapping("/page3")
    public R pageCmp3(Page page, ConfigureGauge configureGauge) {
        configureGauge.setDelFlag("1"); //查询未删除数据
        configureGauge.setMeterLevel("3"); //查询未删除数据
        return R.ok(configureGaugeService.pageCmp(page, configureGauge));
    }

    /**
     * 分页查询其他能源计量器具一览表分表
     *
     * @param page           分页对象
     * @param configureGauge
     * @return
     */
    @SysLog("能源计量器具基本信息-分页查询其他能源计量器具一览表分表")
    @GetMapping("/page4")
    public R pageCmp4(Page page, ConfigureGauge configureGauge) {
        configureGauge.setDelFlag("1"); //查询未删除数据
        configureGauge.setMeterLevel("4"); //查询未删除数据
        return R.ok(configureGaugeService.pageCmp(page, configureGauge));
    }


    /**
     * 信息
     *
     * @param configureGaugeId
     * @return R
     */
    @SysLog("能源计量器具基本信息-根据id查询能源计量器具基本信息")
    @GetMapping("/{configureGaugeId}")
    @ApiOperation(value = "根据id查询能源计量器具基本信息", notes = "根据id查询能源计量器具基本信息")
    @ApiImplicitParam(name = "configureGaugeId", value = "能源计量器具基本信息id", required = false, dataType = "int", paramType = "path")
    public R getById(@PathVariable("configureGaugeId") Integer configureGaugeId) {
        return R.ok(configureGaugeService.getById(configureGaugeId));
    }

    /**
     * 保存
     *
     * @param configureGauge
     * @return R
     */
    @SysLog("能源计量器具基本信息-保存")
    @PostMapping("/save")
    @ApiOperation(value = "保存/修改能源计量器具基本信息", notes = "保存/修改能源计量器具基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ConfigureGauge", value = "能源计量器具基本信息", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "barCodeFile", value = "文件流（计量器具二维码）", required = false, dataType = "File", paramType = "path"),
            @ApiImplicitParam(name = "nextAlignDateStr", value = "下次一次检定校准时间字符串", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "installTimeStr", value = "安装时间字符串", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "stateChangeTimeStr", value = "状态发生时间字符串", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "lastAlignDateStr", value = "最近一次检定校准时间字符串", required = false, dataType = "string", paramType = "path"),
    })
    public R save(ConfigureGauge configureGauge, MultipartFile barCodeFile, String nextAlignDateStr, String installTimeStr,
                  String stateChangeTimeStr, String lastAlignDateStr) throws Exception {
        log.error("保存/修改能源计量器具基本信息：{}，##文件：{}", configureGauge, barCodeFile);

        ScUser u = SecurityUtils.getUser();
        configureGauge.setUserid(u.getId());
        configureGauge.setDeptId(u.getDeptId());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (nextAlignDateStr != null && !"".equals(nextAlignDateStr) && nextAlignDateStr != "Invalid Date") {
            configureGauge.setNextAlignDate(nextAlignDateStr); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
//            configureGauge.setNextAlignDate(df.parse(nextAlignDateStr)); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
//            configureGauge.setNextAlignDate(new Date(nextAlignDateStr)); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        if (installTimeStr != null && !"".equals(installTimeStr) && installTimeStr != "Invalid Date") {
            configureGauge.setInstallTime(installTimeStr); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        if (stateChangeTimeStr != null && !"".equals(stateChangeTimeStr) && stateChangeTimeStr != "Invalid Date") {
            configureGauge.setStateChangeTime(stateChangeTimeStr); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        if (lastAlignDateStr != null && !"".equals(lastAlignDateStr) && lastAlignDateStr != "Invalid Date") {
            configureGauge.setLastAlignDate(lastAlignDateStr); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        configureGauge.setEnterpriseCode(configureGauge.getEnterpriseCode());
//        configureGauge.setEnterpriseCode(u.getEnterpriseCode());
        configureGauge.setDelFlag("1");
        configureGauge.setUpdateTime(new Date());

        if (barCodeFile != null) {
            if (barCodeFile.getSize() > 0) {
                //被替换计量器二位码
                configureGauge.setBarCode(getFileUrl(barCodeFile));
            }
        }
        return R.ok(configureGaugeService.saveOrUpdate(configureGauge));
    }

    @SysLog("能源计量器具基本信息-上传文件")
    public String getFileUrl(MultipartFile file) throws Exception {
        String uuid = UUID.randomUUID().toString();
        InputStream inputStream = file.getInputStream(); //得到文件流
        String fileName = file.getOriginalFilename();    //文件名（含后缀）
        //minioTemplate.putObject("jly", uuid, inputStream);
        minioTemplate.putObject("jly", uuid, inputStream, inputStream.available(), "application/octet-stream");
        return fileName + "<" + uuid;
    }


    /**
     * 批量新增
     */
    @SysLog("能源计量器具基本信息-批量新增")
    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量新增能源计量器具基本信息", notes = "批量新增能源计量器具基本信息")
    @ApiImplicitParam(name = "ConfigureGauge", value = "能源计量器具基本信息集合", required = false, dataType = "json", paramType = "path")
    public R saveBatch(@RequestBody List<ConfigureGauge> configureGaugeList) {
        List<ConfigureGauge> newList = new ArrayList<>();
        ScUser u = SecurityUtils.getUser();
        for (ConfigureGauge configureGauge : configureGaugeList) {
            if (u.getId() != null) {
                configureGauge.setUserid(u.getId());
            }
            configureGauge.setDelFlag("1");
            configureGauge.setUpdateTime(new Date());
            newList.add(configureGauge);
        }
        return R.ok(configureGaugeService.saveOrUpdateBatch(newList));
    }

    /**
     * 修改
     *
     * @param configureGauge
     * @return R
     */
    @SysLog("能源计量器具基本信息-修改")
    @PutMapping
    @ApiOperation(value = "修改能源计量器具基本信息", notes = "修改能源计量器具基本信息")
    @ApiImplicitParam(name = "ConfigureGauge", value = "能源计量器具基本信息", required = false, dataType = "json", paramType = "path")
    public R updateById(@RequestBody ConfigureGauge configureGauge) {
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            configureGauge.setUserid(u.getId());
        }
        configureGauge.setUpdateTime(new Date());
        return R.ok(configureGaugeService.updateById(configureGauge));
    }

    /**
     * 批量修改企业计量器具名称
     *
     * @return R
     */
    @SysLog("能源计量器具基本信息-批量修改企业计量器具名称")
    @RequestMapping("/updateName")
    @ApiOperation(value = "批量修改企业计量器具名称", notes = "批量修改企业计量器具名称")
    @ApiImplicitParam(name = "ConfigureGauge", value = "能源计量器具基本信息", required = false, dataType = "json", paramType = "path")
    public R updateName(String epc) {
        List<ConfigureGauge> list1 = configureGaugeService.getList(epc);
        list1.forEach(r->{
            r.setMeterName(r.getType()+ '(' + r.getMeterName() + ')');
        });
        return R.ok(configureGaugeService.updateBatchById(list1));
    }

    /**
     * 删除
     *
     * @param configureGaugeId
     * @return R
     */
    @SysLog("能源计量器具基本信息-删除")
    @DeleteMapping("/{configureGaugeId}")
    @ApiOperation(value = "根据id删除能源计量器具基本信息", notes = "根据id删除能源计量器具基本信息")
    @ApiImplicitParam(name = "configureGaugeId", value = "能源计量器具基本信息id", required = false, dataType = "int", paramType = "path")
    public R removeById(@PathVariable("configureGaugeId") Long configureGaugeId) {
        ConfigureGauge configureGauge = configureGaugeService.getById(configureGaugeId);
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            configureGauge.setUserid(u.getId());
        }
        configureGauge.setDelFlag("4");
        configureGauge.setUpdateTime(new Date());
        return R.ok(configureGaugeService.updateById(configureGauge));
    }

    /**
     * 查询各地区各等级计量器具统计数据
     *
     * @return R
     */
    @SysLog("能源计量器具基本信息-查询各地区各等级计量器具统计数据")
    @GetMapping("/getGaugesStatistics")
    public R getGaugesStatistics() {
        return R.ok(configureGaugeService.getGaugesStatistics());
    }

    /**
     * 分页查询计量器具数据
     *
     * @return R
     */
    @SysLog("能源计量器具基本信息-分页查询计量器具数据")
    @ApiOperation(value = "分页查询计量器具数据", notes = "分页查询计量器具数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "areaCodes", value = "地区编码", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "industryCode", value = "行业编码", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "cmpName", value = "企业名称", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "cmp", value = "企业编码", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "meterLevel", value = "计量器具等级", required = false, dataType = "string", paramType = "path")
    })
    @GetMapping("/getPageData")
    public R getPageData(Page page, String areaCodes, String industryCode, String cmpName, String meterLevel, String cmp, String location,String type) {
        return R.ok(configureGaugeService.getPageData(page, areaCodes, industryCode, cmpName, meterLevel, cmp, location,type));
    }


    @ApiOperation(value = "下载模板", notes = "下载模板")
    @SysLog("下载计量器具模板")
    @RequestMapping(value = {"/template"}, produces = {"application/json;charset=UTF-8"})
    public void template(HttpServletRequest request, HttpServletResponse response) {
        try {
            InputStream is = null;
            String name = null;
            is = minioTemplate.getObject("jly", "能源计量器具一览表模板文件.xlsx");
            name = "能源计量器具一览表模板文件.xlsx";
            XSSFWorkbook xSSFWorkbook = new XSSFWorkbook(is);
            OutputStream output = response.getOutputStream(); // 读取的文件路径
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("charset=GBK");
            xSSFWorkbook.write(output);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载模板文件
     */
    @SysLog("能源计量器具基本信息-下载模板文件")
    @GetMapping(value = "/download")
    @ApiOperation(value = "下载模板文件", notes = "下载模板文件")
    public R download(HttpServletRequest request, HttpServletResponse response) {
        try {
            //URL url = getClass().getClassLoader().getResource("mouldFile/RecordPersonManagerMouldFile.xls");
            URL url = new ClassPathResource("mouldFile/RecordGaugeManagerMouldFile.xls").getURL();
            log.info("获取文件url:" + url);
            // 通过url获取File的绝对路径
            File f = new File(url.getFile());
            if (!f.exists()) {
                return R.failed("路径有误，文件不存在！");
            }
            log.info("获取文件的绝对路径:" + f + "，文件长度：" + f.length());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;charset=utf-8");
            response.setHeader("Content-disposition", URLEncoder.encode(f.getName(), "UTF-8"));
            //mime类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(f.getName(), "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            //从内存中写出来
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(FileUtil.file2byte(f));
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok("下载模板文件成功");
    }

    /**
     * 导入excel
     */
    @SysLog("能源计量器具基本信息-导入excel")
    @PostMapping("excelImport")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
    public R excelImport(@RequestParam MultipartFile file, String epc, String meterLevel) throws FileFormatException {
        return configureGaugeService.excelImport(file, epc, meterLevel);
    }

    /**
     * 查询企业计量器具未检定数量
     *
     * @param
     * @return R
     */
    @SysLog("能源计量器具基本信息-查询企业计量器具未检定数量")
    @GetMapping("/getNotCertified")
    @ApiOperation(value = "查询企业计量器具未检定数量", notes = "查询企业计量器具未检定数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseCode", value = "信用代码", required = true, dataType = "string", paramType = "path"),
    })
    public R getNotCertified( String enterpriseCode) {
        return R.ok(configureGaugeService.getNotCertified(enterpriseCode),"查询成功");
    }
}
