package com.zzliaoyuan.power_sensor.fragment;

import android.os.Environment;

import com.rscja.deviceapi.entity.UHFTAGInfo;
import com.zzliaoyuan.power_sensor.MainApplication;
import com.zzliaoyuan.power_sensor.MainActivity;
import com.zzliaoyuan.power_sensor.tools.UIHelper;
import com.zzliaoyuan.rifdmastercore.LibCore;
import com.zzliaoyuan.rifdmastercore.ProductInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class UHFReadTagFragment {

    private static UHFReadTagFragment mInstance;
    private MainActivity mContext;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private static int delayTime = 100;  //ms
    private static int periodTime = 300;  //ms
    private boolean isStop = true;
    private ArrayList<String> assetsList = new ArrayList<String>();

    public static UHFReadTagFragment getInstance() {
        if (mInstance == null) {
            synchronized (UHFReadTagFragment.class) {
                if (mInstance == null) {
                    mInstance = new UHFReadTagFragment();
                }
            }
        }

        return mInstance;
    }

    public void setContext(MainActivity context) {
        mContext = context;
    }


    // wsdd userd
    public void setUserModel() {
        // 设置循环盘点同时读取 EPC、TID、USER 模式
        mContext.mReader.setEPCAndTIDUserMode(0, 24);
        readAssets();
    }

    private void readTag() {
        // wsdd 点击开始按钮后，开始执行扫描
        // wsdd 单步读取的数据
        UHFTAGInfo strUII = mContext.mReader.inventorySingleTag();
        if (strUII != null) {
//            String strTid = "E28011052000715CA32D0A1C"; //strUII.getTid();
//            String strUser = "2F83FE1758F601C6E70BECF1DCCC491866D30D5D5178FA48CFD18A87A7709D42A5EC8599882C8EDF3E3D6DA0E6EB1FE0"; //strUII.getUser();
            String strTid = strUII.getTid();
            String strUser = strUII.getUser();
            if (strUser != null && strTid != null) {
                String Data = "{\"userData\":\"" + strUser + "\""; // 读取的用户区数据
                byte[] szBuffer = LibCore.HexStringToByteArray(strUser);
                ProductInfo product = LibCore.decode(szBuffer, strTid);//

                if (strUser.length() == 96 && product != null) {

                    Data += ",\"error\":0"; // 错误提示
                    Data += ",\"assetID\":\"" + product.assetID.replace("\\s*","").trim()  + "\""; // 资产编号
                    Data += ",\"model\":\"" + product.model + "\""; // 型号
                    Data += ",\"manufacturer\":\"" + product.manufacturer + "\""; // 生产厂家
                    Data += ",\"kind\":\"" + product.kind + "\""; // 产品类型
                    Data += ",\"district\":\"" + product.district + "\""; // 用户地区代码
                    Data += ",\"districtText\":\"" + product.districtText + "\""; // 用户地区
                    Data += ",\"place\":\"" + product.place + "\""; // 安装场所
                    Data += ",\"voltageLevel\":\"" + product.voltageLevel + "\""; // 电压等级
                    Data += ",\"secondWindingCount\":\"" + product.secondWindingCount + "\""; // 二次绕组数量
                    Data += ",\"secondVoltage\":\"" + product.secondVoltage + "\""; // 二次电压
                    Data += ",\"firstCurrent\":\"" + product.firstCurrent + "\""; // 一次电流
                    Data += ",\"senondCurrent\":\"" + product.senondCurrent + "\""; // 二次电流
                    Data += ",\"accuracy\":\"" + product.accuracy + "\""; // 准确等级
                    Data += ",\"ratedLoad\":\"" + product.ratedLoad + "\""; // 额定负荷
                    Data += ",\"releaseDate\":\"" + product.releaseDate + "\""; // 出厂日期
                    Data += ",\"voltageFactor\":\"" + product.voltageFactor + "\""; // 电压因数
                    Data += ",\"version\":\"" + product.version + "\""; // 版本
                    Data += ",\"powerFactor\":\"" + product.powerFactor + "\""; // 功率因数
                    writeAssets(product.assetID);
                    // wsdd 添加读取的数据,此处应该返回数据strEPC到RN
                    // 返回给RN的数据格式 {"userData":"6a173f0fd2a140cf20204fbaa6d1c0158518031da248f306535dc6d10026a7c985671ae611afb4c151feb5712eba3d52","assetID":"4330012800000002178203  ","model":"002型","manufacturer":"北京***公司","kind":"电压互感器"}
                } else {
                    Data += ",\"error\":1";
                    Data += ",\"error_msg\":\"格式错误(" + strUser.length() + ")：" + strUser + "\"";
                }
                Data += "}";
                MainApplication.GetReactPackage().reactModule.sendMsgToRN("MsgFromAndroid", Data);
                mContext.playSound(1);
            } else {
                mContext.playSound(2);
            }
        } else {
            UIHelper.ToastMessage(mContext, "识别失败");
        }
    }

    /**
     * 设置功率
     */
    public void setPower(Integer power) {
        if (mContext.mReader.setPower(power)) {
            UIHelper.ToastMessage(mContext, "设置功率成功");
        } else {
            UIHelper.ToastMessage(mContext, "设置功率失败");
        }
    }

    public int getPower() {
        return mContext.mReader.getPower();
    }

    /**
     * 停止识别
     */
    public void myOnKeyDwon() {
        isStop = !isStop;

        if (!isStop) {
            startRead();
        } else {
            stopRead();
        }
    }

    public void startRead() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    try {
                        readTag();
                    } catch (Exception e) {
                        e.printStackTrace();
//                        UIHelper.ToastMessage(mContext, "识别失败");
                    }
                }
            };
        }

        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, delayTime, periodTime);
        }
    }

    public void stopRead() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    public void readAssets() {
        assetsList = new ArrayList<String>();
        try {
            // 存放的文件路径
            File assetsFile = new File(
                    Environment.getExternalStorageDirectory().getCanonicalPath() + "/assetsLog"
            );
            if (!assetsFile.exists()) {
                try {
                    assetsFile.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                    UIHelper.ToastMessage(mContext, "创建资产编号日志文件夹失败" + "-" + e.getMessage());
                }
            }
            String strFilePath = "assets.txt";
            File file = new File(assetsFile, strFilePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            // 读取文件内容
            FileInputStream instream = new FileInputStream(file);
            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;
                //分行读取
                while ((line = buffreader.readLine()) != null) {
                    assetsList.add(line);
                }
                instream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            UIHelper.ToastMessage(mContext, "读取资产编号日志文件失败" + "-" + e.getMessage());
        }
    }

    public void writeAssets(String asset) {
        // 先判断assetsList中是否存在新读取的asset,不存在，则写入
        if (!assetsList.contains(asset)) {
            try {
                // 存放的文件路径
                File assetsFile = new File(
                        Environment.getExternalStorageDirectory().getCanonicalPath() + "/assetsLog"
                );
                if (!assetsFile.exists()) {
                    try {
                        assetsFile.mkdirs();
                    } catch (Exception e) {
                        e.printStackTrace();
                        UIHelper.ToastMessage(mContext, "创建资产编号日志文件夹失败" + "-" + e.getMessage());
                    }
                }
                String strFilePath = "assets.txt";
                String strContent = asset + "\r\n";
                File file = new File(assetsFile, strFilePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
//                MediaScannerConnection.scanFile(mContext, new String[] { file.getAbsolutePath() }, null, null);
                assetsList.add(asset);
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                raf.seek(file.length());
                raf.write(strContent.getBytes());
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
                UIHelper.ToastMessage(mContext, "写入资产编号日志文件失败" + "-" + e.getMessage());
            }
        }
    }

}
