/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2023/10/19
 */
package org.springblade.modules.baseinfo.monitorsite.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.monitorpoint.entity.MonitorPointInfoEntity;
import org.springblade.modules.baseinfo.monitorpoint.entity.MonitorPointRelEntity;
import org.springblade.modules.baseinfo.monitorpoint.service.IMonitorPointRelService;
import org.springblade.modules.baseinfo.monitorpoint.service.IMonitorPointService;
import org.springblade.modules.baseinfo.monitorsite.dto.MonitorSiteInfoDTO;
import org.springblade.modules.baseinfo.monitorsite.entity.MonitorSiteInfoEntity;
import org.springblade.modules.baseinfo.monitorsite.entity.MonitorSiteRelEntity;
import org.springblade.modules.baseinfo.monitorsite.service.IMonitorSiteRelService;
import org.springblade.modules.baseinfo.monitorsite.service.IMonitorSiteService;
import org.springblade.modules.baseinfo.monitorsite.vo.MonitorSiteInfoVO;
import org.springblade.modules.baseinfo.monitorsite.wrapper.MonitorSiteWrapper;
import org.springblade.modules.baseinfo.rtu.entity.RtuInfoEntity;
import org.springblade.modules.baseinfo.rtu.service.IRtuBaseInfoService;
import org.springblade.modules.baseinfo.wateruseconsumer.entity.WaterUseConsumerInfoEntity;
import org.springblade.modules.baseinfo.wateruseconsumer.service.IWaterUseConsumerService;
import org.springblade.modules.business.rtumanage.entity.RtuStatusEntity;
import org.springblade.modules.business.rtumanage.service.IRtuManageService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/***
 * Date:2023/10/19
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/base/monitorsite")
@AllArgsConstructor
@Api(value = "监测站模块", tags = "监测站接口")
public class MonitorSiteController extends BladeController {
    private final IMonitorSiteService monitorSiteService;
    private final IMonitorSiteRelService monitorSiteRelService;
    private final IRtuBaseInfoService rtuBaseInfoService;
    private final IWaterUseConsumerService waterUseConsumerService;
    private final IMonitorPointRelService monitorPointRelService;
    private final IMonitorPointService monitorPointService;
    private final IRtuManageService rtuManageService;


    /**
     * 多表联合查询自定义分页
     */
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wiustCd", value = "监测站代码", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "wiustNm", value = "监测站名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "wiuNm", value = "用水户名称", paramType = "query", dataType = "string"),

    })
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页")
    public R<IPage<MonitorSiteInfoVO>> page(@ApiIgnore MonitorSiteInfoDTO dto, Query query) {
        IPage<MonitorSiteInfoVO> pages = monitorSiteService.selectPage(Condition.getPage(query), dto);
        List<MonitorSiteInfoVO> list = pages.getRecords();
        for (MonitorSiteInfoVO vo : list) {
            MonitorSiteWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }

    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wiustCd", value = "监测站代码", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "wiustNm", value = "监测站名称", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页")
    public R<List<MonitorSiteInfoVO>> list(@ApiIgnore MonitorSiteInfoEntity dto) {
        List<MonitorSiteInfoEntity> list = monitorSiteService.selectAll(dto);
        return R.data(MonitorSiteWrapper.build().listVO(list));
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "")
    public R<MonitorSiteInfoVO> detail(MonitorSiteInfoEntity dto) {
        MonitorSiteInfoEntity detail = monitorSiteService.getOne(Condition.getQueryWrapper(dto));
        return R.data(MonitorSiteWrapper.build().entityVO(detail));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "")
    public R save(@RequestBody MonitorSiteInfoDTO dto) {
        if (Func.isNull(dto.getWiustCd()) || Func.isNull(dto.getWiuCd())) {
            return R.fail("参数错误");
        }
        LambdaQueryWrapper<MonitorSiteInfoEntity> wrapper = Wrappers.<MonitorSiteInfoEntity>query().lambda();
        wrapper.eq(MonitorSiteInfoEntity::getIsDeleted, 0);
        wrapper.eq(MonitorSiteInfoEntity::getWiustCd, dto.getWiustCd());
        long count = monitorSiteService.count(wrapper);
        if (count > 0) {
            return R.fail("测站已经存在");
        }
        //添加RTU
        RtuInfoEntity rtuInfoEntity = rtuBaseInfoService.rtuInfoByRtuCode(dto.getWiustCd());
        if (Func.isNull(rtuInfoEntity)) {
            rtuInfoEntity = new RtuInfoEntity();
        }
        rtuInfoEntity.setRtuCode(dto.getWiustCd());
        rtuInfoEntity.setRtuName(dto.getWiustNm());
        LambdaQueryWrapper<WaterUseConsumerInfoEntity> wrapper2 = Wrappers.<WaterUseConsumerInfoEntity>query().lambda();
        wrapper2.eq(WaterUseConsumerInfoEntity::getIsDeleted, 0);
        wrapper2.eq(WaterUseConsumerInfoEntity::getWiuCd, dto.getWiuCd());
        WaterUseConsumerInfoEntity waterUseConsumerInfoEntity = waterUseConsumerService.getOne(wrapper2);
        if (Func.notNull(waterUseConsumerInfoEntity)) {
            rtuInfoEntity.setOrgId(waterUseConsumerInfoEntity.getOrgId());
        }
        rtuBaseInfoService.saveOrUpdate(rtuInfoEntity);
        //测站和用水户关联表
        monitorSiteRelService.removeRel(dto.getWiustCd());
        MonitorSiteRelEntity relEntity = new MonitorSiteRelEntity();
        relEntity.setWiustCd(dto.getWiustCd());
        relEntity.setWiuCd(dto.getWiuCd());
        monitorSiteRelService.save(relEntity);
        return R.status(monitorSiteService.save(dto));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "")
    public R update(@RequestBody MonitorSiteInfoDTO dto) {
        if (Func.isNull(dto.getId())) {
            return R.fail("参数错误");
        }
        if (monitorSiteService.updateById(dto)) {
            RtuInfoEntity rtuInfoEntity = rtuBaseInfoService.rtuInfoByRtuCode(dto.getWiustCd());
            if (Func.notNull(rtuInfoEntity)) {
                rtuInfoEntity.setRtuName(dto.getWiustNm());
                rtuBaseInfoService.updateById(rtuInfoEntity);
            }
        }
        return R.status(true);
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "")
    public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
        List<Long> idArr = Func.toLongList(ids);
        for (Long id : idArr) {
            MonitorSiteInfoEntity entity = monitorSiteService.getById(id);
            //删除RTU
            RtuInfoEntity rtuInfoEntity = rtuBaseInfoService.rtuInfoByRtuCode(entity.getWiustCd());
            if (Func.notNull(rtuInfoEntity)) {
                rtuBaseInfoService.deleteLogic(Func.toLongList(Func.toStr(rtuInfoEntity.getId())));
            }
            //删除RTU状态
//            LambdaQueryWrapper<RtuStatusEntity> wrapper = Wrappers.<RtuStatusEntity>query().lambda();
//            wrapper.eq(RtuStatusEntity::getIsDeleted, 0);
//            wrapper.eq(RtuStatusEntity::getRtuCode, entity.getWiustCd());
//            RtuStatusEntity rtuStatusEntity = rtuManageService.getOne(wrapper);
//            if (Func.notNull(rtuStatusEntity)) {
//                rtuManageService.deleteLogic(Func.toLongList(Func.toStr(rtuStatusEntity.getId())));
//            }
            //删除站点下点位
            monitorSiteService.removeRelPoints(entity.getWiustCd());
            //删除测站和用水户关联表
            monitorSiteRelService.removeRel(entity.getWiustCd());
        }
        //删除站点
        boolean temp = monitorSiteService.deleteLogic(Func.toLongList(ids));
        return R.status(true);
    }
}
