package com.unis.crk.hardware.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.rfid.CReader;
import com.unis.crk.cplbusiness.entity.DataCrkywCplbjdyDefault;
import com.unis.crk.cplbusiness.entity.DataCrkywCplckDefault;
import com.unis.crk.hardware.util.CReaderCopy;
import com.unis.crk.hardware.util.Rfid3Service;
import com.unis.crk.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
//import jdk.internal.instrumentation.Logger;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 单位硬件管理表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-15
 */
@Api(value = "rfid配置",tags = {"rfid配置"})
@RestController
@RequestMapping("rfid")
public class CRreader3SetController {
//    private static final Logger LOGGER =null ;
    public static Map<String, Rfid3Service> rService=new HashMap<String, Rfid3Service>();
    public static Map<String, Long> serviceTiem=new HashMap<String, Long>();
    /**
     * 打开rifd并打开盘点
     * @return
     */
    @ApiOperation(value="打开rifd并打开盘点", notes="链接rfid,ip地址，端口号")
    @GetMapping("OpenreadDatas/{ip}/{port}")
    public ResultUtil OpenreadDatas(@PathVariable("ip") String ip, @PathVariable("port") int port){
        System.out.println("--链接rfid--");
        ResultUtil<Map> data = new ResultUtil<>();
        HashMap<String, String> resultMap = new HashMap<>();
        Rfid3Service rfid3Service = new Rfid3Service();
        String serviceid=IdUtil.simpleUUID();
        rService.put(serviceid,rfid3Service);
        serviceTiem.put(serviceid,System.currentTimeMillis());
        rfid3Service.setId(serviceid);
        int connect = rfid3Service.connect(ip, port); //连接
        if (connect!=0){
            return  data.failed("链接rfid失败");
        }
        int i = rfid3Service.queryLabelContinued();//打开盘点
        if(i !=0){
            return  data.failed("打开盘点失败");
        }
        resultMap.put("server",serviceid);
        return data.success(resultMap);
    }
    /**
     * 打开rifd连接
     * @return
     */
    @ApiOperation(value="打开rifd连接", notes="链接rfid,ip地址，端口号")
    @GetMapping("OpenRfid/{ip}/{port}")
    public ResultUtil OpenRfid(@PathVariable("ip") String ip, @PathVariable("port") int port){
        System.out.println("--链接rfid--");
        ResultUtil<Map> data = new ResultUtil<>();
        HashMap<String, String> resultMap = new HashMap<>();
        Rfid3Service rfid3Service = new Rfid3Service();
        String serviceid=IdUtil.simpleUUID();
        rService.put(serviceid,rfid3Service);
        serviceTiem.put(serviceid,System.currentTimeMillis());
        rfid3Service.setId(serviceid);
        int connect = rfid3Service.connect(ip, port); //连接
        if (connect!=0){
            return  data.failed("链接rfid失败");
        }
        resultMap.put("server",serviceid);
        return data.success(resultMap);
    }
    /**
     * 获取rifd读卡数据
     * @return
     */
    @ApiOperation(value="获取rifd读卡数据", notes="server序号")
    @GetMapping("getRfiddata/{server}")
    public ResultUtil getRfiddata(@PathVariable("server") String server){
        ResultUtil<Map<String,String>> data = new ResultUtil<>();
        Rfid3Service rfid3Service = rService.get(server);
        if(ObjectUtil.isNotNull(rfid3Service)){
            serviceTiem.put(server,System.currentTimeMillis());
            Map<String, String> stringObjectMap = new HashMap<>();
            if(ObjectUtil.isNotNull(rfid3Service)){
                Map<String, Map<String, String>> datarfid = rfid3Service.getDatarfid();
                Iterator<String> iterator = datarfid.keySet().iterator();
                while (iterator.hasNext()) {// 循环取键值进行判断
                    String key = iterator.next();// 键
                    if (key.equals(server)) {
                        Map<String, String> doubleMap = datarfid.get(server);
                        stringObjectMap.putAll(doubleMap);
                    }
                }

            }
            data.success(stringObjectMap);
        }else{
            data.success("请打开盘点");
        }
        return data;
    }

    /**
     * 关闭rifd连接
     * @return
     */
    @ApiOperation(value="关闭rifd连接", notes="server序号")
    @GetMapping("CloesRfid/{server}")
    public ResultUtil CloesRfid(@PathVariable("server") String server){
        System.out.println("--链接关闭rfid--");
        ResultUtil data = new ResultUtil<>();
        Rfid3Service rfid3Service = rService.get(server);
        serviceTiem.remove(server);
        int i = rfid3Service.disConnect();
        rService.remove(server);
        if(i==0){
            return data.success("关闭成功");
        }

        return data.failed("关闭失败");
    }
    /**
     * 关闭rifd连接
     * @return
     */
    @ApiOperation(value="修改Rifd,读写功率(读写器的输出功率。范围是0到30，单位dBm),天线（1-4）", notes="server序号")
    @GetMapping("upataRfid/{server}/{power}/{Antenna1}/{Antenna2}/{Antenna3}/{Antenna4}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="server",value="rfid服务编号",paramType = "query",required=true),
            @ApiImplicitParam(name="power",value="读写器的输出功率。范围是0到30，单位dBm",paramType = "query",required=false),
            @ApiImplicitParam(name="Antenna1",value="天线1",paramType = "query",required=false,allowableValues="true,false"),
            @ApiImplicitParam(name="Antenna2",value="天线2",paramType = "query",required=false,allowableValues="true,false"),
            @ApiImplicitParam(name="Antenna3",value="天线3",paramType = "query",required=false,allowableValues="true,false"),
            @ApiImplicitParam(name="Antenna4",value="天线4",paramType = "query",required=false,allowableValues="true,false"),
    })
    public ResultUtil upataRfid(@RequestParam  String server,@RequestParam  int power,@RequestParam  Boolean Antenna1,@RequestParam  Boolean Antenna2,@RequestParam  Boolean Antenna3,@RequestParam  Boolean Antenna4){
        System.out.println("--链接关闭rfid--");
        serviceTiem.put(server,System.currentTimeMillis());
        String str="";
        ResultUtil data = new ResultUtil<>();
        Rfid3Service rfid3Service = rService.get(server);
        if(ObjectUtil.isNotNull(power)){
            int i = rfid3Service.SetRfPower(power, true);
            if(i==0){
                str+="设置读写功率成功！";
            }else{
                str+="设置读写功率失败！";
            }
        }
        if(ObjectUtil.isNotNull(Antenna1)&&ObjectUtil.isNotNull(Antenna2)&&ObjectUtil.isNotNull(Antenna3)&&ObjectUtil.isNotNull(Antenna4)){
            int i = rfid3Service.setAntenna(Antenna1,Antenna2,Antenna3,Antenna4);
            if(i==0){
                str+="设置天线成功！";
            }else{
                str+="设置天线失败！";
            }
        }


        return data.success(str);
    }
    /**
     * 关闭rifd盘点
     * @return
     */
    @ApiOperation(value="关闭rifd盘点", notes="链接rfid,ip地址，端口号")
    @GetMapping("CloesDatas/{server}")
    public ResultUtil CloesDatas(@PathVariable("server") String server){
        System.out.println("--链接关闭rfid--");
        ResultUtil data = new ResultUtil<>();
        serviceTiem.remove(server);
        Rfid3Service rfid3Service = rService.get(server);
        //关闭盘点时删除读取数据Map
        Map<String, Map<String, String>> datarfid = rfid3Service.getDatarfid();
        Iterator<String> itera = datarfid.keySet().iterator();
        while (itera.hasNext()) {// 循环取键值进行判断
            String key = itera.next();// 键
            if (key.equals(server) ) {
                itera.remove();
            }
        }
        //关闭盘点时删除连接Map
        Iterator<String> iterator = rService.keySet().iterator();
        while (iterator.hasNext()) {// 循环取键值进行判断
            String key = iterator.next();// 键
            if (key.equals(server)) {
                iterator.remove();//
            }
        }
        int i = rfid3Service.ColseContinued();
        if(i==0){
            return data.success("关闭成功");
        }

        return data.failed("关闭失败");
    }

    /**
     * 写epc数据
     * @return
     */
    @ApiOperation(value="写epc数据", notes="链接rfid,ip地址，端口号")
    @GetMapping("writeData/{ip}/{port}/{str}")
    public ResultUtil writeData(@PathVariable("ip") String ip, @PathVariable("port") int port,@PathVariable("str") String str){
        System.out.println("--链接rfid--");
        ArrayList<String> epcArray = new ArrayList<>();
        String newEpc=null;
        Rfid3Service rfid3Service = new Rfid3Service();
        int connect = rfid3Service.connect(ip, port); //连接
        ResultUtil<List<Map<String,Object>>> data = new ResultUtil<>();
        if (connect!=0){
            data.failed("链接rfid失败");
            return data;
        }
        int rst = rfid3Service.queryLabel(); //寻卡

        if(rst <0){
            data.failed("寻卡失败");
        }else{
            System.out.println("总共查询到" + rst +"张卡");
        }
        if(rfid3Service.getEpcs().size()>10){
            System.out.println("查询到多张标签，无法进行写入操作");
            return  data.failed("查询到多张标签，无法进行写入操作");
        }else if(rfid3Service.getEpcs().size()==0){
            System.out.println("未查询到标签，无法进行写入操作");
            return  data.failed("未查询到标签，无法进行写入操作");
        }
        for(int i=0;i<rfid3Service.getEpcs().size();i++) {
             newEpc = rfid3Service.writeData(rfid3Service.getEpcs().get(i).toString(), str);
            System.out.println("写入后返回:" + newEpc);
        }
        for(int k=0;k<rfid3Service.getEpcs().size();k++) {
            String epc = rfid3Service.readData(rfid3Service.getEpcs().get(k).toString());
            System.out.println("写后epc:" + epc);
            data.success(epc);
            String timeStr1 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        }
        data.success(newEpc);
        rfid3Service.disConnect();
        return data;
    }
    public static void removeRfidService(){
        Iterator<Map.Entry<String, Long>> iterator = serviceTiem.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Long> next = iterator.next();
            Long value = next.getValue();
            long l = System.currentTimeMillis() - value;
            if(l>1000*60*2){
                System.out.println("执行rfid超时连接关闭");
                String key = next.getKey();
                Rfid3Service key1 = rService.get(key);
                Map<String, Map<String, String>> datarfid = key1.getDatarfid();
                if(ObjectUtil.isNotNull(datarfid)){
                    datarfid.remove(key);
                }
                key1.disConnect();
                rService.remove(key);
                iterator.remove();
            }

        }
    }
}
