package com.yeejoin.equipmanage.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.vo.DetailssAmountVO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentDetailDownloadVO;
import com.yeejoin.equipmanage.common.enums.ExcelEnums;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.common.vo.EquipmentDate;
import com.yeejoin.equipmanage.dto.ExcelDto;
import com.yeejoin.equipmanage.fegin.JcsFeign;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.*;
import com.yeejoin.equipmanage.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wujiang
 * @date 2020-07-07
 */
@RestController
@Api(tags = "装备详情 Api")
@RequestMapping(value = "/equipment-detail", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class EquipmentDetailController extends AbstractBaseController {

    @Autowired
    IEquipmentDetailService iEquipmentDetailService;

    @Autowired
    IEquipmentParamsService iEquipmentParamsService;

    @Autowired
    IEquipmentParamsService equipmentParamsService;

    @Autowired
    IEquipmentCategoryService iEquipmentCategoryService;

    @Autowired
    IFireFightingSystemService fireFightingSystemService;

    @Autowired
    EquipmentDetailMapper equipmentDetailMapper;

    @Autowired
    EquipmentParamsMapper equipmentParamsMapper;
    @Autowired
    private StockDetailMapper stockDetailMapper;
    @Autowired
    @Lazy
    IStockService iStockService;
    @Autowired
    private ManufacturerInfoMapper manufacturerInfoMapper;

    @Autowired
    private IEquipmentSpecificIndexSerivce equipmentSpecificIndexSerivce;

    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificSerivce;

    @Autowired
    private IExcelService excelService;

    @Autowired
    private JcsFeign jcsFeign;

    @Autowired
    private IWarehouseStructureService warehouseStructureService;

    @Autowired
    private ISyncDataService syncDataService;

    @Autowired
    private EquipmentCategoryMapper equipmentCategoryMapper;

    @Autowired
    private IEquipmentFaultKnowledgeService equipmentFaultKnowledgeService;


    @Value("${systemctl.sync.switch}")
    private Boolean syncSwitch;

    /**
     * 新增
     *
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
    public EquipmentDetail saveEquipmentDetail(HttpServletRequest request, @RequestBody EquipmentDetail equipmentDetail) {
        return iEquipmentDetailService.saveOne(equipmentDetail);
    }


    /**
     * 设备新增带打码入库
     ***/
    @RequestMapping(value = "/saveEquipment", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
    public EquipmentDate saveEquipmentDetail(@RequestBody EquipmentDate equipmentDate) {

        EquipmentSpecific  vo = equipmentDate.getEquipmentSpecific();
        EquipmentDetail  de = equipmentDate.getEquipmentDetail();
        String eqcode = de.getEqcode();

        if (StringUtils.isNotEmpty(eqcode) && StringUtils.isNotEmpty(eqcode.trim())){
            int code = iEquipmentDetailService.count(new QueryWrapper<EquipmentDetail>().eq("eq_code", eqcode.trim()));
            if (code != 0 ) {
                throw new BadRequest("部件编码填写重复，请重新输入！");
            }
        }

        String iot = vo.getIotCode();
        if (StringUtils.isNotEmpty(iot) && StringUtils.isNotEmpty(iot.trim())){
            int iot_code = equipmentSpecificSerivce.count(new QueryWrapper<EquipmentSpecific>().eq("iot_code", iot.trim()));
            if (iot_code != 0 ) {
                throw new BadRequest("物联编码填写重复，请重新输入！");
            }
        }
        EquipmentDate date = equipmentSpecificSerivce.equipmentSpecificCreate(equipmentDate, getSelectedOrgInfo(), getUserInfo());
       // equipmentDate.getEquipmentParams().setCode(equipmentDate.getEquipmentDetail().getEqcode());
       // iEquipmentParamsService.saveOne(equipmentDate.getEquipmentParams());
        // TODO 后续判断成功，执行同步
        Long equipmentId = date.getEquipmentDetail().getEquipmentId();
//         编辑同步redis装备iotcode数据
        syncDataService.saveOrUpdateEquipIotCodeRedisData(null);
        if (syncSwitch) {
            equipmentSpecificSerivce.equipSpecificDataSync(date.getEquipmentSpecific().getId());
        }
        return equipmentDate;
    }


    /***
     *
     * 根id查询
     *
     * **/
    @RequestMapping(value = "equipment/{code}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据二维码查询", notes = "根据二维码查询")
    public EquipmentDate selectByCode(HttpServletRequest request, @PathVariable String code) {
        EquipmentDate equipmentDate = new EquipmentDate();
        EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.equipmentByQrcode(code);
        EquipmentDetail equipmentDetail = iEquipmentDetailService.getOneById(equipmentSpecific.getEquipmentDetailId());
        equipmentDate.setEquipmentDetail(equipmentDetail);
        equipmentDate.setEquipmentSpecific(equipmentSpecific);
        return equipmentDate;
    }

    /***
     *
     * 根id查询
     *
     * **/
    @RequestMapping(value = "/selectequipmentDateById", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public EquipmentDate selectequipmentDateById(@RequestParam Long id,
                                                 @RequestParam(required = false) Long stockDetailId) {
        EquipmentDate equipmentDate = new EquipmentDate();
        EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(id);
        String iotCode=equipmentSpecific.getIotCode();
        equipmentSpecific.setFullqrCode("01#" + equipmentSpecific.getQrCode());
        EquipmentDetail equipmentDetail = iEquipmentDetailService.getOneById(equipmentSpecific.getEquipmentDetailId());

        //查找装备故障的最后一条状态
        QueryWrapper<EquipmentParams> wrapper = new QueryWrapper<>();
        wrapper.eq("detail_id",iotCode);//故障记录表中的detail_id 是装备的iotCode
        wrapper.orderByDesc("create_date");
        List<EquipmentParams> equipmentParams = equipmentParamsMapper.selectList(wrapper);
        if(!equipmentParams.isEmpty()){
            EquipmentParams equipmentParam = equipmentParams.get(0);
            equipmentDetail.setStatus(equipmentParam.getStatus());
        }else{
            equipmentDetail.setStatus("正常");
        }
        StockDetail stockDetail = null;
        if(stockDetailId != null){
            //解决灭火药剂，有多个货位状态问题
            stockDetail = stockDetailMapper.selectById(stockDetailId);
            equipmentSpecific.setStockDetail(stockDetail);
        }else {
            //消防装备默认分支
            List<StockDetail> stockDetails = stockDetailMapper.selectList(new LambdaQueryWrapper<StockDetail>().eq(StockDetail::getEquipmentSpecificId,id));
            if(!stockDetails.isEmpty()){
                stockDetail = stockDetails.get(0);
                equipmentSpecific.setStockDetail(stockDetail);
            }
        }
        if (stockDetail != null) {
            equipmentSpecific.setStock(iStockService.getById(stockDetail.getStockId()));
        }
        equipmentDate.setEquipmentDetail(equipmentDetail);
        //equipmentDate.setEquipmentParams(equipmentParams);
        equipmentDate.setEquipmentSpecific(equipmentSpecific);
        return equipmentDate;
    }



    /***
     *
     * 修改
     * **/
    @RequestMapping(value = "equipment/updateById", method = RequestMethod.PUT)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "修改", notes = "修改")
    public EquipmentDate updateByIdEquipmentDetail(HttpServletRequest request, @RequestBody EquipmentDate equipmentDate) {

        EquipmentDetail  de = equipmentDate.getEquipmentDetail();
        String eqcode = de.getEqcode();

        if (StringUtils.isNotEmpty(eqcode) && StringUtils.isNotEmpty(eqcode.trim())){
            int code = iEquipmentDetailService.count(new QueryWrapper<EquipmentDetail>().eq("eq_code", de.getEqcode()).ne("id",de.getId()));
            if (code != 0) {
                throw new BadRequest("部件编码填写重复，请重新输入！");
            }
        }
        EquipmentSpecific vo = equipmentDate.getEquipmentSpecific();
        String iot = vo.getIotCode();
        if (StringUtils.isNotEmpty(iot) && StringUtils.isNotEmpty(iot.trim())){
            int iotCode = equipmentSpecificSerivce.count(new QueryWrapper<EquipmentSpecific>().eq("iot_code", vo.getIotCode()).ne("id",vo.getId()));
            if (iotCode > 0){
                throw new BadRequest("设备物联编码重复");
            }
        }
        //1.更新装备实例Detail数据
        EquipmentDetail equipmentDetail = equipmentDate.getEquipmentDetail();
       // EquipmentParams equipmentParams = equipmentDate.getEquipmentParams();
        final EquipmentDetail dateEquipmentDetail = equipmentDate.getEquipmentDetail();
        boolean b = iEquipmentDetailService.updateOneById(equipmentDate.getEquipmentSpecific().getId(), dateEquipmentDetail);
     /*   if(b){
            equipmentParamsService.updateById(equipmentDate.getEquipmentParams());
        }*/
        //2.更新装备实例主表数据
        Long detailId = dateEquipmentDetail.getId();
        equipmentDate.getEquipmentSpecific().setEquipmentDetailId(detailId);
        EquipmentSpecific equipmentSpecific = equipmentDate.getEquipmentSpecific();
        equipmentSpecific.setName(equipmentDetail.getName());
        EquipmentDetail bean = iEquipmentDetailService.getById(dateEquipmentDetail.getId());
        if (!ObjectUtils.isEmpty(bean)) {
            equipmentSpecific.setEquipmentCode(bean.getCode());
        }
        Long warehouseStructureId = ObjectUtils.isEmpty(equipmentSpecific.getStockDetail()) ? null : equipmentSpecific.getStockDetail().getWarehouseStructureId();
        if (warehouseStructureId != null) {
            WarehouseStructure warehouseStructure = warehouseStructureService.getById(warehouseStructureId);
            if (!ObjectUtils.isEmpty(warehouseStructure)) {
                equipmentSpecific.setPosition(warehouseStructure.getFullName());
            }
        }
        if (!ObjectUtils.isEmpty(equipmentSpecific.getStockDetail())) {
            equipmentSpecific.getStockDetail().setDescription(equipmentDetail.getArea());
        }
        equipmentSpecificSerivce.updateEquipmentSpecific(equipmentSpecific, getSelectedOrgInfo(), getUserInfo());
        // TODO 后续判断成功，执行同步
        // 编辑同步redis装备iotcode数据
        syncDataService.saveOrUpdateEquipIotCodeRedisData(null);
        if (syncSwitch) {
            equipmentSpecificSerivce.equipSpecificDataSync(equipmentSpecific.getId());
        }
        return equipmentDate;
    }


    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(HttpServletRequest request, @PathVariable Long id) {
        return iEquipmentDetailService.removeOneById(id);
    }

    @RequestMapping(value = "/updatequota", method = RequestMethod.PUT)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "修改", notes = "修改")
    public boolean quotaUpdate(HttpServletRequest request, @RequestBody List<EquProperty> e) {
        return iEquipmentDetailService.quotaUpdate(e);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public EquipmentDetail selectById(HttpServletRequest request, @PathVariable Long id) {
        return iEquipmentDetailService.getOneById(id);
    }


    @RequestMapping(value = "/listDate", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public Page listPage(@RequestParam(value = "current") int pageNum,
                         @RequestParam(value = "size") int pageSize,
                         @RequestParam(required = false) String name,
                         @RequestParam(required = false) String standard,
                         @RequestParam(required = false) String manufacturerName) {
        int start = (pageNum - 1) * pageSize;
        List<Map<String, Object>> list = equipmentSpecificIndexSerivce.selectEquList(start, pageSize, name, standard, manufacturerName);
        List<Map<String, Object>> list2 = equipmentSpecificIndexSerivce.selectEquListcount(name, standard, manufacturerName);

        Page psge = new Page(pageNum, pageSize, list2 == null ? 0 : list2.size());
        psge.setRecords(list);
        return psge;

    }



    /**
     * 列表分页查询
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<EquipmentDetail> listPage(String pageNum, String pageSize, EquipmentDetail equipmentDetail) {

        Page<EquipmentDetail> pageBean;
        QueryWrapper<EquipmentDetail> equipmentDetailQueryWrapper = new QueryWrapper<>();
        Class<? extends EquipmentDetail> aClass = equipmentDetail.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(equipmentDetail);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(equipmentDetail);
                        equipmentDetailQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(equipmentDetail);
                        equipmentDetailQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(equipmentDetail);
                        equipmentDetailQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(equipmentDetail);
                        equipmentDetailQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
            }
        });
        IPage<EquipmentDetail> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iEquipmentDetailService.page(pageBean, equipmentDetail);
        return page;
    }

    /**
     * 列表分类查询
     *
     * @return
     */
    @RequestMapping(value = "/list/category/{category}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "列表分类查询", notes = "列表分类查询")
    public IPage<EquipmentDetail> list(String pageNum, String pageSize, @PathVariable String category) {
        Page<EquipmentDetail> pageBean;
        IPage<EquipmentDetail> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iEquipmentDetailService.page(pageBean, category);
        return page;
    }



    /**
     * <pre>
     * 装备补码操作
     * </pre>
     *
     * @return CommonResponse
     * @throws @version: 1.0
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "装备补码操作", notes = "装备补码操作，根据条件查询")
    @RequestMapping(value = "/complement_code", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public IPage<StockDetail> ComplementCode(String pageNum, String pageSize, String equipmentDetailId, String qrCode,
                                             String status) {
        try {

            Page<StockDetail> pageBean;
            IPage<StockDetail> page;
            if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
                pageBean = new Page<>(0, Long.MAX_VALUE);
            } else {
                pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            }
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.isNotNull("qr_code");
            queryWrapper.ne("qr_code", "");
            if (qrCode != null && !"".equals(qrCode)) {
                queryWrapper.like("qr_code", qrCode);
            }
            if (equipmentDetailId != null && !"".equals(equipmentDetailId)) {
                queryWrapper.eq("equipment_detail_id", equipmentDetailId);
            }
            if (status != null && !"".equals(status)) {
                queryWrapper.eq("status", status);
            }

            IPage<StockDetail> stockDetail = stockDetailMapper.selectPage(pageBean, queryWrapper);
            List<StockDetail> list = stockDetail.getRecords();
            for (int i = 0; i < list.size(); i++) {

                EquipmentDetail equipmentDetail = equipmentDetailMapper.selectById(list.get(i).getEquipmentDetailId());

                list.get(i).setEquipmentDetail(equipmentDetail);

            }
            stockDetail.setRecords(list);
            return stockDetail;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

    /**
     * 批量删除
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean delete(HttpServletRequest request, @RequestBody List<Long> idList) throws Exception {
        return iEquipmentDetailService.removeBatchById(idList);
    }

    /**
     * 设备信息下载
     *
     * @return
     */
    @PostMapping(value = "/downList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "下载模板", notes = "下载模板")
    public void downList(HttpServletResponse response, @RequestBody List<Long> ids) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        QueryWrapper<EquipmentDetail> equipmentDetailQueryWrapper = new QueryWrapper<>();
        if (ids.size() > 0) {
            equipmentDetailQueryWrapper.in("id", ids);
        }
        List<EquipmentDetail> equipmentDetails = iEquipmentDetailService.list(equipmentDetailQueryWrapper);
        List<EquipmentDetailDownloadVO> equipmentDetailDownloads = new ArrayList<>();
        equipmentDetails.forEach(x -> {
            EquipmentDetailDownloadVO equipmentDetailDownloadVO = new EquipmentDetailDownloadVO();
            equipmentDetailDownloadVO.setId(x.getId());
            equipmentDetailDownloadVO.setName(x.getName());
            equipmentDetailDownloadVO.setStandard(x.getStandard());
            equipmentDetailDownloadVO.setManufacturerName(manufacturerInfoMapper.selectById(x.getManufacturerId()).getName());
            equipmentDetailDownloads.add(equipmentDetailDownloadVO);
        });
        ExcelUtils.exportExcel(equipmentDetailDownloads, "设备信息", "设备信息", EquipmentDetailDownloadVO.class, simpleDateFormat.format(new Date()) + ".xlsx", response);
    }

    /**
     * 下载模板
     * @Since 2021-3-10
     * @return
     */
    @GetMapping(value = "/downTemplate")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "下载模板", notes = "下载模板")
    public void downTemplate(HttpServletResponse response) throws ClassNotFoundException {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
//        List<EquipmentDetailDownloadTemplateVO> equipmentDetailDownloads = new ArrayList<>();
//        ExcelUtils.exportExcel(equipmentDetailDownloads, "设备信息", "设备信息", EquipmentDetailDownloadTemplateVO.class, simpleDateFormat.format(new Date()) + ".xls", response);

        try {
            // 判读机场服务是否在线
            ExcelEnums excelEnums;
            ResponseModel<String[]> result = jcsFeign.getEquipmentInfo(getAppKey(), getProduct(), getToken(), null, "getCompany");
            if(200 == result.getStatus()) {
                excelEnums=  ExcelEnums.getByKey(ExcelEnums.XFZB.getType());
                ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(), excelEnums.getClassUrl(), excelEnums.getType());
                String url = excelDto.getClassUrl();
                Class<?> clz = Class.forName(url);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz, getToken(),
                        getAppKey(), getProduct(), true);
            }

        } catch (Exception e) {
            ExcelEnums excelEnums =  ExcelEnums.getByKey(ExcelEnums.XFZBSINGLE.getType());
            ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(), excelEnums.getClassUrl(), excelEnums.getType());
            String url = excelDto.getClassUrl();
            Class<?> clz = Class.forName(url);
            ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz, getToken(),
                    getAppKey(), getProduct(), true);
        }
    }

    /**
     * 单个设备信息导入
     * @Since 2021-3-10
     * @return
     */
    @PostMapping(value = "/uploadListByTemplate")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "单个设备信息导入", notes = "单个设备信息导入")
    public ResponseModel<Object> uploadListByTemplate(MultipartFile file, @RequestParam(value = "type")  String type)  throws Exception {
//        try {
//            InputStream inputStream = null;
//            Workbook workbook = null;
//            inputStream = file.getInputStream();
//            workbook = WorkbookFactory.create(inputStream);
//            inputStream.close();
//            Sheet sheet = workbook.getSheetAt(0);
//            String b = sheet.getRow(0).getCell(1).getStringCellValue();
//            if ( !"器材编码（从装备定义中获取）".equals(b)){
//                throw new Exception();
//            }
//        } catch (Exception e) {
//            throw new BadRequest("请使用指定模板进行上传");
//        }

        // List<EquipmentDetailDownloadTemplateVO> equipmentDetailDownloadS = ExcelUtils.importExcel(file, 1, 1, EquipmentDetailDownloadTemplateVO.class);

        ExcelEnums excelEnums=  ExcelEnums.getByKey(type);
        ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(), excelEnums.getClassUrl(), excelEnums.getType());

        excelService.commonUpload(file, excelDto,getSelectedOrgInfo(), getUserInfo());
        // return iStockService.uploadListByTemplate(equipmentDetailDownloadS, getSelectedOrgInfo(), getUserInfo());
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 设备信息导入
     *
     * @return
     */
    @PostMapping(value = "/uploadList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "导入", notes = "导入")
    public List<EquipmentSpecific> uploadList(MultipartFile file) {
        List<EquipmentDetailDownloadVO> equipmentDetailDownloadS = ExcelUtils.importExcel(file, 1, 1, EquipmentDetailDownloadVO.class);
        return iStockService.uploadList(equipmentDetailDownloadS, getSelectedOrgInfo(), getUserInfo());
    }

    @RequestMapping(value = "/getPref", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public String getPref(@RequestParam(value = "id") String id) {
        String temp = iEquipmentDetailService.getPref(id);
        return StringUtil.isNotEmpty(temp) ? temp : "";
    }

    @RequestMapping(value = "/checkDelete", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public String checkDelete(HttpServletRequest request,
                              @ApiParam(value = "装备定义idList", required = true) @RequestBody List<Long> ids) {
        return iEquipmentDetailService.checkDelete(ids);
    }

    /**
     * 导出隐患清单
     */

    @ApiOperation(value = "导出装备清单", notes = "导出装备清单")
    @PostMapping(value = "/export",produces = "application/json;charset=UTF-8")
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    public void exportDangerList(@RequestBody List<DetailssAmountVO> detailssAmountVO,@RequestParam Integer prop, HttpServletResponse response) {
        String fileName =new Date().toString();
        SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
        String format = formatter.format(new Date());
        if(prop==1){//全部导出
            List<DetailssAmountVO> getall = iEquipmentDetailService.getall();
            List<DetailssAmountVO> detailssAmountVOS = this.selectReasonMeasure(getall);
            FileHelper.exportExcel(detailssAmountVOS, "装备清单", "装备清单", DetailssAmountVO.class, format + ".xls", response);
        }
        else {//仅仅导出筛选结果的数据
            List<DetailssAmountVO> detailssAmountVOS = this.selectReasonMeasure(detailssAmountVO);
            FileHelper.exportExcel(detailssAmountVOS, "装备清单", "装备清单", DetailssAmountVO.class, format + ".xls", response);
        }
    }


    /**
     * 查找原因分析和处置措施
     */
    private List<DetailssAmountVO> selectReasonMeasure(List<DetailssAmountVO> detailssAmountVO){
        for(DetailssAmountVO model:detailssAmountVO){
            Long id = model.getId();
            String  iotCode = equipmentSpecificSerivce.getById(id).getIotCode();
            QueryWrapper<EquipmentParams> wrapper = new QueryWrapper<>();
            wrapper.eq("detail_id",iotCode);
            wrapper.orderByDesc("create_date");
            List<EquipmentParams> equipmentParams =iEquipmentParamsService.list(wrapper);
            if(!equipmentParams.isEmpty()){
                EquipmentParams equipmentParam = equipmentParams.get(0);
                model.setStatus(equipmentParam.getStatus());
                String faultKnowledgeId = equipmentParam.getFaultKnowledgeId();//这里的knowledgeId  是只是库里面的type字段
                QueryWrapper<EquipmentFaultKnowledge> wrapperKnowledge = new QueryWrapper<>();
                wrapperKnowledge.eq("type",faultKnowledgeId);
                EquipmentFaultKnowledge equipmentFaultKnowledge = equipmentFaultKnowledgeService.list(wrapperKnowledge).get(0);
                model.setReason(equipmentFaultKnowledge.getType());
                model.setMeasure(equipmentFaultKnowledge.getMeasure());
            }else{
                model.setStatus("正常");
            }
        }
        return detailssAmountVO;
    }

    /**
     * 根据equipCode查询故障记录
     *
     * @return
     */
    @GetMapping(value = "/eqParamsList")
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "按照id故障记录查询", notes = "按照id故障记录查询")
    public IPage<EquipmentParams> list(@RequestParam(name = "cur")String pageNum, @RequestParam(name = "pageSize")String pageSize, @RequestParam(name = "specificId") Long specificId) {
        Page<EquipmentParams> pageBean;
        IPage<EquipmentParams> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        EquipmentSpecific equmentSpecific = equipmentSpecificSerivce.getById(specificId);
        String iotCode = equmentSpecific.getIotCode();
        QueryWrapper<EquipmentParams> wrapper = new QueryWrapper<>();
        wrapper.eq("detail_id",iotCode);
        wrapper.orderByDesc("create_date");
        page = iEquipmentParamsService.page(pageBean, wrapper);
        List<EquipmentParams> records = page.getRecords();
        for(EquipmentParams ep :records){
            String faultKnowledgeId = ep.getFaultKnowledgeId();
            QueryWrapper<EquipmentFaultKnowledge> wrapperKnowledge = new QueryWrapper<>();
            wrapperKnowledge.eq("type",faultKnowledgeId);
            EquipmentFaultKnowledge model = equipmentFaultKnowledgeService.list(wrapperKnowledge).get(0);
            ep.setType(model.getType());
            ep.setMeasure(model.getMeasure());
            ep.setReason(model.getReason());
        }
        return page;
    }


}
