package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.BasDevice;
import cn.cecep.talroad.domain.BasDeviceInfoOperationLog;
import cn.cecep.talroad.service.FacilityInformationManagementService;
import cn.cecep.talroad.system.api.domain.SysUser;
import cn.cecep.talroad.system.api.model.LoginUser;
import cn.cecep.talroad.vo.FacilityInformationManagementDCSVO;
import cn.cecep.talroad.vo.FacilityInformationManagementVO;
import cn.cecep.talroad.vo.query.FacilityInformationQuery;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: FacilityInformationManagement
 * @description: 设施信息管理
 * @author: Mr.Yanghongtao
 * @date: 2023/04/28 10:32
 * @Company: Copyright© [2023/04/28 10:32] by [Mr.Yanghongtao]
 **/
@RestController
@RequestMapping("facilityInformationManagement")
@Slf4j
@Api(description = "设施信息管理Controller", tags = "设施信息管理Controller")
public class FacilityInformationManagementController {

    @Autowired
    private FacilityInformationManagementService facilityInformationManagementServiceImpl;


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 10:32 AM
     * @Deseription: 分表计电生产设施匹配列表
     * @Params: deviceName 分表计电生产设施的名称
     * @Params: pollutantName 排污生产设施名称
     * @Params: pollutantCode 排污生产设施编号（bas_device表的id）
     * @Return: cn.cecep.talroad.common.core.web.domain.AjaxResults
     * @Throws:
     */
    @ApiOperation(value = "设施匹配列表")
    @PostMapping("/getProductionDeviceList")
    public AjaxResults<IPage<FacilityInformationManagementVO>> getProductionDeviceList(@RequestBody FacilityInformationQuery dto) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResults.error("用户Token失效，请重新登录！");
            }
            Long roleId = loginUser.getSysUser().getRoles().get(0).getRoleId();
            if(ObjectUtil.equal(roleId,10L)) {
                dto.setFactoryId(loginUser.getSysUser().getFactoryId());
            }
            IPage<FacilityInformationManagementVO> list = facilityInformationManagementServiceImpl.getProductionDeviceList(dto);
            return AjaxResults.success(list);
        } catch (Exception e) {
            log.error("设施匹配列表获取失败!,异常：{}", e);
            return AjaxResults.error("分表计电生产设施匹配列表获取失败！");
        }
    }

    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 10:32 AM
     * @Deseription: 分表计电生产设施匹配列表
     * @Return: cn.cecep.talroad.common.core.web.domain.AjaxResults
     * @Throws:
     */
    @ApiOperation(value = "设施匹配搜索列表")
    @GetMapping("/getProductionDeviceSearchList")
    @ApiImplicitParam(name = "queryType", value = "查询类型：1-分表计电生产设施匹配列表查询，2-分表计电治理设施匹配列表查询，3-DCS生产设施匹配列表查询", required = true, paramType = "query", dataType = "Integer")
    public AjaxResults<List<FacilityInformationManagementVO>> getProductionDeviceSearchList(
            @RequestParam(name = "queryType") String queryType,
            @RequestParam(value = "factoryId", required = false) String factoryId
    ) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResults.error("用户Token失效，请重新登录！");
            }
            Long roleId = loginUser.getSysUser().getRoles().get(0).getRoleId();
            if(ObjectUtil.equal(roleId,10L)) {
                factoryId = loginUser.getSysUser().getFactoryId();
            }
            List<FacilityInformationManagementVO> list = facilityInformationManagementServiceImpl.getProductionDeviceSearchList(factoryId, queryType);
            return AjaxResults.success(list);
        } catch (Exception e) {
            log.error("设施匹配列表获取失败!,异常：{}", e);
            return AjaxResults.error("分表计电生产设施匹配列表获取失败！");
        }
    }


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 13:23
     * @Deseription: 保存
     * @Params: dto
     * @Params: type 1-分表计电生产设施匹配｜2-分表计电治理设施匹配｜3-DCS生产设施点位匹配
     * @Return: cn.cecep.talroad.common.core.web.domain.AjaxResults
     * @Throws:
     */
    @ApiOperation(value = "设施匹配列表保存")
    @PostMapping("/modifyDeviceAndPollutantCodeList/{type}")
    public AjaxResults modifyDeviceAndPollutantCodeList(@RequestBody List<FacilityInformationQuery> dto, @PathVariable String type) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResults.error("用户Token失效，请重新登录！");
            }
            SysUser sysUser = loginUser.getSysUser();
            facilityInformationManagementServiceImpl.modifyDeviceAndPollutantCodeList(sysUser, dto, type);
        } catch (Exception e) {
            log.error("设备信息管理-设施匹配列表保存失败!,异常：{}", e);
            return AjaxResults.error("保存失败！");
        }
        return AjaxResults.success();
    }


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 10:32 AM
     * @Deseription: 排污许可设施列表
     * @Params: deviceType 排污许可设施类型，0-生产，1-治理
     * @Return: cn.cecep.talroad.common.core.web.domain.AjaxResults
     * @Throws:
     */
    @ApiOperation(value = "排污许可设施列表")
    @ApiImplicitParam(name = "deviceType", value = "排污许可设施类型，0-生产，1-治理", required = true, paramType = "query", dataType = "Integer")
    @GetMapping("/getPollutantDeviceList")
    public AjaxResults<List<BasDevice>> getPollutantDeviceList(@RequestParam(name = "deviceType") Integer deviceType,@RequestParam(value = "factoryId", required = false) String factoryId) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResults.error("用户Token失效，请重新登录！");
            }
            Long roleId = loginUser.getSysUser().getRoles().get(0).getRoleId();
            if(ObjectUtil.equal(roleId,10L)) {
                factoryId = loginUser.getSysUser().getFactoryId();
            }
            List<BasDevice> list = facilityInformationManagementServiceImpl.getPollutantDeviceList(factoryId, deviceType);
            return AjaxResults.success(list);
        } catch (Exception e) {
            log.error("排污许可设施列表获取失败!,异常：{}", e);
            return AjaxResults.error("排污许可设施列表获取失败！");
        }
    }


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 10:32 AM
     * @Deseription: 分表计电生产设施匹配列表
     * @Params: deviceName 分表计电生产设施的名称
     * @Params: pollutantName 排污生产设施名称
     * @Params: pollutantCode 排污生产设施编号（bas_device表的id）
     * @Return: cn.cecep.talroad.common.core.web.domain.AjaxResults
     * @Throws:
     */
    @ApiOperation(value = "操作日志列表")
    @PostMapping("/getBasDeviceInfoOperationLogList")
    public AjaxResults<IPage<BasDeviceInfoOperationLog>> getBasDeviceInfoOperationLogList(@RequestBody FacilityInformationQuery dto) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResults.error("用户Token失效，请重新登录！");
            }
            Long roleId = loginUser.getSysUser().getRoles().get(0).getRoleId();
            if(ObjectUtil.equal(roleId,10L)) {
                dto.setFactoryId(loginUser.getSysUser().getFactoryId());
            }

            IPage<BasDeviceInfoOperationLog> list = facilityInformationManagementServiceImpl.getBasDeviceInfoOperationLogList(dto);
            return AjaxResults.success(list);
        } catch (Exception e) {
            log.error("操作日志列表获取失败!,异常：{}", e);
            return AjaxResults.error("操作日志列表获取失败！");
        }
    }

    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 10:32 AM
     * @Deseription: 分表计电生产设施匹配列表
     * @Params: deviceName 分表计电生产设施的名称
     * @Params: pollutantName 排污生产设施名称
     * @Params: pollutantCode 排污生产设施编号（bas_device表的id）
     * @Return: cn.cecep.talroad.common.core.web.domain.AjaxResults
     * @Throws:
     */
    @ApiOperation(value = "取消对应关系")
    @PostMapping("/cancelDeviceAndPollutantCodeList/{type}")
    public AjaxResults cancelDeviceAndPollutantCodeList(@RequestBody FacilityInformationQuery dto, @PathVariable String type) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResults.error("用户Token失效，请重新登录！");
            }
            dto.setFactoryId(loginUser.getSysUser().getFactoryId());
            facilityInformationManagementServiceImpl.cancelDeviceAndPollutantCodeList(loginUser.getSysUser(), dto, type);
            return AjaxResults.success();
        } catch (Exception e) {
            log.error("取消对应关系失败!,异常：{}", e);
            return AjaxResults.error("取消对应关系失败！");
        }
    }


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 16:00
     * @Deseription: 导出
     * @Params: response
     * @Params: sRaRealTimeAnalysisConverter
     * @Return: void
     * @Throws:
     */
    @ApiOperation(value = "导出")
    @PostMapping("/export/{type}")
    public void export(HttpServletResponse response, @RequestBody FacilityInformationQuery dto, @PathVariable String type) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            response.setContentType("text/plain;charset=UTF-8");
            response.setStatus(500);
            PrintWriter out = response.getWriter();
            out.println("用户Token失效，请重新登录！");
            return;
        }
        Long roleId = loginUser.getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            dto.setFactoryId(loginUser.getSysUser().getFactoryId());
        }
        dto.setQueryType(type);
        dto.setPageNum(1);
        dto.setPageSize(Integer.MAX_VALUE);
        if ("1".equals(type)) {
            IPage<FacilityInformationManagementVO> list = facilityInformationManagementServiceImpl.getProductionDeviceList(dto);
            ExcelUtil<FacilityInformationManagementVO> util = new ExcelUtil<>(FacilityInformationManagementVO.class);
            util.exportExcel(response, list.getRecords(), "分表计电生产设施匹配");
        } else if ("2".equals(type)) {
            IPage<FacilityInformationManagementVO> list = facilityInformationManagementServiceImpl.getProductionDeviceList(dto);
            ExcelUtil<FacilityInformationManagementVO> util = new ExcelUtil<>(FacilityInformationManagementVO.class);
            util.exportExcel(response, list.getRecords(), "分表计电治理设施匹配");
        } else {
            IPage<FacilityInformationManagementVO> list = facilityInformationManagementServiceImpl.getProductionDeviceList(dto);
            List<FacilityInformationManagementDCSVO> targetList = list.getRecords().stream().map(x -> {
                        FacilityInformationManagementDCSVO vo = new FacilityInformationManagementDCSVO();
                        vo.setDeviceId(x.getDeviceId());
                        vo.setDeviceName(x.getDeviceName());
                        vo.setWorkStep(x.getWorkStep());
                        vo.setPollutantCode(x.getPollutantCode());
                        vo.setPollutantName(x.getPollutantName());
                        return vo;
                    }
            ).collect(Collectors.toList());
            ExcelUtil<FacilityInformationManagementDCSVO> util = new ExcelUtil<>(FacilityInformationManagementDCSVO.class);
            util.exportExcel(response, targetList, "DCS生产设施点位匹配");
        }
    }
}
