package com.inspect.maintain.controller;

import com.alibaba.fastjson.JSONObject;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.domain.DataMsg;
import com.inspect.base.core.service.SyncDataToUpstreamService;
import com.inspect.base.core.utils.SFTPUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.utils.xml.GenXmlByBean;
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.base.core.domain.maintain.MaintainRegion;
import com.inspect.maintain.domain.MaintainAreaXML;
import com.inspect.maintain.domain.PatrolMaintainModuleXml;
import com.inspect.maintain.service.IMaintainRegionService;
import com.inspect.partrolresult.controller.PatrolResultController;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;
import com.inspect.task.domain.PatrolSendTask;
import com.inspect.task.domain.SendTask;
import com.inspect.taskftp.domain.PatrolTaskFtp;
import com.inspect.taskftp.service.IPatrolTaskFtpService;
import com.inspect.taskstatus.client.FeignTaskClient;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/maintarea"})
public class MaintainRegionController extends BaseController {
    @Resource
    private IMaintainRegionService maintainRegionService;
    @Resource
    private IPatrolResultService patrolResultService;
    @Resource
    private FeignTaskClient feignTaskClient;
    @Resource
    private IResultAnalysisService iResultAnalysisService;
    @Resource
    private IPatrolTaskFtpService patrolTaskFtpService;
    @Resource
    private SyncDataToUpstreamService syncDataToUpstreamService;

    @GetMapping({"/list"})
    public TableDataInfo list(MaintainRegion maintainRegion) {
        List<String> points = new ArrayList<>();
        startPage();
        List<MaintainRegion> list = maintainRegionService.selectMaintainRegionList(maintainRegion);
        MaintainRegion region;
        for (Iterator<MaintainRegion> iterator = list.iterator(); iterator.hasNext(); region.setPointName(String.join(StringUtils.COMMA, points))) {
            region = iterator.next();
            if (StringUtils.isNotEmpty(region.getPointList())) {
                String[] pointListArrays = region.getPointList().split(StringUtils.COMMA);
                for (String pointList : pointListArrays) {
                    Map<String, String> map = iResultAnalysisService.selectPointInfoById(pointList);
                    if (map != null && map.get("patrol_point_name") != null) {
                        points.add(map.get("patrol_point_name"));
                    }
                }
            }
        }

        return getDataTable(list);
    }

    @Log(
            title = "检修区域",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, MaintainRegion maintainRegion) {
        List<MaintainRegion> list = maintainRegionService.selectMaintainRegionList(maintainRegion);
        ExcelUtil<MaintainRegion> util = new ExcelUtil<>(MaintainRegion.class);
        util.exportExcel(response, list, "检修区域数据");
    }

    @GetMapping({"/{lineId}"})
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        return AjaxResult.success(maintainRegionService.selectMaintainRegionByLineId(lineId));
    }

    @Log(
            title = "检修区域",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody MaintainRegion maintainRegion) {
        if (StringUtils.isEmpty(maintainRegion.getEnable())) {
            maintainRegion.setEnable("1");
        }

        maintainRegionService.insertMaintainRegion(maintainRegion);
        (new Thread(() -> {
            logger.info("[MAINTAIN] add maintain area to upper start");
            try {
                Thread.sleep(2000L);
                syncMaintainRegionToUpperSystem(new MaintainRegion());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("[MAINTAIN] add maintain area  to upper end");
        })).start();
        return toAjax(1);
    }

    @Log(
            title = "检修区域",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody MaintainRegion maintainRegion) {
        maintainRegionService.updateMaintainRegion(maintainRegion);
        (new Thread(() -> {
            logger.info("[MAINTAIN] edit maintain area to upper start");
            try {
                Thread.sleep(2000L);
                syncMaintainRegionToUpperSystem(new MaintainRegion());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            logger.info("[MAINTAIN] edit maintain area to upper end");
        })).start();
        return toAjax(1);
    }

    @Log(
            title = "检修区域",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return toAjax(maintainRegionService.deleteMaintainRegionByLineIds(lineIds));
    }

    @PostMapping({"/add"})
    @ResponseBody
    public AjaxResult add(@RequestBody String message) {
        logger.info("[MAINTAIN] add2 message: {}", message);
        JSONObject parseObject = JSONObject.parseObject(message);
        List<MaintainRegion> eqList = toList(parseObject);
        if (!eqList.isEmpty()) {
            for (MaintainRegion arr : eqList) {
                maintainRegionService.insertMaintainRegion(arr);
                issueTaskSJ(arr);
            }
        }

        (new Thread(() -> {
            logger.info("[MAINTAIN] add2 maintain area to upper start");
            try {
                Thread.sleep(2000L);
                syncMaintainRegionToUpperSystem(new MaintainRegion());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            logger.info("[MAINTAIN] add2 maintain area to upper end");
        })).start();
        return toAjax(1);
    }

    public List<MaintainRegion> toList(JSONObject str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MaintainRegion> list = new ArrayList<>();
        MaintainRegion patrolTask = new MaintainRegion();

        try {
            if (str.get("enable") != null) {
                String coordinatePixel = str.get("enable").toString();
                if (StringUtils.isNotEmpty(coordinatePixel)) {
                    patrolTask.setEnable(coordinatePixel);
                }
            }

            if (str.get("start_time") != null) {
                String startTime = str.get("start_time").toString();
                if (StringUtils.isNotEmpty(startTime)) {
                    patrolTask.setStartTime(sdf.parse(startTime));
                }
            }

            if (str.get("config_code") != null) {
                String configCode = str.get("config_code").toString();
                if (StringUtils.isNotEmpty(configCode)) {
                    patrolTask.setConfigCode(configCode);
                }
            }

            if (str.get("end_time") != null) {
                String endTime = str.get("end_time").toString();
                if (StringUtils.isNotEmpty(endTime)) {
                    patrolTask.setEndTime(sdf.parse(endTime));
                }
            }

            if (str.get("device_level") != null) {
                String deviceLevel = str.get("device_level").toString();
                if (StringUtils.isNotEmpty(deviceLevel)) {
                    patrolTask.setDeviceLevel(deviceLevel);
                }
            }

            if (str.get("device_list") != null) {
                String deviceList = str.get("device_list").toString();
                if (StringUtils.isNotEmpty(deviceList) && deviceList.contains(StringUtils.UNDERLINE)) {
                    patrolTask.setDeviceList(deviceList.split(StringUtils.UNDERLINE)[1]);
                }
            }

            if (str.get("coordinate_pixel") != null) {
                String coordinatePixel = str.get("coordinate_pixel").toString();
                if (StringUtils.isNotEmpty(coordinatePixel)) {
                    patrolTask.setCoordinatePixel(coordinatePixel);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        list.add(patrolTask);
        return list;
    }

    @GetMapping({"/update"})
    public AjaxResult update(MaintainRegion maintainRegion) {
        maintainRegionService.updateMaintainRegion(maintainRegion);
        (new Thread(() -> {
            logger.info("[MAINTAIN] update maintain area to upper start");
            try {
                Thread.sleep(2000L);
                syncMaintainRegionToUpperSystem(new MaintainRegion());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            logger.info("[MAINTAIN] update maintain area to upper end");
        })).start();
        return toAjax(1);
    }

    /**
     * 下发指令同步检修区域至设备
     * @param maintainRegion
     * @return
     */
    @GetMapping({"/issue"})
    public AjaxResult issueList(MaintainRegion maintainRegion) {
        if (StringUtils.isNotEmpty(maintainRegion.getIds())) {
            String[] ids = maintainRegion.getIds().split(StringUtils.COMMA);
            for (String id : ids) {
                MaintainRegion region = maintainRegionService.selectMaintainRegionByLineId(Long.valueOf(id));
                issueTask(region);
            }
        }

        return toAjax(1);
    }

    public void issueTaskSJ(MaintainRegion maintainRegion) {
        Map<String, String> stringStringMap = patrolResultService.selectBasedataStation();
        String receiveCode = "";
        String sendCode = "";
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = patrolResultService.selectBasedataEqpBookList(based);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }

        Set<String> droneCode = new HashSet<>();
        List<BasedataEqpBookMoMain> eqpBookList = patrolResultService.selectBasedataEqpBookList(new BasedataEqpBookMoMain());
        Iterator iterator = eqpBookList.iterator();
        while (true) {
            String eqpBookString;
            do {
                if (!iterator.hasNext()) {
                    if (!droneCode.isEmpty()) {
                        iterator = droneCode.iterator();

                        while (iterator.hasNext()) {
                            eqpBookString = (String) iterator.next();
                            SendTask sendTask = new SendTask();
                            sendTask.setSendCode(sendCode);
                            sendTask.setReceiveCode(eqpBookString);
                            sendTask.setType("81");
                            sendTask.setCommand("4");
                            if (stringStringMap != null && stringStringMap.get("station_no") != null) {
                                sendTask.setCode(stringStringMap.get("station_no"));
                            }

                            List<PatrolSendTask> list = new ArrayList<>();
                            PatrolSendTask PatrolSendTask = new PatrolSendTask();
                            if (StringUtils.isNotEmpty(maintainRegion.getConfigCode())) {
                                PatrolSendTask.setConfigCode(maintainRegion.getConfigCode());
                            } else {
                                PatrolSendTask.setConfigCode("");
                            }

                            if (StringUtils.isNotEmpty(maintainRegion.getEnable())) {
                                PatrolSendTask.setEnable(maintainRegion.getEnable());
                            } else {
                                PatrolSendTask.setEnable("");
                            }

                            if (StringUtils.isNotEmpty(maintainRegion.getDeviceList())) {
                                PatrolSendTask.setDeviceList(maintainRegion.getDeviceList());
                            } else {
                                PatrolSendTask.setDeviceList("");
                            }

                            if (maintainRegion.getStartTime() != null) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                PatrolSendTask.setStartTime(sdf.format(maintainRegion.getStartTime()));
                            } else {
                                PatrolSendTask.setStartTime("");
                            }

                            if (maintainRegion.getEndTime() != null) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                PatrolSendTask.setEndTime(sdf.format(maintainRegion.getEndTime()));
                            } else {
                                PatrolSendTask.setEndTime("");
                            }

                            if (maintainRegion.getDeviceLevel() == null) {
                                PatrolSendTask.setDeviceLevel("");
                            } else {
                                Set<String> devLevelSet = new HashSet<>();
                                String[] deviceLevelList = maintainRegion.getDeviceLevel().split(StringUtils.COMMA);
                                for (String deviceLevel : deviceLevelList) {
                                    if (StringUtils.isNotEmpty(deviceLevel)) {
                                        if (deviceLevel.equals("area")) {
                                            devLevelSet.add("1");
                                        } else if (deviceLevel.equals("main")) {
                                            devLevelSet.add("2");
                                        } else if (deviceLevel.equals("point")) {
                                            devLevelSet.add("3");
                                        } else if (deviceLevel.equals("dev")) {
                                            devLevelSet.add("4");
                                        } else {
                                            devLevelSet.add(deviceLevel);
                                        }
                                        break;
                                    }
                                }

                                PatrolSendTask.setDeviceLevel(String.join(StringUtils.COMMA, devLevelSet));
                            }

                            if (StringUtils.isNotEmpty(maintainRegion.getCoordinatePixel())) {
                                PatrolSendTask.setCoordinatePixel(maintainRegion.getCoordinatePixel());
                            } else {
                                PatrolSendTask.setCoordinatePixel("");
                            }

                            list.add(PatrolSendTask);
                            sendTask.setItems(list);
                            String jsonString = JSONObject.toJSONString(sendTask);
                            System.out.println(jsonString);
                            feignTaskClient.sendCommand(jsonString);
                        }
                    }

                    return;
                }

                eqpBookString = (String) iterator.next();
            } while (!eqpBookString.equals("1") && !eqpBookString.equals("2") && !eqpBookString.equals("3") && !eqpBookString.equals("13"));

            if (StringUtils.isNotEmpty(eqpBookString)) {
                droneCode.add(eqpBookString);
            }
        }
    }

    public void issueTask(MaintainRegion maintainRegion) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> stationMap = patrolResultService.selectBasedataStation();
        String receiveCode = "";
        String sendCode = "";
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> eqpBookList = patrolResultService.selectBasedataEqpBookList(based);
        if (!eqpBookList.isEmpty()) {
            sendCode = eqpBookList.get(0).getPatrolDeviceCode();
        }

        Set<String> droneCode = new HashSet<>();
        List<BasedataEqpBookMoMain> eqpBookListEx = patrolResultService.selectBasedataEqpBookList(new BasedataEqpBookMoMain());
        Iterator iterator = eqpBookListEx.iterator();

        while (true) {
            String eqpBookString;
            do {
                if (!iterator.hasNext()) {
                    if (!droneCode.isEmpty()) {
                        iterator = droneCode.iterator();

                        while (iterator.hasNext()) {
                            eqpBookString = (String) iterator.next();
                            SendTask sendTask = new SendTask();
                            sendTask.setSendCode(sendCode);
                            sendTask.setReceiveCode(eqpBookString);
                            sendTask.setType("81");
                            sendTask.setCommand("4");
                            if (stationMap != null && stationMap.get("station_no") != null) {
                                sendTask.setCode(stationMap.get("station_no"));
                            }

                            List<PatrolSendTask> list = new ArrayList<>();
                            PatrolSendTask PatrolSendTask = new PatrolSendTask();
                            if (StringUtils.isNotEmpty(maintainRegion.getConfigCode())) {
                                PatrolSendTask.setConfigCode(maintainRegion.getConfigCode());
                            } else {
                                PatrolSendTask.setConfigCode("");
                            }

                            if (StringUtils.isNotEmpty(maintainRegion.getEnable())) {
                                PatrolSendTask.setEnable(maintainRegion.getEnable());
                            } else {
                                PatrolSendTask.setEnable("");
                            }

                            String[] deviceListStringArray;
                            int i;
                            if (!StringUtils.isNotEmpty(maintainRegion.getDeviceList())) {
                                PatrolSendTask.setDeviceList("");
                            } else {
                                List<String> asdlist = new ArrayList<>();
                                deviceListStringArray = maintainRegion.getDeviceList().split(StringUtils.COMMA);
                                Map map;
                                if (!maintainRegion.getDeviceLevel().contains("dev") && !maintainRegion.getDeviceLevel().contains("main")) {
                                    if (maintainRegion.getDeviceLevel().contains("point")) {
                                        for (i = 0; i < deviceListStringArray.length; ++i) {
                                            map = iResultAnalysisService.selectPointInfoById(deviceListStringArray[i]);
                                            if (map != null && map.get("patrol_point_code") != null) {
                                                asdlist.add((String) map.get("patrol_point_code"));
                                            }
                                        }
                                    } else if (maintainRegion.getDeviceLevel().contains("area")) {
                                        for (i = 0; i < deviceListStringArray.length; ++i) {
                                            map = patrolResultService.selectAreaInfo(deviceListStringArray[i]);
                                            if (map != null && map.get("area_code") != null) {
                                                asdlist.add(map.get("area_code") + "");
                                            }
                                        }
                                    }
                                } else {
                                    for (i = 0; i < deviceListStringArray.length; ++i) {
                                        map = patrolResultService.selectDevInfoById(deviceListStringArray[i]);
                                        if (map != null && StringUtils.isNotEmpty(map.get("device_code") + "")) {
                                            asdlist.add(map.get("device_code") + "");
                                        }
                                    }
                                }

                                PatrolSendTask.setDeviceList(String.join(StringUtils.COMMA, asdlist));
                                if (PatrolSendTask.getDeviceList().contains(StringUtils.UNDERLINE)) {
                                    PatrolSendTask.setDeviceList(PatrolSendTask.getDeviceList().split(StringUtils.UNDERLINE)[1]);
                                }
                            }

                            if (maintainRegion.getStartTime() != null) {
                                PatrolSendTask.setStartTime(sdf.format(maintainRegion.getStartTime()));
                            } else {
                                PatrolSendTask.setStartTime("");
                            }

                            if (maintainRegion.getEndTime() != null) {
                                PatrolSendTask.setEndTime(sdf.format(maintainRegion.getEndTime()));
                            } else {
                                PatrolSendTask.setEndTime("");
                            }

                            if (maintainRegion.getDeviceLevel() == null) {
                                PatrolSendTask.setDeviceLevel("");
                            } else {
                                Set<String> devLevelSet = new HashSet<>();
                                deviceListStringArray = maintainRegion.getDeviceLevel().split(StringUtils.COMMA);
                                if (deviceListStringArray.length > 0) {
                                    for (i = 0; i < deviceListStringArray.length; ++i) {
                                        if (StringUtils.isNotEmpty(deviceListStringArray[i])) {
                                            if (deviceListStringArray[i].equals("area")) {
                                                devLevelSet.add("1");
                                            } else if (deviceListStringArray[i].equals("main")) {
                                                devLevelSet.add("2");
                                            } else if (deviceListStringArray[i].equals("point")) {
                                                devLevelSet.add("3");
                                            } else if (deviceListStringArray[i].equals("dev")) {
                                                devLevelSet.add("4");
                                            } else {
                                                devLevelSet.add(deviceListStringArray[i]);
                                            }
                                            break;
                                        }
                                    }
                                }

                                PatrolSendTask.setDeviceLevel(String.join(StringUtils.COMMA, devLevelSet));
                            }

                            if (StringUtils.isNotEmpty(maintainRegion.getCoordinatePixel())) {
                                PatrolSendTask.setCoordinatePixel(maintainRegion.getCoordinatePixel());
                            } else {
                                PatrolSendTask.setCoordinatePixel("");
                            }

                            list.add(PatrolSendTask);
                            sendTask.setItems(list);
                            String str = JSONObject.toJSONString(sendTask);
                            System.out.println(str);
                            feignTaskClient.sendCommand(str);
                        }
                    }

                    return;
                }

                eqpBookString = (String) iterator.next();
            } while (!eqpBookString.equals("1") && !eqpBookString.equals("2") && !eqpBookString.equals("3") && !eqpBookString.equals("13"));

            if (StringUtils.isNotEmpty(eqpBookString)) {
                droneCode.add(eqpBookString);
            }
        }
    }

    public void syncMaintainRegionToUpperSystem(MaintainRegion maintainRegion) {
        logger.info("[MAINTAIN] SYNC maintain region to upper system");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sendCode = "";
        String receiveCode = "";
        Map<String, String> stationMap = patrolResultService.selectBasedataStation();
        String stationNo = stationMap.get("station_no");
        String stationName = stationMap.get("station_name");
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> eqpBookList = patrolResultService.selectBasedataEqpBookList(based);
        if (!eqpBookList.isEmpty()) {
            sendCode = eqpBookList.get(0).getPatrolDeviceCode();
        }

        PatrolTaskFtp patrolTaskFtp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(3L);
        String filepath = "";
        String filename = "";
        String modelXml = null;
        String conType = "";
        List<MaintainRegion> maintainRegionList = maintainRegionService.selectMaintainRegionList(maintainRegion);
        ArrayList items;
        if (null != maintainRegionList && !maintainRegionList.isEmpty()) {
            items = new ArrayList<>();

            MaintainAreaXML up;
            for (Iterator<MaintainRegion> iterator = maintainRegionList.iterator(); iterator.hasNext(); items.add(up)) {
                MaintainRegion book = iterator.next();
                up = new MaintainAreaXML();
                BeanUtils.copyBeanProp(up, book);
                PatrolResultController.noNullStringAttr(up);
                up.setStationCode(stationNo);
                up.setStationName(stationName);
                if (book.getStartTime() != null) {
                    up.setStartTime(sdf.format(book.getStartTime()));
                }

                if (book.getEndTime() != null) {
                    up.setEndTime(sdf.format(book.getEndTime()));
                }
            }

            GenXmlByBean<PatrolMaintainModuleXml> pulseGet = new GenXmlByBean<>();
            PatrolMaintainModuleXml pd = new PatrolMaintainModuleXml();
            pd.setItem(items);
            modelXml = pulseGet.getXml(pd);
        } else {
            items = new ArrayList<>();
            MaintainAreaXML MaintainAreaXML = new MaintainAreaXML();
            items.add(MaintainAreaXML);
            GenXmlByBean pulseGet = new GenXmlByBean<>();
            PatrolMaintainModuleXml pd = new PatrolMaintainModuleXml();
            pd.setItem(items);
            modelXml = pulseGet.getXml(pd);
        }

        InputStream in_nocode = new ByteArrayInputStream(modelXml.getBytes());
        String algorithmBaseImagePath = "";
        filename = "maintain_area_" + System.currentTimeMillis();
        algorithmBaseImagePath = stationNo + "/Model/";
        DataMsg DataMsg = new DataMsg();
        DataMsg.setIp(patrolTaskFtp.getFtpIp());
        DataMsg.setPort(patrolTaskFtp.getFtpPort());
        DataMsg.setUsername(patrolTaskFtp.getFtpUserName());
        DataMsg.setPassword(patrolTaskFtp.getFtpPwd());
        DataMsg.setBasePath(patrolTaskFtp.getFtpPath());
        DataMsg.setType("0");
        DataMsg.setFilePath(algorithmBaseImagePath);
        DataMsg.setFileName(filename + ".xml");
        DataMsg.setInputStream(in_nocode);
        DataMsg.setIsImplicit("true");
        SFTPUtil.uploadFileForXml(DataMsg);
        SendTask sendTask = new SendTask();
        sendTask.setReceiveCode("");
        sendTask.setSendCode(sendCode);
        sendTask.setCode(stationMap.get("station_no"));
        sendTask.setType("11");
        List<PatrolSendTask> taskLis = new ArrayList<>();
        PatrolSendTask patrolSendTask = new PatrolSendTask();
        patrolSendTask.setTime(sdf.format(new Date()));
        patrolSendTask.setType("8");
        patrolSendTask.setFilePath(algorithmBaseImagePath + filename + ".xml");
        taskLis.add(patrolSendTask);
        sendTask.setItems(taskLis);
        String jsonString = JSONObject.toJSONString(sendTask);
        logger.info("[MAINTAIN] SYNC maintain region to upper system jsonString: {}", jsonString);
        syncDataToUpstreamService.postMessage(jsonString);
    }

    @PostMapping("/save")
    public AjaxResult save(@RequestBody MaintainRegion maintainRegion) {
        if (!maintainRegionService.checkConfigCodeUnique(maintainRegion.getConfigCode())) {
            return error("新增检修区域'" + maintainRegion.getConfigCode() + "'失败，检修区域编码已存在");
        }

        if (StringUtils.isEmpty(maintainRegion.getEnable())) {
            maintainRegion.setEnable("1");
        }

        if (StringUtils.isEmpty(maintainRegion.getDeviceLevel())) {
            maintainRegion.setDeviceLevel("0");
        }

        return toAjax(maintainRegionService.insertMaintainRegionWithConfigCode(maintainRegion));
    }
}
