package com.zd.chemical.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.ListUtil;
import com.zd.chemical.domain.vo.*;
import com.zd.chemical.service.IHxpChemicalJoinCabinetService;
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.exception.ServiceException;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.redis.service.RedisService;
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.HxpChemical;
import com.zd.chemical.service.IHxpChemicalService;
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("/hxpChemical")
public class HxpChemicalController extends BaseController {
    @Autowired
    private IHxpChemicalService hxpChemicalService;

    @Autowired
    RedisService redisService;

    @Autowired
    private IHxpChemicalJoinCabinetService hxpChemicalJoinCabinetService;

    /**
     * 查询化学品信息列表
     */
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+ PerFun.LIST)
    @GetMapping("/list")
    @ApiOperation(value = "查询化学品信息列表")
    public TableDataInfo<HxpChemicalVo> list(HxpChemicalSearch hxpChemicalSearch) {
        startPage();
        List<HxpChemicalVo> list = hxpChemicalService.selectHxpChemicalList(hxpChemicalSearch);
        return getDataTable(list);
    }

    @GetMapping("/queryByUser")
    @ApiOperation(value = "查询化学品信息列表")
    public TableDataInfo<HxpChemicalVo> queryByUser(HxpChemicalSearch hxpChemicalSearch) {
        startPage();
        List<HxpChemicalVo> list = hxpChemicalService.selectHxpChemicalList(hxpChemicalSearch);
        return getDataTable(list);
    }

    /**
     * 导出化学品信息列表
     */
    @ApiOperation(value = "导出化学品信息列表")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.EXPORT)
    @Log(title = "化学品信息", businessType = BusinessType.EXPORT)
    @PostMapping({"/export","/export/{ids}"})
    public void export(HttpServletResponse response, HxpChemicalSearch hxpChemicalSearch,@PathVariable(value = "ids",required = false) Long... ids) throws IOException {
        if(ids!=null&&ids.length>0)
        {
            hxpChemicalSearch = new HxpChemicalSearch();
            hxpChemicalSearch.setIds(Arrays.asList(ids));
        }
        List<HxpChemicalVo> list = hxpChemicalService.selectHxpChemicalList(hxpChemicalSearch);
        ExcelUtil<HxpChemicalVo> util = new ExcelUtil<HxpChemicalVo>(HxpChemicalVo.class);
        //本地日期,不包括时分秒
        LocalDate nowDate = LocalDate.now();
        util.exportExcel(response, list, "化学品信息", null, "化学品信息-导出数据表"+nowDate);
    }


    @Log(title = "化学品导入", businessType = BusinessType.IMPORT)
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,HxpChemicalByExcel hxpChemicalByExcel) throws Exception {
        ExcelUtil<HxpChemicalByExcel> util = new ExcelUtil<HxpChemicalByExcel>(HxpChemicalByExcel.class);
        List<HxpChemicalByExcel> chemicalList = util.importExcel(file.getInputStream(),true);
        String operName = SecurityUtils.getUsername();
        List<HxpChemicalByExcel> hxpChemicalByExcels = hxpChemicalService.importUserByChemical(chemicalList, operName, hxpChemicalByExcel);
        Map <String,Object> resultMap = new HashMap <>();
        resultMap.put("totalNum",chemicalList.size());
        resultMap.put("successNum",chemicalList.size()- hxpChemicalByExcels.size());
        resultMap.put("failureNum", hxpChemicalByExcels.size());
        resultMap.put("downFile", hxpChemicalByExcels.size()>0?true:false);
        if(hxpChemicalByExcels.size()>0){
            redisService.setCacheObject("exportByChemical"+SecurityUtils.getUserId(), hxpChemicalByExcels, 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、请注意：CAS号是唯一的，不能重复，不可多条。\n" +
                "6、请注意：需填写系统中已录入的对应数据名称，否则无法正常导入。\n" +
                "系统字段要求提示："+
                "化学品分类：普通化学品、危险化学品；"+
                "化学品属性：爆炸品、压缩气体或液化气体、易燃液体、易燃固体、自燃物品和遇湿易燃物品、氧化剂和有机过氧化物、有毒品、放射性物品、腐蚀品、无；"+
                "形态：固体、液体、气体、其他；"+
                "标签类型：二维码、RFID。";
        ExcelUtil<HxpChemicalByExcel> util = new ExcelUtil<HxpChemicalByExcel>(HxpChemicalByExcel.class);
        List<HxpChemicalByExcel> chemicalByExcels = redisService.getCacheObject("exportByChemical"+SecurityUtils.getUserId());
        if(chemicalByExcels.size()>0){
            util.exportExcel(response, chemicalByExcels, "未导入的化学品数据数据", tips, "化学品批量导入模板");
        }
    }


    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        String tips = "导入注意事项：（未按如下要求填写，会导致数据不能正常导入）\n" +
                "1、请不要修改此表格的格式，包括插入删除行和列、合并拆分单元格等。请在表格里面逐行录入数据。一次最多导入5000条数据信息。\n" +
                "2、需要填写的单元格字段规则校验，请按照提示输入。\n" +
                "3、请不要随意复制单元格，这样会破坏字段规则校验。\n" +
                "4、带有星号（*）的红色字段为必填项。\n" +
                "5、请注意：CAS号是唯一的，不能重复，不可多条。\n" +
                "6、请注意：需填写系统中已录入的对应数据名称，否则无法正常导入。\n" +
                "系统字段要求提示："+
                "化学品分类：普通化学品、危险化学品；"+
                "化学品属性：爆炸品、压缩气体或液化气体、易燃液体、易燃固体、自燃物品和遇湿易燃物品、氧化剂和有机过氧化物、有毒品、放射性物品、腐蚀品、无；"+
                "形态：固体、液体、气体、其他；"+
                "标签类型：二维码、RFID。";
        ExcelUtil<HxpChemicalByExcel> util = new ExcelUtil<HxpChemicalByExcel>(HxpChemicalByExcel.class);
        util.exportExcel(response, null, "化学品信息", tips, "化学品信息-批量导入模板");
    }

    /**
     * 获取化学品信息详细信息
     */
    @ApiOperation(value = "获取化学品信息详细信息")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public ResultData<HxpChemical> getInfo(@PathVariable("id") Long id) {
        return ResultData.success(hxpChemicalService.selectHxpChemicalById(id));
    }

    /**
     * 获取化学品信息详细信息(学生端专用)
     */
    @ApiOperation(value = "获取化学品信息详细信息(学生端专用)")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.QUERY)
    @GetMapping(value = "/myInfo/{id}")
    public ResultData<HxpChemical> myInfo(@PathVariable("id") Long id) {
        return ResultData.success(hxpChemicalService.selectHxpChemicalById(id));
    }

    /**
     * 新增化学品信息
     */
    @ApiOperation(value = "新增化学品信息")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.ADD)
    @Log(title = "化学品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData add(@RequestBody HxpChemical hxpChemical) {
        return ResultData.result(hxpChemicalService.insertHxpChemical(hxpChemical));
    }

    /**
     * 修改化学品信息
     */
    @ApiOperation(value = "修改化学品信息")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.EDIT)
    @Log(title = "化学品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData edit(@RequestBody HxpChemical hxpChemical) {
        return ResultData.result(hxpChemicalService.updateHxpChemical(hxpChemical));
    }


    /**
     * 修改化学品信息(绑定危险源数据)
     */
    @ApiOperation(value = "修改化学品信息")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.EDIT)
    @Log(title = "化学品信息", businessType = BusinessType.UPDATE)
    @PutMapping("/editChemicalByJoinHazard")
    public ResultData editChemicalByJoinHazard(@RequestBody HxpChemical hxpChemical) {
        return ResultData.result(hxpChemicalService.editChemicalByJoinHazard(hxpChemical));
    }

    /**
     * 删除化学品信息
     */
    @ApiOperation(value = "删除化学品信息")
    @PreAuthorize(hasPermi = PerPrefix.HPX_CHEMICAL+PerFun.REMOVE)
    @Log(title = "化学品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData remove(@PathVariable Long[] ids) {
        HxpChemicalJoinCabinetSearch hxpChemicalJoinCabinetSearch = new HxpChemicalJoinCabinetSearch();
        hxpChemicalJoinCabinetSearch.setChemicalId(ids[0]);
        List<HxpChemicalJoinCabinetListVo> list = hxpChemicalJoinCabinetService.selectHxpChemicalJoinCabinetList(hxpChemicalJoinCabinetSearch);
        if(list.size()>0){
            throw new ServiceException("化学品已有入库记录，无法删除！");
        }
        return ResultData.result(hxpChemicalService.deleteHxpChemicalByIds(ids));
    }


    /**
     * 查询化学品信息列表
     */
    @GetMapping("/noAuthlist")
    @ApiOperation(value = "查询化学品信息列表")
    public TableDataInfo<HxpChemicalVo> noAuthlist(HxpChemicalSearch hxpChemicalSearch) {
        startPage();
        List<HxpChemicalVo> list = hxpChemicalService.selectHxpChemicalList(hxpChemicalSearch);
        return getDataTable(list);
    }

    @ApiOperation(value = "查询实验室化学品临界量风险指标")
    @GetMapping("/queryCriticaliBySubId")
    public R<List<Map<String, Object>>> queryCriticaliBySubId(@RequestParam List<Long> subIds) {
        if(subIds.isEmpty()){
            return R.ok(ListUtil.empty());
        }
        return R.ok(hxpChemicalService.queryCriticaliBySubId(subIds));
    }


    @ApiOperation(value = "定时监测实验室化学品存放风险指标")
    @Log(title = "定时监测实验室化学品存放风险指标", businessType = BusinessType.OTHER)
    @PostMapping("/indicatorMonitoring")
    public void indicatorMonitoring() {
        hxpChemicalService.indicatorMonitoring();
    }


}
