package com.xzzn.web.controller.ems;

import com.xzzn.common.annotation.Log;
import com.xzzn.common.config.RuoYiConfig;
import com.xzzn.common.core.controller.BaseController;
import com.xzzn.common.core.domain.AjaxResult;
import com.xzzn.common.core.page.TableDataInfo;
import com.xzzn.common.enums.BusinessType;
import com.xzzn.common.utils.file.FileUploadUtils;
import com.xzzn.common.utils.file.MimeTypeUtils;
import com.xzzn.common.utils.poi.ExcelUtil;
import com.xzzn.ems.domain.EmsSiteSetting;
import com.xzzn.ems.domain.vo.DeviceUpdateRequest;
import com.xzzn.ems.domain.vo.DevicesSettingVo;
import com.xzzn.ems.domain.vo.PointDataRequest;
import com.xzzn.ems.domain.vo.PointQueryResponse;
import com.xzzn.ems.domain.vo.SiteDeviceListVo;
import com.xzzn.ems.domain.vo.SiteMonitorProjectPointMappingSaveRequest;
import com.xzzn.ems.domain.vo.SingleBatteryConfigInitRequest;
import com.xzzn.ems.domain.vo.SingleBatteryConfigInitResultVo;
import com.xzzn.ems.domain.vo.SingleBatteryMonitorImportResultVo;
import com.xzzn.ems.domain.vo.SingleBatteryMonitorImportRowVo;
import com.xzzn.ems.domain.vo.WorkStatusEnumMappingSaveRequest;
import com.xzzn.ems.service.IEmsDeviceSettingService;
import com.xzzn.ems.service.IEmsSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 绔欑偣閰嶇疆
 */
@RestController
@RequestMapping("/ems/siteConfig")
public class EmsSiteConfigController extends BaseController {

    @Autowired
    private IEmsSiteService iEmsSiteService;

    @Autowired
    private IEmsDeviceSettingService iEmsDeviceSettingService;

    @GetMapping("/getSiteInfoList")
    public TableDataInfo getSiteInfoList(@RequestParam String siteName, @RequestParam String startTime, @RequestParam String endTime) {
        startPage();
        List<EmsSiteSetting> list = iEmsSiteService.getAllSiteInfoList(siteName, startTime, endTime);
        return getDataTable(list);
    }

    @PostMapping("/addSite")
    public AjaxResult addSite(@RequestBody EmsSiteSetting emsSiteSetting) {
        emsSiteSetting.setCreateBy(getUsername());
        return toAjax(iEmsSiteService.addSite(emsSiteSetting));
    }

    @PostMapping("/updateSite")
    public AjaxResult updateSite(@RequestBody EmsSiteSetting emsSiteSetting) {
        emsSiteSetting.setUpdateBy(getUsername());
        return toAjax(iEmsSiteService.updateSite(emsSiteSetting));
    }

    @GetMapping("/getDeviceInfoList")
    public TableDataInfo getDeviceInfoList(@RequestParam(value = "siteId", required = false) String siteId,
                                           @RequestParam(value = "deviceCategory", required = false) String deviceCategory) {
        startPage();
        List<SiteDeviceListVo> list = iEmsSiteService.getAllDeviceListNoDisp(siteId, deviceCategory);
        return getDataTable(list);
    }

    @GetMapping("/getDeviceDetailInfo")
    public AjaxResult getDeviceDetailInfo(@RequestParam Long id) {
        return success(iEmsDeviceSettingService.getDeviceDetailInfo(id));
    }

    @GetMapping("/getDeviceList")
    public AjaxResult getDeviceInfoList2(@RequestParam String siteId) {
        return success(iEmsSiteService.getAllDeviceList(siteId, null));
    }

    @GetMapping("/getDeviceCategory")
    public AjaxResult getDeviceCategory() {
        return success(iEmsDeviceSettingService.getDeviceCategory());
    }

    @PostMapping("/addDevice")
    public AjaxResult addDevice(@RequestBody DevicesSettingVo devicesSetting) {
        int result = iEmsDeviceSettingService.addDevice(devicesSetting);
        if (result > 0) {
            return AjaxResult.success(result);
        }
        return AjaxResult.error("璇ヨ澶囧凡瀛樺湪");
    }

    @PostMapping("/uploadDeviceImg")
    public AjaxResult uploadDeviceImg(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getDevicePath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            return ajax;
        }
        return error("涓婁紶鍥剧墖寮傚父锛岃鑱旂郴绠＄悊鍛?");
    }

    @PostMapping("/updateDevice")
    public AjaxResult updateDevice(@RequestBody DevicesSettingVo emsDevicesSetting) {
        int result = iEmsDeviceSettingService.updateDevice(emsDevicesSetting);
        if (result > 0) {
            return AjaxResult.success(result);
        } else if (result == -1) {
            return AjaxResult.error("鏁版嵁涓嶅瓨鍦?");
        } else if (result == -2) {
            return AjaxResult.error("璇ヨ澶囧凡瀛樺湪");
        }
        return AjaxResult.success(result);
    }

    @DeleteMapping("/deleteService/{id}")
    public AjaxResult deleteService(@PathVariable Long id) {
        return toAjax(iEmsDeviceSettingService.deleteEmsDevicesSettingById(id));
    }

    @GetMapping("/getDevicePointList")
    public TableDataInfo getDevicePointList(@Validated PointDataRequest request) {
        List<PointQueryResponse> result = iEmsDeviceSettingService.getSingleSiteDevicePoints(request);
        return getDataTable2(result);
    }

    @GetMapping("/getSiteAllDeviceCategory")
    public AjaxResult getSiteAllDeviceCategory(String siteId) {
        return success(iEmsDeviceSettingService.getSiteAllDeviceCategory(siteId));
    }

    @GetMapping("/getParentDeviceId")
    public AjaxResult getParentDeviceId(@RequestParam String siteId, @RequestParam String deviceCategory) {
        return success(iEmsSiteService.getParentCategoryDeviceId(siteId, deviceCategory));
    }

    @GetMapping("/getDeviceListBySiteAndCategory")
    public AjaxResult getDeviceListBySiteAndCategory(String siteId, String deviceCategory) {
        return success(iEmsDeviceSettingService.getDeviceListBySiteAndCategory(siteId, deviceCategory));
    }

    @GetMapping("/getSingleMonitorProjectPointMapping")
    public AjaxResult getSingleMonitorProjectPointMapping(@RequestParam String siteId) {
        return success(iEmsDeviceSettingService.getSiteMonitorProjectPointMapping(siteId));
    }

    @PostMapping("/saveSingleMonitorProjectPointMapping")
    public AjaxResult saveSingleMonitorProjectPointMapping(@RequestBody SiteMonitorProjectPointMappingSaveRequest request) {
        int rows = iEmsDeviceSettingService.saveSiteMonitorProjectPointMapping(request, getUsername());
        return AjaxResult.success(rows);
    }

    @GetMapping("/getSingleMonitorWorkStatusEnumMappings")
    public AjaxResult getSingleMonitorWorkStatusEnumMappings(@RequestParam String siteId) {
        return success(iEmsDeviceSettingService.getSiteWorkStatusEnumMappings(siteId));
    }

    @PostMapping("/saveSingleMonitorWorkStatusEnumMappings")
    public AjaxResult saveSingleMonitorWorkStatusEnumMappings(@RequestBody WorkStatusEnumMappingSaveRequest request) {
        int rows = iEmsDeviceSettingService.saveSiteWorkStatusEnumMappings(request.getSiteId(), request.getMappings(), getUsername());
        return AjaxResult.success(rows);
    }

    @GetMapping("/downloadSingleBatteryMonitorImportTemplate")
    public void downloadSingleBatteryMonitorImportTemplate(HttpServletResponse response) {
        ExcelUtil<SingleBatteryMonitorImportRowVo> util = new ExcelUtil<>(SingleBatteryMonitorImportRowVo.class);
        util.importTemplateExcel(response, "单体电池导入模板", "单体电池导入模板");
    }

    @PostMapping("/importSingleBatteryMonitorMappings")
    public AjaxResult importSingleBatteryMonitorMappings(@RequestParam("siteId") String siteId,
                                                         @RequestParam("file") MultipartFile file) throws Exception {
        ExcelUtil<SingleBatteryMonitorImportRowVo> util = new ExcelUtil<>(SingleBatteryMonitorImportRowVo.class);
        List<SingleBatteryMonitorImportRowVo> rowList = util.importExcel(file.getInputStream(), 1);
        if (rowList == null) {
            return AjaxResult.error("导入失败：未读取到任何数据，请检查 Excel 文件内容");
        }
        List<SingleBatteryMonitorImportRowVo> validRowList = new ArrayList<>();
        for (int i = 0; i < rowList.size(); i++) {
            SingleBatteryMonitorImportRowVo row = rowList.get(i);
            if (row == null) {
                continue;
            }
            row.setRowNum(i + 3);
            validRowList.add(row);
        }
        if (validRowList.isEmpty()) {
            return AjaxResult.error("导入失败：未识别到有效数据，请使用系统导出的最新模板，并保持表头名称不变");
        }
        SingleBatteryMonitorImportResultVo result = iEmsDeviceSettingService.importSingleBatteryMonitorMappings(siteId, validRowList, getUsername());
        return AjaxResult.success(result);
    }

    @PostMapping("/initializeSingleBatteryMonitorMappings")
    public AjaxResult initializeSingleBatteryMonitorMappings(@RequestBody SingleBatteryConfigInitRequest request) {
        SingleBatteryConfigInitResultVo result = iEmsDeviceSettingService.initializeSingleBatteryMonitorMappings(request, getUsername());
        return AjaxResult.success(result);
    }

//    @PreAuthorize("@ss.hasPermi('system:device:onAndOff')")
    @Log(title = "寮€鍏虫満", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDeviceStatus")
    public AjaxResult updateDeviceStatus(@Valid @RequestBody DeviceUpdateRequest request) {
        return success(iEmsDeviceSettingService.updateDeviceStatus(request));
    }
}
