package com.inspect.metadata.prodevmnt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.metadata.area.domain.BaseDataArea;
import com.inspect.metadata.area.service.IBaseDataAreaService;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.service.IBasedataEqpBookService;
import com.inspect.metadata.mqutil.FeignMsgClient;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPoint;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.prodevmnt.domain.BasedataDevice;
import com.inspect.metadata.prodevmnt.domain.BasedataDeviceType;
import com.inspect.metadata.prodevmnt.domain.TreeModule;
import com.inspect.metadata.prodevmnt.domain.vo.ProDeviceTreeSelectVO;
import com.inspect.metadata.prodevmnt.domain.vo.ProMainDevicePatrolEquTreeSelect;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceService;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceTypeService;
import com.inspect.metadata.prodevmnt.util.ExportExcelUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.annotation.RequiresPermissions;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;
import com.inspect.system.base.openDomain.PatrolTaskDomain;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping({"/prodevmnt/device"})
public class BasedataDeviceController extends BaseController {
    private final IBasedataDeviceService basedataDeviceService;
    private final IBaseDataAreaService baseDataAreaService;
    private final FeignMsgClient feignMsgClient;
    private final IBasedataEqpBookService basedataEqpBookService;
    private final IBasedataDeviceTypeService basedataDeviceTypeService;
    private final IBasedataPatrolPointService basedataPatrolPointService;

    public BasedataDeviceController(IBasedataDeviceService basedataDeviceService, IBaseDataAreaService baseDataAreaService, FeignMsgClient feignMsgClient, IBasedataEqpBookService basedataEqpBookService, IBasedataDeviceTypeService basedataDeviceTypeService, IBasedataPatrolPointService basedataPatrolPointService) {
        this.basedataDeviceService = basedataDeviceService;
        this.baseDataAreaService = baseDataAreaService;
        this.feignMsgClient = feignMsgClient;
        this.basedataEqpBookService = basedataEqpBookService;
        this.basedataDeviceTypeService = basedataDeviceTypeService;
        this.basedataPatrolPointService = basedataPatrolPointService;
    }

    @RequiresPermissions({"basedata/prodevmnt:device:list"})
    @GetMapping({"/list"})
    public TableDataInfo list(BasedataDevice basedataDevice) {
        this.startPage();
        List<BasedataDevice> list = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
        return this.getDataTable(list);
    }

    @RequiresPermissions({"basedata/prodevmnt:device:export"})
    @Log(
            title = "生产设备",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, BasedataDevice basedataDevice) {
        List<BasedataDevice> list = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
        Map<Object, Object> mapNew = new HashMap<>();
        Map<String, Long> map = this.baseDataAreaService.selectAreaForNamePatch(new BaseDataArea());
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            mapNew.put(map.get(key), key.toString());
        }

        iterator = list.iterator();

        while (iterator.hasNext()) {
            BasedataDevice basedataDeviceList = (BasedataDevice) iterator.next();
            Long ss = basedataDeviceList.getAreaId();
            if (mapNew.containsKey(ss)) {
                String str = mapNew.get(ss).toString();
                basedataDeviceList.setAreaName(str);
            }
        }

        ExcelUtil<BasedataDevice> util = new ExcelUtil<>(BasedataDevice.class);
        util.exportExcel(response, list, "生产设备数据");
    }

    @GetMapping({"/{deviceId}"})
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return AjaxResult.success(this.basedataDeviceService.selectBasedataDeviceByDeviceId(deviceId));
    }

    @RequiresPermissions({"basedata/prodevmnt:device:add"})
    @Log(
            title = "生产设备",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody BasedataDevice basedataDevice) {
        try {
            return this.toAjax(this.basedataDeviceService.insertBasedataDevice(basedataDevice));
        } catch (Exception var3) {
            return AjaxResult.error("添加失败，设备编号不能重复！");
        }
    }

    @RequiresPermissions({"basedata/prodevmnt:device:edit"})
    @Log(
            title = "生产设备",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody BasedataDevice basedataDevice) {
        return "1".equals(this.basedataDeviceService.checkDeviceCodeUnique(basedataDevice)) ? AjaxResult.error("设备'" + basedataDevice.getDeviceName() + "'添加失败，设备编码已存在") : ("1".equals(this.basedataDeviceService.checkDeviceNameUnique(basedataDevice)) ? AjaxResult.error("设备'" + basedataDevice.getDeviceCode() + "'修改失败，设备名称已存在") : this.toAjax(this.basedataDeviceService.updateBasedataDevice(basedataDevice)));
    }

    @RequiresPermissions({"basedata/prodevmnt:device:remove"})
    @Log(
            title = "生产设备",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{deviceIds}"})
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        BasedataPatrolPoint basedataPatrolpoint = new BasedataPatrolPoint();
        basedataPatrolpoint.setDeviceId(deviceIds[0]);
        List<BasedataPatrolPoint> basedataPatrolPoints = this.basedataPatrolPointService.selectBasedataPatrolPointList(basedataPatrolpoint);
        if (!basedataPatrolPoints.isEmpty()) {
            return AjaxResult.error("删除失败，设备已绑定巡检点！");
        } else {
            BasedataDevice basedataDevice = new BasedataDevice();
            basedataDevice.setParentId(deviceIds[0]);
            List<BasedataDevice> deviceList = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
            return !deviceList.isEmpty() ? AjaxResult.error("删除失败，设备存在部件，请先删除部件！") : this.toAjax(this.basedataDeviceService.deleteBasedataDeviceByDeviceIds(deviceIds));
        }
    }

    @PostMapping({"/exportTemplate"})
    public void exportTemplate(HttpServletResponse response) {
        ExportExcelUtil.exportTemplate(response, "生产设备导入模板.xlsx");
    }

    @GetMapping({"/getDeviceInfo/{patrolPointId}"})
    public AjaxResult getDeviceInfo(@PathVariable String patrolPointId) {
        return AjaxResult.success(this.basedataDeviceService.selectBasedataDeviceByPatrolPointId(patrolPointId));
    }

    @GetMapping({"/treeAreaDeviceSelect"})
    public AjaxResult treeAreaDeviceSelect(BaseDataArea area) {
        log.info("treeAreaDeviceSelect param: {}", area);
        List<BaseDataArea> areas = this.baseDataAreaService.selectAreaList(area);
        return null != areas && !areas.isEmpty() ? AjaxResult.success(this.basedataDeviceService.buildAreaDeviceTreeSelectByAreas(areas)) : AjaxResult.success(new JSONArray());
    }

    @GetMapping({"/treeAreaDeviceSelectFilterByPreset"})
    public AjaxResult treeAreaDeviceSelectFilterByPreset(BaseDataArea baseDataArea) {
        log.info("treeAreaDeviceSelectFilterByPreset param: {}", baseDataArea);
        List<BaseDataArea> areaList = baseDataAreaService.selectAreaList(baseDataArea);
        List<String> filterNameList = baseDataArea.getFilterNameList();
        if(filterNameList == null || filterNameList.isEmpty()) {
            filterNameList = new ArrayList<>();
            filterNameList.add("无人机");
            filterNameList.add("机器人");
            filterNameList.add("安防摄像头");
            filterNameList.add("生活区域");
            filterNameList.add("新增相机");
        }
        return !areaList.isEmpty()
                ? AjaxResult.success(basedataDeviceService.buildAreaDeviceTreeSelectByAreasFilterByPreset(areaList, filterNameList))
                : AjaxResult.success(new JSONArray());
    }

    /**
     * 用于迁移的左侧列表展示原始数据（叶子节点有点位）
     * @param baseDataArea
     * @return
     */
    @GetMapping({"/treeAreaDeviceSelectFilterByPreset/relation/left"})
    public AjaxResult treeAreaDeviceSelectFilterByPresetLeft(BaseDataArea baseDataArea) {
        log.info("treeAreaDeviceSelectFilterByPreset param: {}", baseDataArea);
        List<BaseDataArea> areaList = baseDataAreaService.selectAreaList(baseDataArea);
        List<String> filterNameList = baseDataArea.getFilterNameList();
        if(filterNameList == null || filterNameList.isEmpty()) {
            filterNameList = new ArrayList<>();
            filterNameList.add("无人机");
            filterNameList.add("机器人");
            filterNameList.add("安防摄像头");
            filterNameList.add("生活区域");
            filterNameList.add("新增相机");
        }
        return !areaList.isEmpty()
                ? AjaxResult.success(basedataDeviceService.buildAreaDeviceTreeSelectByAreasFilterByPresetRelationLeft(areaList, filterNameList))
                : AjaxResult.success(new JSONArray());
    }

    /**
     * 用于迁移的右侧列表展示（叶子节点有点位）
     * @param baseDataArea
     * @return
     */
    @GetMapping({"/treeAreaDeviceSelectFilterByPreset/relation/right"})
    public AjaxResult treeAreaDeviceSelectFilterByPresetRight(BaseDataArea baseDataArea) {
        log.info("treeAreaDeviceSelectFilterByPreset param: {}", baseDataArea);
        List<BaseDataArea> areaList = baseDataAreaService.selectAreaRelationList(baseDataArea);
        List<String> filterNameList = baseDataArea.getFilterNameList();
        if(filterNameList == null || filterNameList.isEmpty()) {
            filterNameList = new ArrayList<>();
            filterNameList.add("无人机");
            filterNameList.add("机器人");
            filterNameList.add("安防摄像头");
            filterNameList.add("生活区域");
            filterNameList.add("新增相机");
        }
        return !areaList.isEmpty()
                ? AjaxResult.success(basedataDeviceService.buildAreaDeviceTreeSelectByAreasFilterByPresetRelationRight(areaList, filterNameList, baseDataArea))
                : AjaxResult.success(new JSONArray());
    }

    /**
     * 新的树形关系 （叶子节点无点位）用于页面展示（绍兴）
     * @param baseDataArea
     * @return
     */
    @GetMapping({"/treeAreaDeviceSelectFilterByPreset/relation"})
    public AjaxResult treeAreaDeviceSelectFilterByPresetRelation(BaseDataArea baseDataArea) {
        log.info("treeAreaDeviceSelectFilterByPreset param: {}", baseDataArea);
        List<BaseDataArea> areaList = baseDataAreaService.selectAreaRelationList(baseDataArea);
        List<String> filterNameList = baseDataArea.getFilterNameList();
        if(filterNameList == null || filterNameList.isEmpty()) {
            filterNameList = new ArrayList<>();
            filterNameList.add("无人机");
            filterNameList.add("机器人");
            filterNameList.add("安防摄像头");
            filterNameList.add("生活区域");
            filterNameList.add("新增相机");
        }
        return !areaList.isEmpty()
                ? AjaxResult.success(basedataDeviceService.buildAreaDeviceTreeSelectByAreasFilterByPresetRelation(areaList, filterNameList))
                : AjaxResult.success(new JSONArray());
    }


    @PostMapping({"/updateTreeAreaRelation"})
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateTreeAreaRelation (@RequestBody JSONObject jsonObject) {
        log.info("updateTreeAreaRelation param: {}", jsonObject);
        Long toAreaId = jsonObject.getLong("toAreaId");// 迁移到的区域
        Long toDeviceId = jsonObject.getLong("toDeviceId");// 迁移到的设备id/部件id

        String areaIdStr = jsonObject.getString("areaId");// 需要迁移的区域
        String deviceIdStr = jsonObject.getString("deviceId");// 需要迁移的设备id
        String patrolPointIdStr = jsonObject.getString("patrolPointId");// 需要迁移的点位id

        if (StringUtils.isNotEmpty(areaIdStr) && toAreaId != null) {
            // 区域迁移
            List<Long> areaIds = Arrays.stream(areaIdStr.split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            if (toDeviceId != null) {
                return AjaxResult.error("迁移失败，不支持区域迁移到设备部件");
            }
            // 1.查出要迁移到哪个区域下的area的信息
            BaseDataArea baseDataArea = baseDataAreaService.selectAreaRelationById(toAreaId);
            log.info("updateTreeAreaRelation baseDataArea: {}", baseDataArea);
            if (baseDataArea == null) {
                return AjaxResult.error("迁移失败，找不到目标区域");
            }
            // 2.update parent_id = 迁移到的area_id  and ancestors = 迁移到的ancestors+",迁移到的area_id" where area_id = fromAreaId
            String ancestors = baseDataArea.getAncestors();
            for (Long areaId : areaIds) {
                baseDataAreaService.updateAreaRelationById(areaId, toAreaId, ancestors);
            }
            log.info("----updateTreeAreaRelation成功迁移{}个区域", areaIds.size());
        }

        else if (StringUtils.isNotEmpty(deviceIdStr) && toAreaId != null) {
            if (toDeviceId != null) {
                return AjaxResult.error("迁移失败，只允许设备部件迁移到区域");
            }
            // 设备部件迁移
            List<Long> deviceIds = Arrays.stream(deviceIdStr.split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long deviceId : deviceIds) {
                // 更新设备及其部件区域
                basedataDeviceService.updateBasedataDeviceRelation(toAreaId, deviceId);
                // 更新设备及部件下点位所属区域
                basedataPatrolPointService.updateBasedataPatrolPointRelation(toAreaId, deviceId);
            }
        }

        else if (StringUtils.isNotEmpty(patrolPointIdStr) && toDeviceId != null) {
            if (toAreaId != null) {
                return AjaxResult.error("迁移失败，只允许点位迁移到设备部件");
            }
            //点位迁移
            List<Long> patrolPointIds = Arrays.stream(patrolPointIdStr.split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            // 查询迁移到哪个设备下的设备信息
            BasedataDevice basedataDevice = basedataDeviceService.selectBasedataDeviceRelationByDeviceId(toDeviceId);
            toAreaId = basedataDevice.getRelationAreaId();
            basedataDevice.setParentId(basedataDevice.getParentId() == 0 ? toDeviceId : basedataDevice.getParentId());
            Long toParentId = basedataDevice.getParentId();
            // 更新点位所属区域及设备id等信息
            basedataPatrolPointService.batchUpdateBasedataPatrolPointRelation(toAreaId, toParentId, toDeviceId, patrolPointIds);

        }
        return AjaxResult.success("迁移成功");
    }

    @GetMapping({"/treeAreaDeviceSelectFilterByMeter"})
    public AjaxResult treeAreaDeviceSelectFilterByMeter(BaseDataArea baseDataArea) {
        log.info("treeAreaDeviceSelectFilterByMeter param: {}", baseDataArea);
        List<BaseDataArea> areaList = baseDataAreaService.selectAreaList(baseDataArea);
        return !areaList.isEmpty()
                ? AjaxResult.success(basedataDeviceService.buildAreaDeviceTreeSelectByAreasFilterByMeter(areaList))
                : AjaxResult.success(new JSONArray());
    }

    @GetMapping({"/treeAreaDeviceSelectFilterByFault"})
    public AjaxResult treeAreaDeviceSelectFilterByFault(BaseDataArea baseDataArea) {
        log.info("treeAreaDeviceSelectFilterByFault param: {}", baseDataArea);
        List<BaseDataArea> areaList = baseDataAreaService.selectAreaList(baseDataArea);
        return !areaList.isEmpty()
                ? AjaxResult.success(basedataDeviceService.buildAreaDeviceTreeSelectByAreasFilterByFault(areaList))
                : AjaxResult.success(new JSONArray());
    }

    @GetMapping({"/treeProMainDevicePatrolEquSelect"})
    public AjaxResult treeProMainDevicePatrolEquSelect(BasedataDevice basedataDevice) {
        logger.info("[META] device: {}", basedataDevice);
        idToList(basedataDevice);
        paramsSetAreaIdToList(basedataDevice);
        if (null != basedataDevice.getAreaName()) {
            basedataDevice.setAreaName(null);
        }

        basedataDevice.setPowerMainEquFlag("Yes");
        List<BasedataDevice> mainDevices = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
        logger.info("[META] -----------------------------------mainDevices size: {}", mainDevices.size());
        return AjaxResult.success(this.basedataDeviceService.treeProMainDevicePatrolEquSelect(mainDevices));
    }

    @PostMapping({"/v2/treeProMainDevicePatrolEquSelect"})
    public AjaxResult treeProMainDevicePatrolEquSelectV2(@RequestBody BasedataDevice basedataDevice) {
        logger.info("[META] device: {}", basedataDevice);
        idToList(basedataDevice);
        paramsSetAreaIdToList(basedataDevice);
        if (null != basedataDevice.getAreaName()) {
            basedataDevice.setAreaName(null);
        }

        basedataDevice.setPowerMainEquFlag("Yes");
        List<BasedataDevice> mainDevices = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
        logger.info("[META] -----------------------------------mainDevices size: {}", mainDevices.size());
        return AjaxResult.success(this.basedataDeviceService.treeProMainDevicePatrolEquSelect(mainDevices));
    }

    @GetMapping({"/getMessageByDeviceId"})
    public AjaxResult getMessageByDeviceId() {
        BasedataDevice basedataDevice = new BasedataDevice();
        List<BasedataDevice> list = this.basedataDeviceService.selectBasedataDeviceList(basedataDevice);
        Iterator<BasedataDevice> iterator = list.iterator();
        label40:
        while (true) {
            BasedataDevice basedataDeviceList;
            AjaxResult ajaxResult;
            do {
                if (!iterator.hasNext()) {
                    return AjaxResult.success(list);
                }

                basedataDeviceList = iterator.next();
                ajaxResult = this.feignMsgClient.getMessageByDeviceId(String.valueOf(basedataDeviceList.getDeviceId()));
            } while (!"200".equals(ajaxResult.get("code")));

            List<PatrolTaskDomain> patrolTaskList = JSONObject.parseArray(JSON.toJSONString(ajaxResult.get("data")), PatrolTaskDomain.class);
            Iterator<PatrolTaskDomain> iterator1 = patrolTaskList.iterator();

            while (true) {
                PatrolTaskDomain patrolTaskDomain;
                List basedataEqpbookList;
                ArrayList basedataEqpbookMomainList;
                do {
                    if (!iterator1.hasNext()) {
                        basedataDeviceList.setPatrolTaskList(patrolTaskList);
                        continue label40;
                    }

                    patrolTaskDomain = iterator1.next();
                    BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
                    basedataEqpbook.setPatrolDeviceCode(patrolTaskDomain.getDevNo());
                    basedataEqpbookList = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
                    basedataEqpbookMomainList = new ArrayList<>();
                } while (basedataEqpbookList.isEmpty());

                for (Object object : basedataEqpbookList) {
                    BasedataEqpBook basedata = (BasedataEqpBook) object;
                    BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
                    BeanUtils.copyProperties(basedata, basedataEqpbookMomain);
                    basedataEqpbookMomainList.add(basedataEqpbookMomain);
                }

                patrolTaskDomain.setBasedataEqpbookList(basedataEqpbookMomainList);
            }
        }
    }

    @PostMapping({"/importData"})
    public AjaxResult importData(MultipartFile file) throws Exception {
        if (file == null) {
            throw new NullArgumentException();
        } else {
            String filename = file.getOriginalFilename();
            if (filename == null) {
                throw new NullArgumentException();
            } else {
                String a;

                try {
                    a = this.parseRowCell(filename, file.getInputStream());
                } catch (IOException var5) {
                    throw new Exception(var5.getMessage());
                }

                return AjaxResult.success("导入结果", a);
            }
        }
    }

    private String parseRowCell(String filename, InputStream is) throws Exception {
        try {
            Workbook workbook = null;
            if (filename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(is);
            }

            if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(is);
            }

            if (workbook == null) {
                throw new NullArgumentException();
            } else {
                Sheet sheet = workbook.getSheetAt(0);
                if (sheet == null) {
                    throw new NullArgumentException();
                } else {
                    for (int rowNum = 12; rowNum <= sheet.getLastRowNum(); ++rowNum) {
                        Row row = sheet.getRow(rowNum);
                        if (row != null) {
                            String deviceName = "";
                            if (row.getCell(0) != null) {
                                row.getCell(0).setCellType(CellType.STRING);
                                deviceName = row.getCell(0).getStringCellValue().trim();
                            }

                            String devicetypeName = "";
                            if (row.getCell(1) != null) {
                                row.getCell(1).setCellType(CellType.STRING);
                                devicetypeName = row.getCell(1).getStringCellValue().trim();
                            }

                            String areaName = "";
                            if (row.getCell(2) != null) {
                                row.getCell(2).setCellType(CellType.STRING);
                                areaName = row.getCell(2).getStringCellValue().trim();
                            }

                            String deviceCode = "";
                            if (row.getCell(3) != null) {
                                row.getCell(3).setCellType(CellType.STRING);
                                deviceCode = row.getCell(3).getStringCellValue().trim();
                            }

                            String stationNo = "";
                            if (row.getCell(4) != null) {
                                row.getCell(4).setCellType(CellType.STRING);
                                stationNo = row.getCell(4).getStringCellValue().trim();
                            }

                            String monitorIndexNo = "";
                            if (row.getCell(5) != null) {
                                row.getCell(5).setCellType(CellType.STRING);
                                monitorIndexNo = row.getCell(5).getStringCellValue().trim();
                            }

                            String deviceModel = "";
                            if (row.getCell(6) != null) {
                                row.getCell(6).setCellType(CellType.STRING);
                                deviceModel = row.getCell(6).getStringCellValue().trim();
                            }

                            String manufacturer = "";
                            if (row.getCell(7) != null) {
                                row.getCell(7).setCellType(CellType.STRING);
                                manufacturer = row.getCell(7).getStringCellValue().trim();
                            }

                            String intallPosition = "";
                            if (row.getCell(8) != null) {
                                row.getCell(8).setCellType(CellType.STRING);
                                intallPosition = row.getCell(8).getStringCellValue().trim();
                            }

                            if (StringUtils.isAllBlank(deviceName, devicetypeName)) {
                                throw new Exception("请检查必填项！");
                            }

                            Map deviceTypeId = this.getDeviceTypeIdByDeviceTypeName(devicetypeName);
                            String areaId = this.getAreaIdByAreaName(areaName);
                            BasedataDevice basedataDevice = new BasedataDevice();
                            basedataDevice.setDeviceName(deviceName);
                            basedataDevice.setDeviceTypeId(Long.valueOf(String.valueOf(deviceTypeId.get("devicetype_id"))));
                            basedataDevice.setDeviceTypeName(devicetypeName);
                            basedataDevice.setAreaName(areaName);
                            basedataDevice.setAreaId(Long.valueOf(areaId));
                            basedataDevice.setDeviceCode(deviceCode);
                            basedataDevice.setStationNo(stationNo);
                            basedataDevice.setMonitorIndexNo(monitorIndexNo);
                            basedataDevice.setDeviceModel(deviceModel);
                            basedataDevice.setManufacturer(manufacturer);
                            basedataDevice.setInstallPosition(intallPosition);
                            this.basedataDeviceService.insertMainDeviceAndCommByDeviceType(basedataDevice);
                        }
                    }

                    return "成功！";
                }
            }
        } catch (IOException e) {
            e.getMessage();
            return "失败！";
        }
    }

    public Map getDeviceTypeIdByDeviceTypeName(String deviceTypeName) {
        BasedataDeviceType basedataDevicetype = new BasedataDeviceType();
        basedataDevicetype.setDeviceTypeName(deviceTypeName);
        basedataDevicetype.setPowerMainEquFlag("Yes");
        return this.basedataDeviceTypeService.getDeviceTypeIdByDeviceTypeName(basedataDevicetype);
    }

    public String getAreaIdByAreaName(String areaName) {
        String areaId = "0";
        if (!"/".contains(areaName)) {
            areaId = "100";
            return areaId;
        } else {
            String[] str = areaName.split(StringUtils.SLASH);

            for (String s : str) {
                areaId = this.baseDataAreaService.selectAreaIdByName(s, areaId);
            }

            return areaId;
        }
    }

    @RequiresPermissions({"basedata/prodevmnt:device:add"})
    @Log(
            title = "生产设备",
            businessType = BizType.INSERT
    )
    @PostMapping({"/insertMainDeviceAndCommByDeviceType"})
    public AjaxResult insertMainDeviceAndCommByDeviceType(@RequestBody BasedataDevice basedataDevice) {
        if ("1".equals(this.basedataDeviceService.checkDeviceCodeUnique(basedataDevice))) {
            return AjaxResult.error("设备'" + basedataDevice.getDeviceCode() + "'编码已存在");
        } else if ("1".equals(this.basedataDeviceService.checkDeviceNameUnique(basedataDevice))) {
            return AjaxResult.error("设备'" + basedataDevice.getDeviceName() + "'名称已存在");
        } else {
            this.basedataDeviceService.insertMainDeviceAndCommByDeviceType(basedataDevice);
            return null != basedataDevice.getDeviceId() ? AjaxResult.success(basedataDevice) : AjaxResult.error("新增异常");
        }
    }

    @Log(
            title = "设备树查询",
            businessType = BizType.OTHER
    )
    @GetMapping({"/getProDeviceTreeSelect"})
    public AjaxResult getProDeviceTreeSelect(BasedataDevice basedataDevice) {
        this.idToList(basedataDevice);
        this.paramsSetAreaIdToList(basedataDevice);
        List<ProDeviceTreeSelectVO> list = this.basedataDeviceService.getProDeviceTreeSelect(basedataDevice);
        return AjaxResult.success(list);
    }

    @Log(
            title = "设备树查询v2",
            businessType = BizType.OTHER
    )
    @PostMapping({"/v2/getProDeviceTreeSelect"})
    public AjaxResult getProDeviceTreeSelectV2(@RequestBody BasedataDevice basedataDevice) {
        this.idToList(basedataDevice);
        this.paramsSetAreaIdToList(basedataDevice);
        List<ProDeviceTreeSelectVO> list = this.basedataDeviceService.getProDeviceTreeSelect(basedataDevice);
        return AjaxResult.success(list);
    }

    @Log(
            title = "生产设备全路径名称对应的id",
            businessType = BizType.OTHER
    )
    @GetMapping({"/getProDeviceAllPatchNameId"})
    public AjaxResult getProDeviceAllPatchNameId() {
        Map<String, Long> map = this.basedataDeviceService.getProDeviceAllPatchNameId();
        return AjaxResult.success(map);
    }

    public void idToList(BasedataDevice basedataDevice) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(basedataDevice.getDeviceIdAll())) {
            if (basedataDevice.getDeviceIdAll().contains(StringUtils.COMMA)) {
                String[] strs = basedataDevice.getDeviceIdAll().split(StringUtils.COMMA);

                for (String str : strs) {
                    if (StringUtils.isNotEmpty(str)) {
                        list.add(str);
                    }
                }
            } else {
                list.add(basedataDevice.getDeviceIdAll());
            }
        }

        if (!list.isEmpty()) {
            basedataDevice.setDeviceIdListAll(list);
        }

    }

    public void paramsSetAreaIdToList(BasedataDevice basedataDevice) {
        Map<String, Object> params = new HashMap<>();
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(basedataDevice.getAreaIdS())) {
            if (basedataDevice.getAreaIdS().contains(",")) {
                String[] strs = basedataDevice.getAreaIdS().split(StringUtils.COMMA);

                for (String str : strs) {
                    if (StringUtils.isNotEmpty(str)) {
                        list.add(str);
                    }
                }
            } else {
                list.add(basedataDevice.getAreaIdS());
            }
        }

        if (!list.isEmpty()) {
            params.put("areaIdList", list);
            basedataDevice.setParams(params);
        }

    }

    @GetMapping({"/treeProMainDevicePatrolEquSelectByEqookCode"})
    public AjaxResult treeProMainDevicePatrolEquSelectByEqBookCode(BasedataDevice basedataDevice) {
        if (StringUtils.isEmpty(basedataDevice.getDeviceIdAll())) {
            List<ProMainDevicePatrolEquTreeSelect> list = new ArrayList<>();
            return AjaxResult.success(list);
        } else {
            this.idToList(basedataDevice);
            List<BasedataDevice> mainDevices = this.basedataDeviceService.selectBasedataTreeByEqBookCode(basedataDevice);
            return AjaxResult.success(this.basedataDeviceService.treeProMainDevicePatrolEquSelect(mainDevices));
        }
    }

    @GetMapping({"/treeAreaDeviceSelectAgain"})
    public AjaxResult treeAreaDeviceSelectAgain(BaseDataArea area) {
        List<BaseDataArea> areas = this.baseDataAreaService.selectAreaList(area);
        List<TreeModule> arel = this.baseDataAreaService.buildAreaTreeAgain(areas);
        BasedataDevice basedataDevice = new BasedataDevice();
        basedataDevice.setPowerMainEquFlag("Yes");
        basedataDevice.setDeviceIdAll("0");
        List<TreeModule> treeModuleList = this.basedataDeviceService.selectAreaAndDeviceTree(basedataDevice);

        for (TreeModule arr : treeModuleList) {
            BasedataDevice basedataDevice1 = new BasedataDevice();
            basedataDevice1.setPowerMainEquFlag("No");
            basedataDevice1.setDeviceIdAll("1");
            basedataDevice1.setParentId(arr.getId());
            List<TreeModule> dev = this.basedataDeviceService.selectAreaAndDeviceTree(basedataDevice1);
            if (!dev.isEmpty()) {
                arr.setChildren(dev);
            }
        }

        List<TreeModule> point = this.basedataDeviceService.selectPointList();
        List<TreeModule> maindevlist = this.mergeDeptAndEquipment(treeModuleList, point, "0");
        return AjaxResult.success(this.mergeDeptAndEquipment(arel, maindevlist, "1"));
    }

    @GetMapping("/treeAreaDeviceSelectByLevel")
    public AjaxResult treeAreaDeviceSelectByLevel(@RequestParam(defaultValue = "0")int deviceLevel) {
        log.info("deviceLevel: {}", deviceLevel);
        List<BaseDataArea> areas = this.baseDataAreaService.selectAreaList(new BaseDataArea());
        log.info("areas: {}", areas);
        List<TreeModule> arel = this.baseDataAreaService.buildAreaTreeAgain(areas);
        log.info("arel: {}", arel);
        return AjaxResult.success(arel);
    }

    private List<TreeModule> mergeDeptAndEquipment(List<TreeModule> mainOrgList, List<TreeModule> pointOrgList, String type) {

        for (TreeModule equipmentOrg : pointOrgList) {
            this.setEquipmentInDept(mainOrgList, equipmentOrg, type);
        }

        return mainOrgList;
    }

    private void setEquipmentInDept(List<TreeModule> orgList, TreeModule eModel, String type) {
        if (orgList != null && !orgList.isEmpty()) {
            TreeModule org;
            for (Iterator<TreeModule> iterator = orgList.iterator(); iterator.hasNext(); this.setEquipmentInDept(org.getChildren(), eModel, type)) {
                org = iterator.next();
                if (type.equals("0")) {
                    if (eModel.getParentId() != null && org.getId() == eModel.getParentId() && (org.getType().equals("dev") || org.getType().equals("main"))) {
                        if (org.getChildren() == null) {
                            org.setChildren(new ArrayList<>());
                        }

                        org.getChildren().add(eModel);
                        return;
                    }
                } else if (org.getType().equals("area") && eModel.getParentId() != null && eModel.getParentId() == 0L && org.getId() == eModel.getAreaId()) {
                    if (org.getChildren() == null) {
                        org.setChildren(new ArrayList<>());
                    }

                    org.getChildren().add(eModel);
                    return;
                }
            }

        }
    }
}
