/*
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.eartagregister.controller;


import com.aliyun.oss.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.core.annotion.BusinessLog;
import com.huimv.core.annotion.Permission;
import com.huimv.core.enums.LogAnnotionOpTypeEnum;
import com.huimv.core.factory.PageFactory;
import com.huimv.core.pojo.page.PageResult;
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.collectorregister.entity.CollectorRegister;
import com.huimv.modular.collectorregister.mapper.CollectorRegisterMapper;
import com.huimv.modular.collectorregister.param.CollectorRegisterParam;
import com.huimv.modular.eartagdata.entity.EartagData;
import com.huimv.modular.eartagdata.entity.vo.EartagDataVo;
import com.huimv.modular.eartagdata.mapper.EartagDataMapper;
import com.huimv.modular.eartagdata.service.EartagDataService;
import com.huimv.modular.eartagregister.entity.EartagRegister;
import com.huimv.modular.eartagregister.entity.EartagRegisterVO;
import com.huimv.modular.eartagregister.mapper.EartagRegisterMapper;
import com.huimv.modular.eartagregister.param.EartagRegisterParam;
import com.huimv.modular.eartagregister.service.EartagRegisterService;
import com.huimv.modular.farmstock.param.FarmStockParam;
import com.huimv.modular.result.R;
import com.huimv.modular.utils.util.StringUtilsWork;
import com.tencentcloudapi.vpc.v20170312.models.PrivateIpAddressSpecification;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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.RestController;


import javax.xml.transform.Source;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 耳标注册控制器
 *
 * @author yinhao
 * @date 2021-08-17 16:17:54
 */

@RestController
public class EartagRegisterController{
    
    
    @Autowired
    private EartagRegisterService   eartagRegisterService;


    @Autowired
    private EartagRegisterMapper eartagRegisterMapper;


    @Autowired
    private EartagDataMapper  eartagDataMapper ;



    @Autowired
    private CollectorRegisterMapper collectorRegisterMapper ;




    //增加增删改查的功能  删除的时候删除所有的耳标：
    //手动添加的只有三个参数  耳标号   坐标  然后没有了    在上传的时候补齐其余信息  （默认上传次数为1）
    //所有的事件接口   //批量添加耳标
    @PostMapping ("/EratagRegister/addPro")
    public ResponseData addPro(@RequestBody Map<String, Object> params) throws ClientException, ParseException {
        //入参的统一校验就应该通过 param的统一校验来做  不然重复代码过多啊
        String eartagNoList = (String) params.get("eartagNoList");  //耳标号
        String deviceCode = (String) params.get("deviceCode");  //坐标
        //禁止重复添加耳标号
        LambdaQueryWrapper<CollectorRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CollectorRegister::getDeviceCode, deviceCode);
        CollectorRegister collectorRegister = collectorRegisterMapper.selectOne(wrapper);

        if (collectorRegister == null) {
            ErrorResponseData errorResponseData = new ErrorResponseData("添加失败，采集器未注册");
            errorResponseData.setCode(0);
            return errorResponseData;
        }


        String[] as = eartagNoList.split(",");
        System.out.println(eartagNoList);
        LambdaQueryWrapper<EartagRegister> wrapper13 = Wrappers.lambdaQuery();
        wrapper13.in(EartagRegister::getEartagNo ,   as);
        List<EartagRegister> eartagRegisters = eartagRegisterMapper.selectList(wrapper13);
        if(eartagRegisters.size()!=0) {
            List<String> eartagRegiste = new ArrayList<>();
            for ( EartagRegister eartagRegister : eartagRegisters) {
                eartagRegiste.add(eartagRegister.getEartagNo());
            }
            ErrorResponseData errorResponseData = new ErrorResponseData("添加失败，耳标存在重复,重复编码为 "+eartagRegiste);
            return errorResponseData;
        }


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

            EartagRegister eartagRegister = new EartagRegister();
            eartagRegister.setDeviceCode(collectorRegister.getDeviceCode());
            eartagRegister.setFarmCode(collectorRegister.getFarmCode());
            eartagRegister.setRegisterDate(new Date());
            eartagRegister.setEartagNo(as[i]);
            eartagRegister.setOrgId(123456L);
            eartagRegister.setPigpen(String.valueOf(collectorRegister.getPigpenId()));
            eartagRegisterService.save(eartagRegister);
        }
        
        SuccessResponseData successResponseData = new SuccessResponseData();
        successResponseData.setCode(200);
        successResponseData.setSuccess(true);
        successResponseData.setMessage("保存成功");
        return successResponseData;
    }

    /**
     * 最近添加的十个耳标
     * @param params
     * @return
     * @throws ClientException
     * @throws ParseException
     */
    @PostMapping ("/EratagRegister/listlast10Add")
    public ResponseData listlast10Add(@RequestBody Map<String, Object> params) throws ClientException, ParseException {
        //入参的统一校验就应该通过 param的统一校验来做  不然重复代码过多啊
        String farmId = (String) params.get("farmId");  //耳标号
        //禁止重复添加耳标号
        LambdaQueryWrapper<EartagRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(EartagRegister::getFarmCode, farmId);
        wrapper.orderByDesc(EartagRegister::getId);
        wrapper.last("limit 10");
        List<EartagRegister> eartagRegisters = eartagRegisterMapper.selectList(wrapper);

        SuccessResponseData successResponseData = new SuccessResponseData("成功");
        successResponseData.setData(eartagRegisters);
        return successResponseData;
    }


    //展示注册表中的所有耳标  通过时间来倒序查
   /* {
        "eartagNo": "00010131010",
            "location": "A13-6",
            "pageSize":10,
            "pageSize"
    }*/
    //增加增删改查的功能  删除的时候删除所有的耳标：
    //手动添加的只有三个参数  耳标号   坐标  然后没有了    在上传的时候补齐其余信息  （默认上传次数为1）
    //所有的事件接口
    @RequestMapping("/EratagRegister/list")
    public  SuccessResponseData listEratagRegister(@RequestBody Map<String, Object> params) throws ClientException, ParseException {
        //入参的统一校验就应该通过 param的统一校验来做  不然重复代码过多啊
        String   eartagNo = (String) params.get("eartagNo");  //耳标号
        String   location = (String) params.get("location");  //坐标
        Integer   pageNo = (Integer) params.get("pageNo");
        Integer  pageSize = (Integer)  params.get("pageSize");
        String   EartagError = (String) params.get("EartagError");  //耳标损坏  --次数个和温度都是0
        String   EartagWarm = (String) params.get("EartagWarm");  //可能次数很少 但是温度不为0
        Integer  countTimes = (Integer)  params.get("countTimes");
        String   TempError = (String) params.get("TempError");  //可能次数很少 但是温度不为0
        EartagRegisterVO eartagRegisterVO = new EartagRegisterVO();

        if(countTimes!=null){
            eartagRegisterVO.setCount(String.valueOf(countTimes));
        }
        eartagRegisterVO.setLocation(location);
        eartagRegisterVO.setTempError(TempError);
        eartagRegisterVO.setPageNo(pageNo);
        eartagRegisterVO.setPageSize(pageSize);
        eartagRegisterVO.setEartagNo(eartagNo);
        eartagRegisterVO.setEartagWarm(EartagWarm);
        eartagRegisterVO.setEartagError(EartagError);
        //
        PageResult<EartagRegister> query = eartagRegisterService.query(eartagRegisterVO);
        return     new SuccessResponseData(query);
       
    }





    //修改注册信息
    @RequestMapping("/EratagRegister/update")
    public R updateEratagRegister(@RequestBody Map<String, Object> params) throws ClientException, ParseException {
        //入参的统一校验就应该通过 param的统一校验来做  不然重复代码过多啊

        Integer  id = (Integer)  params.get("id");
        String   eartagNo = (String) params.get("eartagNo");  //耳标号---不可修改  可能会乱数据库
        String   location = (String) params.get("location");  //坐标


        LambdaQueryWrapper<EartagRegister> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(EartagRegister::getId, id);
        EartagRegister eartagRegister = eartagRegisterMapper.selectOne(wrapper);

        if (StringUtilsWork.isNotBlank(location)) {
            eartagRegister.setLocation(location);
            eartagRegister.setEartagNo(eartagNo);
        }

        eartagRegisterService.updateById(eartagRegister);
        return  R.ok("修改耳标基础信息成功");
    }


    //增加增删改查的功能  删除的时候删除所有的耳标：
    //手动添加的只有三个参数  耳标号   坐标  然后没有了    在上传的时候补齐其余信息  （默认上传次数为1）
    //所有的事件接口
    @RequestMapping("/EratagRegister/add")
    public R addEratagRegister(@RequestBody Map<String, Object> params) throws ClientException, ParseException {
        //入参的统一校验就应该通过 param的统一校验来做  不然重复代码过多啊
        String   eartagNo = (String) params.get("eartagNo");  //耳标号
        String   location = (String) params.get("location");  //坐标
        //禁止重复添加耳标号

        LambdaQueryWrapper<EartagRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(EartagRegister::getEartagNo, eartagNo ).last( "limit 1");
        EartagRegister    EarTagDate = eartagRegisterMapper.selectOne(wrapper);
        if(EarTagDate !=null){
            return R.error("耳标号已经存在，请检查后添加");
        }
        EartagRegister eartagRegister = new EartagRegister();
        eartagRegister.setEartagNo(eartagNo);   //耳标号
        eartagRegister.setLocation(location);  //位置
        eartagRegister.setOrgId(1453999066545344513L);//存放一个 目前没啥用的字段
        eartagRegister.setRegisterDate( new Date());  //注册时间
        eartagRegister.setCountTimes( 0);  //统计次数
        eartagRegister.setEarTemp(0);  //统计次数
        eartagRegister.setWeartagAge(0);  //日龄暂时为0
        eartagRegisterService.save(eartagRegister);
        
        return R.ok("保存成功");
    }



    
    //删除耳标左右信息
    @RequestMapping("/EratagRegister/delete")
    public R deleteEratagRegister(@RequestBody Map<String, Object> params) throws ClientException, ParseException {
        //入参的统一校验就应该通过 param的统一校验来做  不然重复代码过多啊
        String   eartagNo = (String) params.get("eartagNo");  //耳标号
        LambdaQueryWrapper<EartagRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(EartagRegister::getEartagNo, eartagNo ).last( "limit 1");
        EartagRegister    EarTagDate = eartagRegisterMapper.selectOne(wrapper);
        if(EarTagDate ==null){
            return R.error("要删除的耳标不存在，请确认耳标号");
        }
       //存在耳标号就删除所有的耳标号
        eartagRegisterMapper.deleteByeartagnoFromEartagregister(eartagNo);
       //删除这个耳标的数据
        eartagDataMapper.deleteOneEartagDataAll(eartagNo);
        return R.ok("删除成功");
    }































    
    
    
    
    
    
    
    
    
    
    
    
    
    


}
