/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.huimv.modular.collectorregister.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huimv.core.annotion.BusinessLog;
import com.huimv.core.annotion.DataScope;
import com.huimv.core.annotion.Permission;
import com.huimv.core.enums.LogAnnotionOpTypeEnum;
import com.huimv.core.pojo.response.ErrorResponseData;
import com.huimv.core.pojo.response.ResponseData;
import com.huimv.core.pojo.response.SuccessResponseData;
import com.huimv.modular.basepigpen.entity.BasePigpen;
import com.huimv.modular.basepigpen.mapper.BasePigpenMapper;
import com.huimv.modular.basepigpen.service.BasePigpenService;
import com.huimv.modular.collectorregister.entity.CollectorRegister;
import com.huimv.modular.collectorregister.mapper.CollectorRegisterMapper;
import com.huimv.modular.collectorregister.param.CollectorRegisterParam;
import com.huimv.modular.collectorregister.service.CollectorRegisterService;
import com.huimv.modular.constant.ConstnatValue;
import com.huimv.modular.eartagregister.entity.EartagRegister;
import com.huimv.modular.eartagregister.service.EartagRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * 设备管理控制器
 *
 * @author yinhao
 * @date 2021-08-19 09:43:52
 */
@RestController
public class CollectorRegisterController {

    @Resource
    private CollectorRegisterService collectorRegisterService;

    @Resource
    private EartagRegisterService eartagRegisterService;

    @Autowired
    private BasePigpenService basePigpenService;

    @Autowired
    private CollectorRegisterMapper collectorRegisterMapper;


    @Autowired
    private BasePigpenMapper basePigpenMapper;


    //批量添加采集器----客户接口--针对瑞安项目 还没有更新添加基站进去
/*

    @PostMapping("/collectorRegister/addPro")
    public ResponseData addPro(@RequestBody Map<String, Object> params) {
        //批量添加  只是基站号码不是一个  可以一样的操作 -------基站编号自动生成--唯一且不可更改--只展示自己
        String   deviceCodeList = (String) params.get("deviceCodeList");  //耳基站号码  不止一个---实际上是 registerCode

        String[] as = deviceCodeList.split(",");



        String penName = (String) params.get("penName");
        String unitName = (String) params.get("unitName");
        String farmName = (String) params.get("farmName");
        String farmId = (String) params.get("farmId");
        //基站的编码应该在这儿提前确定
        //上传的IP怎么处理--初始ooo 登录后台进行设置？


        //一进来先添加栋舍   拿到  id  再添加舍
        BasePigpen basePigpen = new BasePigpen();
        basePigpen.setFarmCode(farmId); //记录牧场
        basePigpen.setPigpenName(penName); //记录舍名
        basePigpen.setType(1);//栋
        basePigpen.setParentId(0);//栋  阶段啥的全部空着
        basePigpenService.save(basePigpen);


        //拿最新的id 很麻烦直接查一次
        LambdaQueryWrapper<BasePigpen> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc().last("limit 1");
        BasePigpen pigpen = basePigpenMapper.selectOne(wrapper);


        //添加舍得信息
        BasePigpen basePigpenunit = new BasePigpen();
        basePigpenunit.setFarmCode(farmId); //记录牧场
        basePigpenunit.setPigpenName(unitName); //记录舍名
        basePigpenunit.setType(2);//栋
        basePigpenunit.setParentId(pigpen.getId());//栋  阶段啥的全部空着
        basePigpenService.save(basePigpenunit);


        LambdaQueryWrapper<BasePigpen> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.orderByDesc(BasePigpen::getId).last("limit 1");
        BasePigpen pigpenUnite = basePigpenMapper.selectOne(wrapper1);

        //主从关系直接在这里创建   存到云服务器的只有设备编号  不存在其他的东西  转发IP   我们给他写死就可以了





         //传的注册码不能重复
        LambdaQueryWrapper<CollectorRegister> wrapper13 = Wrappers.lambdaQuery();
        wrapper13.in(CollectorRegister::getRegisteCode, as);
        List<CollectorRegister> collectorRegisters = collectorRegisterMapper.selectList(wrapper13);

        if (collectorRegisters.size() != 0) {
            List<String> devideCodes = new ArrayList<>();
            for (CollectorRegister collectorRegister : collectorRegisters) {
                devideCodes.add(collectorRegister.getDeviceCode());
            }
            ErrorResponseData errorResponseData = new ErrorResponseData("添加失败，基站编码存在重复,重复编码为 " + devideCodes);
            return errorResponseData;
        }

        //校验结束的同同时生成基站编码





        //关于设备得机器编码重复的问题  每个牧场分配不同的号段  这里就不做校验了

        // 给 注册中心的的重要参数就是编码   添加到注册中心

        RestTemplate restTemplateAddController = new RestTemplate();

        //放置   tokrn 到  header

        HttpHeaders headers = new HttpHeaders();

        headers.add("Authorization", "Bearer " + json.get("data"));

        headers.add("Content-Type", "applicati on/json");

        Map<String, Object> requestBody = new HashMap<>(8);


        requestBody.put("deviceCode", collectorRegister.getDeviceCode() );

        requestBody.put("penName", collectorRegister.getPenName());

        requestBody.put("pigpenId", collectorRegister.getPigpenId() );

        requestBody.put("port", collectorRegister.getPort());

        requestBody.put("registeCode", collectorRegister.getRegisteCode() );

        requestBody.put("serverIp", collectorRegister.getServerIp() );

        requestBody.put("stage", collectorRegister.getStage());

        requestBody.put("unitId", collectorRegister.getUnitId() );

        requestBody.put("unitName", collectorRegister.getUnitName());

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(requestBody, headers);

        //用的是 199数据库  只有这一个数据库     调用他的增加办法

        String body = restTemplate.postForEntity("http://47.98.40.154:8256/collectorRegister/add", httpEntity, String.class).getBody();

        System.out.println(body);

        //Integer userId = TokenSign.getMemberIdByJwtToken(request);

        collectorRegister.setRegisterTime(new Date());

        collectorRegisterService.save(collectorRegister);

        return new Result(10000,"添加成功",true);










        //前面校验都通过.这儿添加发送的端口，进行数据添加

        List<String>






        for (int i = 0; i < as.length; i++) {

            CollectorRegister collectorRegister = new CollectorRegister();
            collectorRegister.setDeviceCode(as[i]);//拿基站编码
            collectorRegister.setFarmCode(farmId);
            collectorRegister.setFarmName(farmName);
            collectorRegister.setRegisterTime(new Date());
            collectorRegister.setOrgId(123456L);
            collectorRegister.setPenName(penName);
            collectorRegister.setUnitName(unitName);
            collectorRegister.setUnitId(pigpenUnite.getId());
            collectorRegister.setPigpenId(pigpen.getId());
            collectorRegister.setPort(ConstnatValue.Port);//
            collectorRegister.setServerIp(ConstnatValue.IP_VALUE);

            collectorRegisterService.save(collectorRegister);

        }
        SuccessResponseData successResponseData = new SuccessResponseData();
        successResponseData.setCode(200);
        successResponseData.setSuccess(true);
        successResponseData.setMessage("保存成功");
        return successResponseData;
        
    }




*/




    
    
    /**
     * 查询设备管理
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @Permission
    @GetMapping("/collectorRegister/page")
    public ResponseData page(CollectorRegisterParam collectorRegisterParam) {
        return new SuccessResponseData(collectorRegisterService.page(collectorRegisterParam));
    }


    /**
     * 添加设备管理
     * 添加就是这个接口   最终就是这样  带上  token就行
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @Permission
    @PostMapping("/collectorRegister/add")
    public ResponseData add(@RequestBody @Validated(CollectorRegisterParam.add.class) CollectorRegisterParam collectorRegisterParam) {
        collectorRegisterService.add(collectorRegisterParam);
        return new SuccessResponseData();
    }


    /**
     * 删除设备管理，可批量删除
     * 统计数量
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @PostMapping("/collectorRegister/delete")
    public ResponseData delete(@RequestBody @Validated(CollectorRegisterParam.delete.class) List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return ResponseData.error("请选择设备");
        }
        for (Integer id : ids) {
            CollectorRegister collectorRegisterEntity = collectorRegisterService.getById(id);
            String deviceCode = collectorRegisterEntity.getDeviceCode();

            int count = eartagRegisterService.count(Wrappers.<EartagRegister>lambdaQuery().eq(EartagRegister::getDeviceCode, deviceCode));
            if (count > 0) {
                return ResponseData.error("删除失败，设备号为" + collectorRegisterEntity.getDeviceCode() + "的设备下有未清理耳标");
            }
        }

        collectorRegisterService.delete(ids);
        return new SuccessResponseData();
    }


    /**
     * 编辑设备管理
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @PostMapping("/collectorRegister/edit")
    public ResponseData edit(@RequestBody @Validated(CollectorRegisterParam.edit.class) CollectorRegisterParam collectorRegisterParam) {
        collectorRegisterService.edit(collectorRegisterParam);
        return new SuccessResponseData();
    }

    /**
     * 查看设备管理
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @GetMapping("/collectorRegister/detail")
    public ResponseData detail(@Validated(CollectorRegisterParam.detail.class) CollectorRegisterParam collectorRegisterParam) {
        return new SuccessResponseData(collectorRegisterService.detail(collectorRegisterParam));
    }

    @PostMapping("/collectorRegister/logout")
    public ResponseData logout(@RequestBody CollectorRegister collectorRegister) {
        Integer id = collectorRegister.getId();
        CollectorRegister byId = collectorRegisterService.getById(id);
        if (0 == byId.getCanStatus()) {
            byId.setCanStatus(3);
        } else {
            byId.setCanStatus(0);
        }
        collectorRegisterService.updateById(byId);
        return new SuccessResponseData();
    }

    /**
     * 设备管理列表
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @GetMapping("/collectorRegister/list")
    public ResponseData list(CollectorRegisterParam collectorRegisterParam) {
        return new SuccessResponseData(collectorRegisterService.list(collectorRegisterParam));
    }

    /**
     * 采集器总数
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    @GetMapping("/collectorRegister/selectPcEveryStatusCollectors")
    public ResponseData selectPcEveryStatusCollectors(Long orgId) {
        return collectorRegisterService.selectPcEveryStatusCollectors(orgId);
    }

}
