package com.zd.chemical.controller;

import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.zd.chemical.domain.HxpSmartTerminalConfig;
import com.zd.chemical.domain.vo.HxpSmartTerminalByExcel;
import com.zd.chemical.domain.vo.HxpSmartTerminalSearch;
import com.zd.chemical.domain.vo.HxpSmartTerminalVo;
import com.zd.chemical.service.IHxpSmartTerminalConfigService;
import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.redis.service.RedisService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.chemical.domain.HxpSmartTerminal;
import com.zd.chemical.service.IHxpSmartTerminalService;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.zd.common.swagger.config.Knife4jConfiguration;

import com.zd.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 化学品设备管理Controller
 *
 * @author liubo
 * @date 2022-06-16
 */
@RestController
@Api(tags = "【 化学品设备管理】")
@RequestMapping("/hxpSmartTerminal")
public class HxpSmartTerminalController extends BaseController {
    @Autowired
    private IHxpSmartTerminalService hxpSmartTerminalService;
    @Autowired
    private IHxpSmartTerminalConfigService hxpSmartTerminalConfigService;

    @Autowired
    RedisService redisService;

    /**
     * 查询 化学品设备管理列表
     */
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.LIST)
    @GetMapping("/list")
    @ApiOperation(value = "查询 化学品设备管理列表")
    public TableDataInfo<HxpSmartTerminalVo> list(HxpSmartTerminalSearch hxpSmartTerminalSearch) {
        startPage();
        if (StringUtils.isNotNull(hxpSmartTerminalSearch.getTerminalStatus()) && hxpSmartTerminalSearch.getTerminalStatus() == 3) {
            hxpSmartTerminalSearch.setStatus(0);
            hxpSmartTerminalSearch.setTerminalStatus(null);
        }
        List<HxpSmartTerminalVo> list = hxpSmartTerminalService.selectHxpSmartTerminalList(hxpSmartTerminalSearch);
        return getDataTable(list);
    }

    /**
     * 导出 化学品设备管理列表
     */
    @ApiOperation(value = "导出 化学品设备管理列表")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.EXPORT)
    @Log(title = " 化学品设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HxpSmartTerminalSearch hxpSmartTerminalSearch) throws IOException {
        List<HxpSmartTerminalVo> list = hxpSmartTerminalService.selectHxpSmartTerminalList(hxpSmartTerminalSearch);
        ExcelUtil<HxpSmartTerminalVo> util = new ExcelUtil<>(HxpSmartTerminalVo.class);
        util.exportExcel(response, list, " 化学品设备管理数据");
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        String tips = "导入注意事项：（未按如下要求填写，会导致数据不能正常导入）\n" +
                "1、请不要修改此表格的格式，包括插入删除行和列、合并拆分单元格等。请在表格里面逐行录入数据。一次最多导入5000条数据信息。\n" +
                "2、需要填写的单元格字段规则校验，请按照提示输入。\n" +
                "3、请不要随意复制单元格，这样会破坏字段规则校验。\n" +
                "4、带有星号（*）的红色字段为必填项。\n" +
                "5、请注意：设备编号是唯一的，不能重复，不可多条；编号要求最大20个字符，包含大小写字母、数字。\n" +
                "6、请注意：实验室，需填写系统中已录入的对应数据名称，否则无法正常导入。\n";
        ExcelUtil<HxpSmartTerminalByExcel> util = new ExcelUtil<>(HxpSmartTerminalByExcel.class);
        util.exportExcel(response, null, "化学品智能终端", tips, "化学品智能终端-批量导入模板");
    }

    @Log(title = "化学品导入", businessType = BusinessType.IMPORT)
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, HxpSmartTerminalByExcel hxpChemicalByExcel) throws Exception {
        ExcelUtil<HxpSmartTerminalByExcel> util = new ExcelUtil<>(HxpSmartTerminalByExcel.class);
        List<HxpSmartTerminalByExcel> smartTerminalList = util.importExcel(file.getInputStream(), true);
        String operName = SecurityUtils.getUsername();
        List<HxpSmartTerminalByExcel> hxpSmartTerminalByExcels = hxpSmartTerminalService.importSmartTerminal(smartTerminalList, operName, hxpChemicalByExcel);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("totalNum", smartTerminalList.size());
        resultMap.put("successNum", smartTerminalList.size() - hxpSmartTerminalByExcels.size());
        resultMap.put("failureNum", hxpSmartTerminalByExcels.size());
        resultMap.put("downFile", hxpSmartTerminalByExcels.size() > 0);
        if (hxpSmartTerminalByExcels.size() > 0) {
            redisService.setCacheObject("exportBySmartTerminal" + SecurityUtils.getUserId(), hxpSmartTerminalByExcels, 1L, TimeUnit.HOURS);
        }
        return AjaxResult.success(resultMap);
    }

    @Log(title = "化学品导入出错误数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importErrorData")
    public void importErrorData(HttpServletResponse response) throws Exception {
        String tips = "导入注意事项：（未按如下要求填写，会导致数据不能正常导入）\n" +
                "1、请不要修改此表格的格式，包括插入删除行和列、合并拆分单元格等。请在表格里面逐行录入数据。一次最多导入5000条数据信息。\n" +
                "2、需要填写的单元格字段规则校验，请按照提示输入。\n" +
                "3、请不要随意复制单元格，这样会破坏字段规则校验。\n" +
                "4、带有星号（*）的红色字段为必填项。\n" +
                "5、请注意：设备编号是唯一的，不能重复，不可多条；编号要求最大20个字符，包含大小写字母、数字。\n" +
                "6、请注意：实验室，需填写系统中已录入的对应数据名称，否则无法正常导入。\n";
        ExcelUtil<HxpSmartTerminalByExcel> util = new ExcelUtil<>(HxpSmartTerminalByExcel.class);
        List<HxpSmartTerminalByExcel> smartTerminalByExcels = redisService.getCacheObject("exportBySmartTerminal" + SecurityUtils.getUserId());
        if (smartTerminalByExcels.size() > 0) {
            util.exportExcel(response, smartTerminalByExcels, "未导入的智能终端数据数据", tips, "智能终端批量导入模板");
        }
    }


    /**
     * 获取 化学品设备管理详细信息
     */
    @ApiOperation(value = "获取 化学品设备管理详细信息")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public ResultData<HxpSmartTerminal> getInfo(@PathVariable("id") Long id) {
        return ResultData.success(hxpSmartTerminalService.selectHxpSmartTerminalById(id));
    }

    /**
     * 新增 化学品设备管理
     */
    @ApiOperation(value = "新增 化学品设备管理")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.ADD)
    @Log(title = " 化学品设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData<Boolean> add(@RequestBody HxpSmartTerminal hxpSmartTerminal) {
        return ResultData.result(hxpSmartTerminalService.insertHxpSmartTerminal(hxpSmartTerminal));
    }

    /**
     * 修改 化学品设备管理
     */
    @ApiOperation(value = "修改 化学品设备管理")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.EDIT)
    @Log(title = " 化学品设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData<Boolean> edit(@RequestBody HxpSmartTerminal hxpSmartTerminal) {
        return ResultData.result(hxpSmartTerminalService.updateHxpSmartTerminal(hxpSmartTerminal));
    }

    /**
     * 修改 化学品设备管理状态
     */
    @ApiOperation(value = "修改 化学品设备管理状态")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.EDIT)
    @Log(title = " 化学品设备管理", businessType = BusinessType.UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ipAddress", value = "设备IP地址"),
            @ApiImplicitParam(name = "terminalStatus", value = "设备状态")
    })
    @PutMapping("update/status")
    public ResultData<Boolean> updateStatus(@RequestParam("ipAddress") String ipAddress, @RequestParam("terminalStatus") Integer terminalStatus) {
        return ResultData.result(hxpSmartTerminalService.updateStatus(ipAddress, terminalStatus));
    }

    @ApiOperation(value = "化学品设备开启关闭")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.EDIT)
    @Log(title = " 化学品设备开启关闭", businessType = BusinessType.UPDATE)
    @GetMapping("/updateStatus")
    public ResultData<Integer> updateStatus(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        HxpSmartTerminal hxpSmartTerminal = new HxpSmartTerminal();
        hxpSmartTerminal.setId(id);
        hxpSmartTerminal.setStatus(status);
        return ResultData.result(hxpSmartTerminalService.updateHxpSmartTerminal(hxpSmartTerminal));
    }

    @ApiOperation(value = "报警器报警设置")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINALCONFIG + PerFun.EDIT)
    @Log(title = " 化学品设备开启关闭", businessType = BusinessType.UPDATE)
    @PostMapping("/alarmSettings")
    public R<Integer> alarmSettings(@RequestBody HxpSmartTerminalConfig smartTerminalConfig) {
        if (CollectionUtils.isEmpty(smartTerminalConfig.getIds())) {
            return R.fail("修改失败，参数异常！");
        }

        return R.ok(hxpSmartTerminalConfigService.updateHxpSmartTerminalConfig(smartTerminalConfig),"操作成功");
    }

    /**
     * 删除 化学品设备管理
     */
    @ApiOperation(value = "删除 化学品设备管理")
    @PreAuthorize(hasPermi = PerPrefix.HXP_SMARTTERMINAL + PerFun.REMOVE)
    @Log(title = " 化学品设备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData<Boolean> remove(@PathVariable Long[] ids) {
        return ResultData.result(hxpSmartTerminalService.deleteHxpSmartTerminalByIds(ids));
    }
}
