/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.xrtygis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.entity.Dmatable;
import com.tofly.xrtygis.entity.TfDeviceArchiveManage;
import com.tofly.xrtygis.service.DmatableService;
import com.tofly.xrtygis.service.TfDeviceArchiveManageService;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备档案管理
 *
 * @author admin
 * @date Fri Mar 11 00:00:00 CST 2022
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tfdevicearchivemanage")
@Api(tags="设备档案管理接口")
public class TfDeviceArchiveManageController {

    private final TfDeviceArchiveManageService tfDeviceArchiveManageService;
    private final DmatableService dmatableService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param tfDeviceArchiveManage 设备档案管理
     * @return
     */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getTfDeviceArchiveManagePage(Page page, @ModelAttribute TfDeviceArchiveManage tfDeviceArchiveManage) {
        try{
            String waterIds = tfDeviceArchiveManage.getWaterIds();
            String deviceTypeIds = tfDeviceArchiveManage.getDeviceTypeIds();
            List<Long> waterIdList = new ArrayList<>();
            List<String> deviceTypeList = new ArrayList<>();
            if(StringUtil.isNotEmpty(waterIds)){
                waterIdList = Arrays.stream(waterIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            }
            if(StringUtil.isNotEmpty(deviceTypeIds)){
                deviceTypeList = Arrays.stream(deviceTypeIds.split(Constant.CSV)).map(String::trim)
                        .collect(Collectors.toList());
            }
            return ResultRespone.success(tfDeviceArchiveManageService.page(page, new QueryWrapper<TfDeviceArchiveManage>().lambda()
                    .in(StringUtil.isNotEmpty(waterIdList),TfDeviceArchiveManage::getWaterId,waterIdList)
                    .in(StringUtil.isNotEmpty(deviceTypeList),TfDeviceArchiveManage::getDeviceType,deviceTypeList)
                    .setEntity(tfDeviceArchiveManage)));
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed();
        }
    }


    /**
     * 通过id查询设备档案管理
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id" ) Long id) {
        try{
            return ResultRespone.success(tfDeviceArchiveManageService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed();
        }
    }

    /**
     * 新增设备档案管理
     * @param tfDeviceArchiveManage 设备档案管理
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增设备档案管理" )
    @ApiOperation(value = "新增设备档案管理")
    @PostMapping
    @Transactional
    public ResultRespone save(@RequestBody TfDeviceArchiveManage tfDeviceArchiveManage) {
        try{
           Integer count=tfDeviceArchiveManageService.count(
                    new QueryWrapper<TfDeviceArchiveManage>().lambda()
                            .eq(TfDeviceArchiveManage::getCode,tfDeviceArchiveManage.getCode()));
            if(count>0){
                return ResultRespone.failed("设备编号已存在，不能重复新增");
            }
            boolean save = tfDeviceArchiveManageService.save(tfDeviceArchiveManage);
            // 判断是否为计量表 为计量表则同步
            String deviceType = tfDeviceArchiveManage.getDeviceType();
            if("3".equals(deviceType)||"2".equals(deviceType)){
                Dmatable dmatable = new Dmatable();
                dmatable.setDeviceId(tfDeviceArchiveManage.getId());
                dmatable.setMinFlow((double)0);

                dmatableService.save(dmatable);
            }
            return ResultRespone.success(save);
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed();
        }
    }

    /**
     * 修改设备档案管理
     * @param tfDeviceArchiveManage 设备档案管理
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改设备档案管理" )
    @ApiOperation(value = "修改设备档案管理")
    @PutMapping
    @Transactional
    public ResultRespone updateById(@RequestBody TfDeviceArchiveManage tfDeviceArchiveManage) {
        // 判断是否为计量表 为计量表则同步

        Integer count=tfDeviceArchiveManageService.count(
                new QueryWrapper<TfDeviceArchiveManage>().lambda()
                        .eq(TfDeviceArchiveManage::getCode,tfDeviceArchiveManage.getCode())
                        .ne(TfDeviceArchiveManage::getId,tfDeviceArchiveManage.getId()));
        if(count>0){
            return ResultRespone.failed("设备编号已存在，不能修改");
        }


        String deviceType = tfDeviceArchiveManage.getDeviceType();
        List<Dmatable> list = dmatableService.list(new QueryWrapper<Dmatable>().lambda().eq(Dmatable::getDeviceId, tfDeviceArchiveManage.getId()));
        if("3".equals(deviceType)||"2".equals(deviceType)){
            Dmatable dmatable = new Dmatable();
            dmatable.setDeviceId(tfDeviceArchiveManage.getId());
            dmatable.setMinFlow((double)0);
            if(null == list || list.size() == 0){
                dmatableService.save(dmatable);
            }
        }else {
            // 删除区域表(不为计量表)
            if(null!=list && StringUtil.isNotEmpty(deviceType)){
                for (Dmatable dmatable : list) {
                    dmatableService.removeById(dmatable.getId());
                }
            }
        }
        try{
            return ResultRespone.success(tfDeviceArchiveManageService.updateById(tfDeviceArchiveManage));
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed();
        }
    }


    /**
     * 通过id批量删除设备档案管理
     * @param ids id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id批量删除设备档案管理" )
    @ApiOperation(value = "通过ID批量删除设备档案管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds" )
    public ResultRespone removeById(String ids) {
        try{
            List<Long> idList = Arrays.stream(ids.split(",")).map(k -> Long.parseLong(k.trim())).collect(Collectors.toList());
            // 删除计量表同步的设备
            dmatableService.remove(new QueryWrapper<Dmatable>().lambda().in(Dmatable::getDeviceId,idList));
            return ResultRespone.success(tfDeviceArchiveManageService.removeByIds(idList));
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed();
        }
    }


    /**
     * 导入设备和对应的指标数据
     * @return
     */
    @ToFlyAppLog(title="导入设备和对应的指标数据" )
    @ApiOperation(value = "导入设备和对应的指标数据")
    @PostMapping("/import")
  public ResultRespone ImportData(@Validated @RequestParam(value = "file",required = true) MultipartFile file){
        return ResultRespone.success(tfDeviceArchiveManageService.ImportData(file));
    }


    /**
     * 设备类型统计
     * @return
     */
    @GetMapping("/getDeviceTypeReport" )
    @ToFlyAppLog(title="设备类型统计" )
    @ApiOperation(value = "设备类型统计")
    public ResultRespone getDeviceTypeReport() {
        return ResultRespone.success(tfDeviceArchiveManageService.getDeviceTypeReport());
    }
}
