package com.ecom.park_jy;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import cz.msebera.android.httpclient.Header;

public class Start extends AppCompatActivity implements LocationListener{
    private LocationManager mgr;
    Intent intent = new Intent();
    List list = new ArrayList();
    int sNum,expenses,nTrueId,nCurrentId;
    int count = 1;
    int photoCount = 0;
    String[] dataCount,gps_boxA;
    double hour = 0;
    int nCount;
    static int RoadNum = 0;
    static int postion_box = 0;
    Road_list rL = new Road_list();
    Handler handler = new Handler();
    private ArrayList<String> szFileList  = new ArrayList<String>();
    private static int nStatus = 0;  //0:New; 1:List; 2:Changed;
    int fee;
    double fee_time;
    ProgressDialog mProcessDlg = null;
    double lat,lon;

    String ip = "http://192.168.3.240";

    EditText edit3;
    SimpleDateFormat sdtAll = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat sdt = new SimpleDateFormat("HH:mm");
    SimpleDateFormat sdtY = new SimpleDateFormat("yyyy");
    //SimpleDateFormat sdtM = new SimpleDateFormat("MM月dd日");
    SimpleDateFormat sdtM1 = new SimpleDateFormat("MM");
    SimpleDateFormat sdtD1 = new SimpleDateFormat("dd");
    //SimpleDateFormat sdt2 = new SimpleDateFormat("ddMMyy");
    Date d = new Date();
    TextView t,t17,t19,t20;
    String adr,car_color,car_box,car_mark,upload_path,carNum,szlocation = "Lat:0.0" + " Lon:0.0",findin,findout,gps_box;

    String car_type = "01 自小客";
    String[] car_TypeA = car_type.split(" ");

    String path = "";
    String szBillStatus = "1";
    Geocoder gc;
    List<Address> address = null;

    Calendar calendar;
    Calendar termCalendar;
    Calendar billingCalendar;
    Calendar nowCalendar;

    boolean isMili = false;
    boolean isTemp = false;
    boolean checkcarno = false;

    Bundle bundle = new Bundle();

    Button btn10,btn11,btn12,btn19,btn23,bt22;
    String billingNumber,billingNumber1,car_boxB,road5 = "A中山 A117";
    String saved = "", saveb = "";
    String writedata = "",writedata1 = "";
    String[] userNum,time,car_boxA,CurrentArraryList,road5A;

    //Bluetooth 變數
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  //註冊廣播
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    private static BluetoothDevice device = null;
    BluetoothSocket socket = null;
    private OutputStream output = null;
    private BluetoothPrint btp = new BluetoothPrint();
    bt_socket btsocket = new bt_socket();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        mgr = (LocationManager)getSystemService(LOCATION_SERVICE);
        gc = new Geocoder(Start.this, Locale.getDefault());

        handler.removeCallbacks(uptime); //設定定時要執行的方法
        handler.postDelayed(uptime,0);  //更新時間

        btn10 = (Button)findViewById(R.id.button10);
        btn11 = (Button)findViewById(R.id.button11);
        btn12 = (Button)findViewById(R.id.button12);
        btn19 = (Button)findViewById(R.id.button19);
        btn23 = (Button) findViewById(R.id.button23);
        bt22 = (Button)findViewById(R.id.button22);
        btn10.setText(car_type);

        edit3 = (EditText)findViewById(R.id.editText3);
        edit3.setInputType(InputType.TYPE_NULL);

        t = (TextView)findViewById(R.id.textView3);
        t19 = (TextView)findViewById(R.id.textView19);
        t20 = (TextView)findViewById(R.id.textView20);
        t17 = (TextView)findViewById(R.id.textView17);
        handler.removeCallbacks(uptime);
        handler.postDelayed(uptime,5000);

        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if(mNetworkInfo == null){
            startActivity(new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS));
        }

        registerReceiver(receiver,filter);

        InitBlueTooth();
        setBillingNumber();
        RollBack();
        nStatus = 0;

    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {  //Bluetooth配對
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()){
                    case BluetoothDevice.BOND_BONDING:
                        Toast.makeText(Start.this,"正在配對...",Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    private Runnable uptime = new Runnable() {
        @Override
        public void run() {    //時間自動更新
            list = new ArrayList();
            handler.postDelayed(this,1000);
            Date d = new Date();
            SimpleDateFormat time = new SimpleDateFormat("HH:mm");
            t.setText("時間:" + time.format(d));
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try{
            unregisterReceiver(receiver);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void bt_gps(View v){ //GPS

        //lat = 23.498068805000003;
        //lon = 120.45109330999999;

        intent.setClass(this,GPS_Search.class);
        bundle.putDouble("Lat",lat);
        bundle.putDouble("Lon",lon);
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
        bt22.setBackgroundResource(R.drawable.baseline_room_white);
        Toast.makeText(Start.this,"Lat:" + lat + "Lon:" + lon,Toast.LENGTH_LONG).show();
    }

    public void edit_carNum(View v){  //輸入車牌
        intent.setClass(this,CarNum_Input.class);
        startActivityForResult(intent,6);
    }

    public void bt_new(View v){   //新筆資料

        int nSaveOK = 0;

        File dir = new File(Environment.getExternalStorageDirectory() + "/Park_jy/" + sdtAll.format(d));
        if(!dir.exists()){
            dir.mkdirs();
        }
        if (nStatus == 1){
            clearAll();
            setBillingNumber();
        }else if(isComplete()){
            if(CheckcarNum(edit3.getText().toString(),btn23.getText().toString()) && (nStatus != 2)){
                new AlertDialog.Builder(Start.this).setTitle("注意重複開單")
                        .setMessage("檢查重複開單")
                        .setIcon(R.drawable.info).setPositiveButton("確認",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialoginterface,int i)
                    {
                        clearAll();
                        setBillingNumber();
                    }
                }).show();
                return ;
            }
            nSaveOK = (nStatus == 2) ? savepage(true,nTrueId) : savepage(false,0);
            SendData();

            if (nSaveOK != 1)
            {
                new AlertDialog.Builder(Start.this).setTitle("檔案保存")
                        .setMessage(
                                (nSaveOK < 0) ? "非值班時段，不能開單或更改" : "檔案保存失敗，請檢查")

                        .setIcon(R.drawable.info).setPositiveButton("確認", null)
                        .show();
                return;
            }

            new AlertDialog.Builder(Start.this).setTitle("檔案保存").setMessage("檔案保存成功").setIcon(R.drawable.ok).setPositiveButton("確認",null).show();
            if(nStatus != 2){
                getIdx(true);
            }

            clearAll();
            setBillingNumber();

        }else{
            new AlertDialog.Builder(Start.this).setTitle("檔案保存").setMessage("資料不完整，保存？").setIcon(R.drawable.info)
                    .setPositiveButton("保存",new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialoginterface,int i)
                        {
                            savepage(false, 0);
                            clearAll();
                            //setBillingNumber();
                            //SendData();
                        }
                    })
                    .setNeutralButton("清空",new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialoginterface,int i)
                        {
                            clearAll();
                            setBillingNumber();
                        }
                    }).setNegativeButton("返回",null).show();
        }

    }

    private boolean isComplete(){  //判斷格號、車種、顏色、廠牌是否為空
        if(car_box != null && car_type != null && carNum != null && car_color != null && car_mark != null && car_box != "" && car_type != "" && carNum != "" && car_color != "" && car_mark != ""){
            return true;
        }else if(gps_box != null && car_type != null && carNum != null && gps_box != "" && car_type != "" && carNum != ""){
            return true;
        }else{
            return false;
        }
    }

    public void pageUp(View v){   //上頁
        Inventory(CurrentArraryList,--nCurrentId);
        if(nCurrentId < 0){
            nCurrentId = 0;
        }
    }

    public void pageDown(View v){   //下頁
        Inventory(CurrentArraryList,++nCurrentId);
        if(nCurrentId >= nCount){
            nCurrentId = nCount - 1;
        }
    }

    public void bt_search(View v){  //搜尋
        getFilename();
        String getpath = Environment.getExternalStorageDirectory() + "/Park_jy/" + sdtAll.format(d) + "/" + writedata1;
        intent.setClass(Start.this,FileList.class);
        bundle.putString("FILES_PATH","*");
        bundle.putString("SEARCH_FILE",getpath);
        bundle.putString("ADDR_SPACE",btn23.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent,9);
    }

    public void bt_Count(View v){  //照片冊
        String szPath = Environment.getExternalStorageDirectory() + "/Park_jy/" + "photo/" + Commin.getDate(calendar,false);
        bundle.putString("PATH",szPath);
        bundle.putString("CALE",Commin.getDate(calendar,false));
        bundle.putString("USER",billingNumber);
        intent.setClass(Start.this, ImageViewer.class);
        intent.putExtras(bundle);
        startActivityForResult(intent,11);
    }

    public void bt_tp(View v){  //拍照
        intent.setClass(this,park_cam.class);
        bundle.putString("billNumber",billingNumber);
        bundle.putInt("photoCount",photoCount);
        intent.putExtras(bundle);
        startActivityForResult(intent,5);
    }

    private void ScanDevice(){  //Bluetooth搜尋設備
        intent.setClass(Start.this,start_btdevice.class);
        startActivityForResult(intent,10);
    }

    public void bt_back(View v){ //返回
        if((nStatus == 0)&&(edit3.getText().toString().length() > 2))
        {
            new AlertDialog.Builder(Start.this).setTitle("退出").setMessage("檔案未存檔，退出？").setIcon(R.drawable.info)
                    .setPositiveButton("確認",
                            new DialogInterface.OnClickListener()
                            {
                                public void onClick(DialogInterface dialoginterface,int i)
                                {
                                    finish();
                                }
                            })
                    .setNegativeButton("取消",null).show();
        }else{
            finish();
        }
    }

    public void bt_addtime(View v){  //累加時間
        if(btn23.getText().toString().equals(""))
        {
            Toast.makeText(Start.this, "請先設定格位", Toast.LENGTH_LONG).show();
        }
        else if(btn10.getText().toString().equals(""))
        {
            Toast.makeText(Start.this, "請先設定車種", Toast.LENGTH_LONG).show();
        }
        else
        {
            intent.setClass(Start.this, Cumulative.class);
            bundle.putString("BILLING_TIME", Commin.getHoursAndMinute(calendar));
            bundle.putInt("TYPE", Integer.valueOf(car_boxA[1]));
            bundle.putInt("GG", Integer.valueOf(car_boxA[2]));
            bundle.putInt("STATUS", Integer.valueOf(szBillStatus));
            bundle.putString("CARTYPE", car_TypeA[0]);
            intent.putExtras(bundle);
            startActivityForResult(intent,7);
        }
    }

    public void bt_accumulative(View v){ //統計
        path = Environment.getExternalStorageDirectory() + "/Park_jy/" + Commin.getDate(calendar,false);
        intent.setClass(Start.this, Total.class);
        bundle.putString("USER_ID", userNum[0]);
        bundle.putString("FILES_PATH", path);
        bundle.putString("YYYYMMDD", Commin.getDate(calendar,false));
        intent.putExtras(bundle);

        startActivity(intent);
    }

    public void bt_box(View v){  //格號
        intent.setClass(this,Road_list.class);
        bundle.putInt("ROAD",RoadNum);
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
    }

    public void bt_type(View v){  //車種
        intent.setClass(this,Car_type.class);
        startActivityForResult(intent,2);
    }

    public void bt_color(View v){ //顏色
        intent.setClass(this,Car_Color.class);
        startActivityForResult(intent,3);
    }

    public void bt_mark(View v){ //廠牌
        intent.setClass(this,Car_mark.class);
        startActivityForResult(intent,4);
    }


    public void bt_print(View v){  //列印
        mProcessDlg = ProgressDialog.show(Start.this,"列印中...", "列印中，請稍候...",true);
        Thread td = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    if(nStatus == 0){
                        if(car_box == null || car_type == null || carNum == null || car_color == null || car_mark == null || car_box == "" ||car_type == ""|| carNum == "" || car_color == "" || car_mark == ""){
                            new AlertDialog.Builder(Start.this).setTitle("檔案保存").setMessage("檔案不完整，請確認").setIcon(R.drawable.ok).setPositiveButton("確認",new DialogInterface.OnClickListener(){
                                public void onClick(DialogInterface dialoginterface,int i)
                                {
                                    return;
                                }
                            }).show();
                        }
                        savepage(false, 0);
                        getIdx(true);
                        nStatus = 1;
                    }
                    getFilename();
                    boolean b60Min = false;
                    Calendar nowCalendar = Calendar.getInstance();
                    carNum = edit3.getText().toString();
                    if(!Commin.isWorkTime(saveb,nowCalendar))
                    {
                        Toast.makeText(Start.this, "非值班時段，不能印單", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if(btsocket.getSocket() != null){
                        try {
                            output = btsocket.getSocket().getOutputStream();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        btp.InitPrinter(output);

                        btp.PrintChangeLine(output,5);
                        btp.PrintBarCode(output,Commin.getDate(termCalendar,true).substring(1,7) + "207",false);

                        btp.PrintChangeLine(output,1);

                        //車牌
                        boolean bMT = (carNum.startsWith("軍")||carNum.startsWith("臨"));
                        btp.PrintString(output,"        " + ((!bMT)?(isMili?"軍 ":(isTemp?"臨 ":"")):"") + carNum);
                        btp.PrintChangeLine(output,1);

                        //路段、格號
                        if(car_boxA[0].length() == 5){
                            car_boxA[0] = car_boxA[0].substring(1,5);
                        }
                        btp.PrintString(output,"        " + car_boxA[0] + " " + car_boxA[3]);
                        btp.PrintChangeLine(output,1);

                        btp.PrintString(output,"        " + String.format("%s年 %s月 %s日", Commin.getDate(calendar,true).substring(0, 3),
                                Commin.getDate(calendar,true).substring(3, 5),Commin.getDate(calendar,true).substring(5, 7)));
                        btp.PrintChangeLine(output,1);

                        //單號2
                        btp.PrintBarCode(output,billingNumber,false);
                        //btp.PrintChangeLine(output,1);

                        btp.PrintString(output,"        " + String.format("%s    %s    %s", Commin.getDate(termCalendar,true).substring(0, 3),
                                Commin.getDate(termCalendar,true).substring(3, 5),Commin.getDate(termCalendar,true).substring(5, 7)));
                        btp.PrintChangeLine(output,1);

                        btp.PrintChangeLine(output,3);  //def:2;1:3lines;

                        nowCalendar = (Calendar)calendar.clone();
                        int nHour = calendar.get(Calendar.HOUR_OF_DAY);
                        for(int i=0; i < 4; i++){
                            if(!Commin.isWorkTime(saveb,nowCalendar)){
                                break;
                            }
                            String szList = (0==i)?String.format(" %02d:%02d%5d     %s", nHour,nowCalendar.get(Calendar.MINUTE),expenses,userNum[1]):
                                    String.format(" %02d:%02d%5s    %s", nHour+(b60Min?1:0),b60Min?0:(nowCalendar.get(Calendar.MINUTE)+1)," ","________");
                            if(Integer.parseInt(car_boxA[2]) == 3){
                                if(Integer.valueOf(car_TypeA[0]) == 12){
                                    if(i==0){
                                        szList = String.format(" %02d:%02d%5d     %s", nHour,nowCalendar.get(Calendar.MINUTE),expenses,userNum[1]);
                                    }
                                    else if(i==1){
                                        szList = String.format(" %02d:%02d%5s    %s", nHour+(b60Min?1:0),b60Min?0:(nowCalendar.get(Calendar.MINUTE)+1),expenses,"________");
                                    }
                                    else{
                                        szList = String.format(" %02d:%02d%5s    %s", nHour+(b60Min?1:0),b60Min?0:(nowCalendar.get(Calendar.MINUTE)+1)," ","________");
                                    }
                                }else if(Integer.valueOf(car_TypeA[0]) == 13){
                                    szList = (0==i)?String.format(" %02d:%02d%5d     %s", nHour,nowCalendar.get(Calendar.MINUTE),expenses,userNum[1]):
                                            String.format(" %02d:%02d%5s    %s", nHour+(b60Min?1:0),b60Min?0:(nowCalendar.get(Calendar.MINUTE)+1),expenses,"________");
                                }
                            }
                            nowCalendar.add(Calendar.MINUTE,(int)(hour*60));
                            nHour = nowCalendar.get(Calendar.HOUR_OF_DAY);

                            if(nowCalendar.get(Calendar.MINUTE) == 59){
                                b60Min = true;
                            }else {
                                b60Min = false;
                            }
                            btp.PrintString(output,szList);
                            btp.PrintChangeLine(output,1);
                        }
                        btp.ToBlackMark(output);
                        SendData();
                    }else{
                        Toast.makeText(Start.this, "印表機連接失敗，請重新連接", Toast.LENGTH_LONG).show();
                        ScanDevice();
                        return;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                mProcessDlg.dismiss();
            }
        });
        td.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        /*if(device == null){
            ScanDevice();
        }*/
        switch (requestCode){
            case 1: //格位
                if(resultCode == RESULT_OK){
                    road5 = rL.listRoad.get(Road_list.tab.getSelectedTabPosition()).toString();
                    RoadNum = Road_list.tab.getSelectedTabPosition();
                    postion_box = data.getIntExtra("選項",postion_box);
                    car_box = data.getStringExtra("車格");
                    gps_box = data.getStringExtra("GPS車格");
                    if(car_box.split(" ").length > 1 ){
                        car_boxB = car_box.split(" ")[0] + " " + car_box.split(" ")[7] + " " + car_box.split(" ")[5] + " " + car_box.split(" ")[3];
                    }
                    if(car_box != null && car_boxB != null){
                        car_boxA = car_boxB.split(" ");
                        if(car_boxA[0].length() == 5){
                            car_boxA[0] = car_boxA[0].substring(1,5);
                        }
                        /*if(car_boxA[0].equals("{data=有車") || car_boxA[0].equals("{data=無車")){
                            btn23.setText(car_boxA[1]);
                            t19.setText("時數:");
                            t20.setText("停車費:");
                            //t.setText("時間:" + car_boxA[14].substring(7));
                        }else{

                        }*/
                        btn23.setText(car_boxA[0]);
                        setHours();
                    }else if(gps_box != null){
                        gps_boxA = gps_box.split(" ");
                        btn23.setText(gps_boxA[0]);
                        setGpsHours();
                    }else{
                        btn23.setText(null);
                    }
                    if(nStatus > 0){
                        nStatus = 2;
                    }
                }
                break;
            case 2: //車種
                if(resultCode == RESULT_OK){
                    car_type = data.getStringExtra("Car_TYPE");
                    car_TypeA = car_type.split(" ");
                    btn10.setText(car_type);
                    if(car_box != null){
                        //setHours();
                    }
                    if(nStatus > 0){
                        nStatus = 2;
                    }
                }
                break;
            case 3:  //顏色
                if(resultCode == RESULT_OK){
                    car_color = data.getStringExtra("Car_Color");
                    btn11.setText(car_color);

                    if(nStatus > 0){
                        nStatus = 2;
                    }
                }
                break;
            case 4:  //廠牌
                if(resultCode == RESULT_OK){
                    car_mark = data.getStringExtra("Car_MARK");
                    btn12.setText(car_mark);

                    if(nStatus > 0){
                        nStatus = 2;
                    }
                }
                break;
            case 5: //照片
                if(resultCode == RESULT_OK){
                    photoCount += 1;
                    btn19.setText(String.valueOf(photoCount));

                    if(nStatus != 0){
                        savepage(true,nTrueId);
                    }
                }
                break;
            case 6:   //黑名單
                if(resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                    if(bundle != null){
                        String temp = "";
                        carNum = bundle.getString("ITEM");
                        isMili = bundle.getBoolean("ISMILI");
                        isTemp = bundle.getBoolean("ISTEMP");
                        if(isMili){
                            temp += "軍 ";
                        }
                        if(isTemp){
                            temp += "臨";
                        }
                        temp += carNum;
                        edit3.setText(temp);
                        if (isBadCar(temp)) {
                            new AlertDialog.Builder(Start.this).setTitle("抓到了~")
                                    .setMessage("車牌:" + temp + "在舉發車名單中")
                                    .setIcon(R.drawable.info).setPositiveButton("確認", null).show();
                        }
                        //CheckControlCar(carNum);
                        Search(carNum);
                    }

                }
                break;
            case 7:  //累加時間
                if(resultCode == RESULT_OK){
                    getFilename();
                    Bundle getBundle = data.getExtras();
                    if(getBundle != null){
                        expenses = getBundle.getInt("EXPENSES");
                        count = getBundle.getInt("COUNT");
                        szBillStatus = String.format("%d",getBundle.getInt("BILL_STATUS"));
                        t19.setText("時數:" + String.valueOf(hour * count));
                        t20.setText("停車費:" + String.valueOf(expenses * count));
                        if(Integer.parseInt(car_boxA[2]) == 3){
                            if(Integer.valueOf(car_TypeA[0]) == 12){
                                if(Integer.parseInt(car_boxA[1]) == 1){
                                    expenses = ((hour * count)<=2)?0:10;
                                    t20.setText("停車費:" + String.valueOf(expenses * (count-2)));
                                }else if(Integer.parseInt(car_boxA[1]) == 2){
                                    expenses = ((hour * count) <= 2)?0:15;
                                    t20.setText("停車費:" + String.valueOf(expenses * (count - 4)));
                                }
                            }
                            if(Integer.valueOf(car_TypeA[0]) == 13){
                                if(Integer.parseInt(car_boxA[1]) == 1){
                                    expenses = ((hour * count)<=4)?0:10;
                                    t20.setText("停車費:" + String.valueOf(expenses * (count - 4)));
                                }else if(Integer.parseInt(car_boxA[1]) == 2){
                                    expenses = ((hour * count)<=4)?0:15;
                                    t20.setText("停車費:" + String.valueOf(expenses * (count - 8)));
                                }
                            }
                        }
                        savepage(true,nTrueId);
                        CurrentArraryList = Commin.readTXT(path +"/"+ writedata1,"\n");
                    }
                }
                break;
            case 8: //清冊
                if(resultCode==RESULT_OK)
                {
                    Bundle getBundle = data.getExtras();
                    if (getBundle == null)
                        break;
                    String[] szTempArray = getBundle.getStringArray("INVENTORY");
                    int nIdx	 = getBundle.getInt("INVENTOR2");
                    szFileList = getBundle.getStringArrayList("FILE_LIST");
                    nCount = szFileList.size();//szTempArray.length;
                    //	Toast.makeText(Start.this,String.valueOf(nIdx), Toast.LENGTH_LONG).show();
                    Inventory(szTempArray,nIdx);
                }
                break;

            case 9: //搜尋
                if(resultCode == RESULT_OK){
                    Bundle getbundle = data.getExtras();
                    if(getbundle == null){
                        break;
                    }
                    int tempkey = getbundle.getInt("positionid");
                    String[] szTempArray = getbundle.getStringArray("INVENTORY");
                    int nIdx = getbundle.getInt("INVENTORY2");
                    szFileList = getbundle.getStringArrayList("FILE_LIST");
                    listingFiles();
                    nCount = szFileList.size();
                    Inventory(szTempArray,tempkey);
                }
                break;
            case 10: //Bluetooth
                if(resultCode == RESULT_OK){
                    String add = data.getExtras().getString(start_btdevice.EXTRA_DEVICE_ADDRESS);
                    device = adapter.getRemoteDevice(add);
                }
                break;
            case 11: //
                if(resultCode == RESULT_OK){

                }
                break;
        }
    }

    private void getFilename(){  //檔案路徑
        if(getIntent().getStringExtra("Morning") != null){
            writedata = "A" + userNum[0] + "-" + sdtAll.format(d);
            saved = "A";
            saveb = "A";
        }else if(getIntent().getStringExtra("Night") != null){
            writedata = "B" + userNum[0] + "-" + sdtAll.format(d);
            saved = "B";
            saveb = "B";
        }
        writedata1 = writedata + ".txt";
        upload_path = Environment.getExternalStorageDirectory() + "/Park_jy/" + "upload/";
    }

    private int savepage(boolean bUpdate, int nLineIdx){  //存檔
        Calendar nowCalendar = Calendar.getInstance();
        getFilename();
        if(!Commin.isWorkTime(saveb,nowCalendar))
        {
            Toast.makeText(Start.this, "非值班時段，不能開單或更改", Toast.LENGTH_LONG).show();
            return -1;
        }

        //sdtAll.format(d);
        saved = saved + userNum[0] + ";" + billingNumber + ";" + Commin.getDate(termCalendar,false) + ";" + sdt.format(d) + ";" + road5 + ";" + car_boxB + ";" + car_type + ";";
        String SaveData2 = edit3.getText().toString() + ";" + car_color + ";" + car_mark + ";" + (hour * count) + ";";

        path = Environment.getExternalStorageDirectory() + "/Park_jy/" + sdtAll.format(d) + "/";

        if(isMili){
            saved += "軍";
        }
        if(isTemp){
            saved += "臨";
        }
        saved += SaveData2;

        if(Integer.parseInt(car_boxA[2]) == 3){
            if(Integer.valueOf(car_TypeA[0]) == 12){
                if(Integer.parseInt(car_boxA[1]) == 1){ //政府殘障車停殘障格兩小時免費 小時計費
                    expenses = ((hour * count)<=2)?0:10;
                    saved += (expenses * (count-2)) + ";";
                }else if(Integer.parseInt(car_boxA[1]) == 2){  //政府殘障車停殘障格兩小時免費 半小時計費
                    expenses = ((hour * count)<=2)?0:15;
                    saved += (expenses * (count * 4)) + ";";
                }
            }else if(Integer.valueOf(car_TypeA[0]) == 13){
                if(Integer.parseInt(car_boxA[1]) == 1){
                    expenses = ((hour * count) <= 4)?0:10; //政府殘障車停殘障格4小時免費 小時計費
                    saved += (expenses *(count - 4)) + ";";
                }else if(Integer.parseInt(car_boxA[1]) == 2){ //政府殘障車停殘障格4小時免費 半小時計費
                    expenses = ((hour * count) <= 4)?0:15;
                    saved += (expenses * (count - 8)) +  ";";
                }
            }else{
                saved += (expenses * count) + ";";  //停殘障格但不是殘障車
            }
        }else{
            saved += (expenses * count) + ";";
        }
        saved += szlocation + ";";  //座標
        saved += szBillStatus + ";";
        saved += photoCount + ";\n"; //照片數量
        try {
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path,true),"UTF-8");

            out.write(saved);

            //out.write("\n");
            out.flush();
            out.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(bUpdate){
            Commin.updateTXT(path + writedata1,billingNumber,saved);
            Commin.writeTXT(upload_path,billingNumber + ".txt",saved);
        }else{
            Commin.writeTXT(path,writedata1,saved);
            Commin.writeTXT(upload_path,billingNumber + ".txt",saved);
        }

        BillsBackup(path,writedata,writedata1);

        return 1;
    }

    private void BillsBackup(String szPath,String szName,String szBack){
        File fBills =  new File(szPath+szName);
        File fBack  =  new File(szPath+szBack);

        if(!fBills.isFile()){
            return;
        }

        try
        {
            Commin.FileBackup(fBills, fBack);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private void RollBack()
    {
        getFilename();

        File fBills = new File(path+writedata1);
        File fBack  = new File(path+writedata);

        if(fBills.isFile() && (fBills.length()==0))
        {
            try
            {
                Commin.FileBackup(fBack, fBills);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    private void clearAll(){  //清除
        car_box = "";
        btn23.setText(car_box);

        carNum = "";
        edit3.setText(carNum);

        car_color = "";
        btn11.setText(car_color);

        car_mark = "";
        btn12.setText(car_mark);

        car_type = "01 自小客";
        btn10.setText(car_type);
        car_TypeA = car_type.split(" ");

        t.setText("時間:");

        count = 1;
        t19.setText("時數:" + String.valueOf(hour * count));
        t20.setText("停車費:" + String.valueOf(expenses * count));

        if(car_box != null && !car_box.equals("")){
            if(Integer.parseInt(car_boxA[5]) == 3 || car_boxA[2].equals("")){
                if(Integer.valueOf(car_TypeA[0]) == 12 || car_TypeA[0].equals("")){
                    t20.setText("0");
                }
                if(Integer.valueOf(car_TypeA[0]) == 13 || car_TypeA[0].equals("")){
                    t20.setText("0");
                }
            }
        }else if(gps_box != null){
            if(Integer.parseInt(gps_boxA[2]) == 3){
                if(Integer.valueOf(car_TypeA[0]) == 12 || car_TypeA[0].equals("")){
                    t20.setText("0");
                }
                if(Integer.valueOf(car_TypeA[0]) == 13 || car_TypeA[0].equals("")){
                    t20.setText("0");
                }
            }
        }
        photoCount = 0;
        btn19.setText(String.valueOf(photoCount));

        nStatus      = 0;
        szBillStatus = "1";
    }

    @Override
    protected void onSaveInstanceState(Bundle saved){
        super.onSaveInstanceState(saved);
        saved.putString("Car_box",car_box);
        saved.putString("Car_type",car_type);
        saved.putString("Car_color",car_color);
    }

    @Override
    protected void onResume() {
        super.onResume();
        adr = LocationManager.GPS_PROVIDER;
        if(adr != null){
            mgr.requestLocationUpdates(adr,500,1,this);
        }else{
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        mgr.removeUpdates(this);

    }

    @Override
    public void onLocationChanged(Location location) {   //當GPS位置變更
        try {
            address = gc.getFromLocation(location.getLatitude(),location.getLongitude(),1);
        } catch (IOException e) {

            e.printStackTrace();
        }

        //addr = "\n" + address.get(0).getAddressLine(0);
        if(location != null){
            lat = location.getLatitude();
            lon = location.getLongitude();
            szlocation = "Lat:" + location.getLatitude() + "Lon:" + location.getLongitude();
            //Toast.makeText(Start.this,"Lat:" + lat + "Lon:" + lon,Toast.LENGTH_LONG).show();
        }else{
            szlocation = "Lat:0.0" + " Lon:0.0";
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Criteria criteria = new Criteria(); //選擇最好的方式定位
        adr = mgr.getBestProvider(criteria,true);
    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
    }

    public void bt_inventory(View v){  //清冊
        getFilename();
        String pathInv = path + "/" +writedata1;
        intent.setClass(Start.this, FileList.class);
        bundle.putString("FILES_PATH", pathInv);
        bundle.putString("SEARCH_FILE", "*");
        bundle.putString("ADDR_SPACE","");
        intent.putExtras(bundle);
        startActivityForResult(intent,8);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_BACK){
            finish();
        }
        return true;
    }

    private void setBillingNumber(){   //單號產生
        String tof = "";
        calendar = Calendar.getInstance();
        termCalendar = Calendar.getInstance();

        termCalendar.add(Calendar.DATE, 19);
        billingNumber1 = String.valueOf(termCalendar.get(Calendar.YEAR) - 11).substring(2);
        if(String.valueOf(termCalendar.get(Calendar.MONTH)+1).length() == 1)
            billingNumber1 += "0";
        billingNumber1 += String.valueOf(termCalendar.get(Calendar.MONTH) + 1);
        if(String.valueOf(termCalendar.get(Calendar.DATE)).length() == 1)
            billingNumber1 += "0";
        billingNumber1 += String.valueOf(termCalendar.get(Calendar.DATE));
        billingNumber1 += "207";

        userNum = getIntent().getStringExtra("PU").split(",");
        sNum = getIdx(false);

        if(userNum[0].length() > 2){
            tof = userNum[0].substring(1,2) + userNum[0].substring(2,3);
        }else{
            tof = userNum[0];
        }
        billingNumber = tof;
        billingNumber += Commin.getTwoNumber(calendar.get(Calendar.YEAR) - 1911);
        billingNumber += Commin.getOneNumber(calendar.get(Calendar.MONTH) + 1);
        billingNumber += Commin.getOneNumber(calendar.get(Calendar.DATE));

        sNum %= 1000;
        if(sNum < 100){
            billingNumber += "0";
        }
        if(sNum < 10){
            billingNumber += "0";
        }
        billingNumber += String.valueOf(sNum);
        billingNumber += Commin.check(billingNumber1,billingNumber);
        t17.setText("單號:" + billingNumber);
    }

    private int getIdx(boolean bUpdate)
    {
        path = Environment.getExternalStorageDirectory() + "/Park_jy/" + Commin.getDate(calendar,false);

        /*if(getIntent().getStringExtra("Morning") != null){
            wirtedata = "A" + userNum[0] + "-" + sdtAll.format(d) + ".txt";
            saved = "A";
        }else if(getIntent().getStringExtra("Night") != null){
            wirtedata = "B" + userNum[0] + "-" + sdtAll.format(d) + ".txt";
            saved = "B";
        }*/

        int nIdx = 1;
        String szPath = path+"/"+userNum[0];

        File temp = new File(szPath);

        if(!temp.isFile())
        {
            Commin.writeTXT(path,"/"+userNum[0],"1");
        }

        nIdx = Integer.parseInt(Commin.readTXT(szPath,"\n")[0]);

        if(bUpdate)
        {
            ++nIdx;
            Commin.updateTXT(szPath, "00", String.valueOf(nIdx));
        }

        return nIdx;
    }

    private boolean isBadCar(String plt) {
        try {
            //String[] badCars = Commin.readTXT(getString(R.string.sysData_path) + getString(R.string.BadCar_txt), "\n");
            /*for (String badCar : badCars) {
                if (badCar.trim().equals(plt.trim()))
                    return true;
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean CheckcarNum(String carNo, String staddr){
        checkcarno=false;
        billingCalendar = Calendar.getInstance();
        nowCalendar = Calendar.getInstance();


        getFilename();
        String  szFilePath = path + writedata1;


        File tmpFile = new File(szFilePath);

        if(!tmpFile.isFile()){
            checkcarno=false ;
            return checkcarno;
        }
        String[] arrayCars = Commin.readTXT(szFilePath, "\n");

        for(int i=0; i<arrayCars.length; ++i)
        {
            String[] arrayItem = arrayCars[i].split(";");

            if(arrayItem.length < 13)
                continue;

            if(arrayItem.length < 12)
                continue;
            String[] szTmpSpace = arrayItem[5].split(" ");
            String[] szTmpcarno = arrayItem[7].split(" ");
            String[] szTmptime = arrayItem[3].split(" ");

            if((0 == staddr.compareTo(szTmpSpace[0]) )&&(0 == carNo.compareTo(szTmpcarno[0]))){


                billingCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(szTmptime[0].toString().substring(0, 2)));
                billingCalendar.set(Calendar.MINUTE, Integer.valueOf(szTmptime[0].toString().substring(3)));
                if(Integer.parseInt(car_boxA[5]) == 1){

                    billingCalendar.add(Calendar.MINUTE, 60);

                    if (billingCalendar.before(nowCalendar)){
                        checkcarno=false ;
                    }else{
                        checkcarno=true ;
                    }
                }else{
                    billingCalendar.add(Calendar.MINUTE, 30);

                    if (billingCalendar.before(nowCalendar)){
                        checkcarno=false ;
                    }else{
                        checkcarno=true ;
                    }
                }
            }
        }
        return checkcarno;
    }

    private void CheckControlCar(String szCarNo)  //檢查是否為管制車輛
    {
        String szFilePath   = Environment.getExternalStorageDirectory() + "/Park_JY/" + "ControlCar.TXT";
        String[] szCarArray = Commin.readTXT(szFilePath, "\r\n");

        for(int i=0;i<szCarArray.length;++i)
        {
            if(szCarNo.compareTo(szCarArray[i].split("  ")[0]) == 0)
            {
                new AlertDialog.Builder(Start.this).setTitle("管制車輛").setMessage(
                        szCarArray[i].split("  ")[1]).setIcon(R.drawable.info).setPositiveButton(
                        "確認", null).show();
                break;
            }
        }
    }

    private void setGpsHours()
    {
        if(Integer.parseInt(gps_boxA[1]) == 1 || Integer.parseInt(gps_boxA[1]) == 1)
        {
            hour = 1;
            try
            {
                if((Integer.valueOf(car_TypeA[0]) == 12) || (Integer.valueOf(car_TypeA[0]) == 13) || (Integer.valueOf(car_TypeA[0]) == 14))
                    expenses =10;
                else if(Integer.valueOf(car_TypeA[0]) == 6 ||
                        Integer.valueOf(car_TypeA[0]) == 7 ||
                        Integer.valueOf(car_TypeA[0]) == 8 ||
                        Integer.valueOf(car_TypeA[0]) == 11)
                    expenses =40;
                else
                    expenses =20;
            }
            catch(Exception e)
            {
                expenses =20;
            }
            fee = expenses * count;
            t20.setText("停車費:" + String.valueOf(fee));
            if(Integer.parseInt(gps_boxA[1]) == 3){
                if(Integer.valueOf(car_TypeA[0]) == 12){
                    expenses = ((hour * count)<=2)?0:10;
                    fee = expenses * (count-2);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
                if(Integer.valueOf(car_TypeA[0]) == 13){
                    expenses = ((hour * count)<=4)?0:10;
                    fee = expenses * (count-4);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
            }
        }
        else if(Integer.parseInt(gps_boxA[1]) == 2)
        {
            hour = 0.5;
            try
            {
                if((Integer.valueOf(car_TypeA[0]) == 12) || (Integer.valueOf(car_TypeA[0]) == 13) || (Integer.valueOf(car_TypeA[0]) == 14))
                    expenses =15;
                else if(Integer.valueOf(car_TypeA[0]) == 6 ||
                        Integer.valueOf(car_TypeA[0]) == 7 ||
                        Integer.valueOf(car_TypeA[0]) == 8 ||
                        Integer.valueOf(car_TypeA[0])== 11)
                    expenses =50;
                else
                    expenses =25;
            }
            catch(Exception e)
            {
                expenses =25;
            }
            fee = expenses * count;
            t20.setText("停車費:" + String.valueOf(fee));
            if(Integer.parseInt(gps_boxA[2]) == 3){
                if(Integer.valueOf(car_TypeA[0]) == 12){
                    expenses = ((hour * count)<=2)?0:15;
                    fee = expenses * (count-4);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
                if(Integer.valueOf(car_TypeA[0]) == 13){
                    expenses = ((hour * count)<=4)?0:15;
                    fee = expenses * (count-8);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
            }
        }
        fee_time = hour * count;
        t19.setText("時數:" + String.valueOf(fee_time));

    }

    private void setHours()
    {
        if(Integer.parseInt(car_boxA[1]) == 1)
        {
            hour = 1;
            try
            {
                if((Integer.valueOf(car_TypeA[0]) == 12) || (Integer.valueOf(car_TypeA[0]) == 13) || (Integer.valueOf(car_TypeA[0]) == 14))
                    expenses =10;
                else if(Integer.valueOf(car_TypeA[0]) == 6 ||
                        Integer.valueOf(car_TypeA[0]) == 7 ||
                        Integer.valueOf(car_TypeA[0]) == 8 ||
                        Integer.valueOf(car_TypeA[0]) == 11)
                    expenses =40;
                else
                    expenses =20;
            }
            catch(Exception e)
            {
                expenses =20;
            }
            fee = expenses * count;
            t20.setText("停車費:" + String.valueOf(fee));
            if(Integer.parseInt(car_boxA[2]) == 3){
                if(Integer.valueOf(car_TypeA[0]) == 12){
                    expenses = ((hour * count)<=2)?0:10;
                    fee = expenses * (count-2);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
                if(Integer.valueOf(car_TypeA[0]) == 13){
                    expenses = ((hour * count)<=4)?0:10;
                    fee = expenses * (count-4);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
            }
        }
        else if(Integer.parseInt(car_boxA[1]) == 2)
        {
            hour = 0.5;
            try
            {
                if((Integer.valueOf(car_TypeA[0]) == 12) || (Integer.valueOf(car_TypeA[0]) == 13) || (Integer.valueOf(car_TypeA[0]) == 14))
                    expenses =15;
                else if(Integer.valueOf(car_TypeA[0]) == 6 ||
                        Integer.valueOf(car_TypeA[0]) == 7 ||
                        Integer.valueOf(car_TypeA[0]) == 8 ||
                        Integer.valueOf(car_TypeA[0])== 11)
                    expenses =50;
                else
                    expenses =25;
            }
            catch(Exception e)
            {
                expenses =25;
            }
            fee = expenses * count;
            t20.setText("停車費:" + String.valueOf(fee));
            if(Integer.parseInt(car_boxA[2]) == 3){
                if(Integer.valueOf(car_TypeA[0]) == 12){
                    expenses = ((hour * count)<=2)?0:15;
                    fee = expenses * (count-4);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
                if(Integer.valueOf(car_TypeA[0]) == 13){
                    expenses = ((hour * count)<=4)?0:15;
                    fee = expenses * (count-8);
                    t20.setText("停車費:" + String.valueOf(fee));
                }
            }
        }
        fee_time = hour * count;
        t19.setText("時數:" + String.valueOf(fee_time));

    }

    private void Inventory(String[] szCarArray,int nIdx)
    {
        if((nIdx < 0)||((nCount-1) < nIdx))
            return;

        int nId = Integer.parseInt(szFileList.get(nIdx).substring(0,3))-1;

        String[] szItemArray = szCarArray[nId].split(";");

        if(szItemArray.length < 12)
        {
            nTrueId				= nId;
            nCurrentId			= nIdx;
            CurrentArraryList	= szCarArray;

            return;
        }
        //	SetBtnEnabled(false);

        billingNumber1 = szItemArray[1];							//單號1
        billingNumber = szItemArray[1];								//單號2
        //	serialNumber;												//流水號
        calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(szItemArray[3].substring(0,2)));										//開單時間
        calendar.set(Calendar.MINUTE,Integer.parseInt(szItemArray[3].substring(3,5)));										//開單時間

        //	private Calendar termCalendar;									//繳費期限
        termCalendar.set(Integer.parseInt(szItemArray[2].substring(0,4)),
                Integer.parseInt(szItemArray[2].substring(4,6))-1, Integer.parseInt(szItemArray[2].substring(6,8)));

        road5 = szItemArray[4];						//A中山路 A117
        road5A = road5.split(" ");
        car_box = szItemArray[5];						//A207 2 1 中山路4
        car_boxB = szItemArray[5];
        car_boxA  = car_box.split(" ");

        car_type = szItemArray[6];								//01 自小客
        car_TypeA = car_type.split(" ");

        carNum = szItemArray[7];                                       //123-456
        car_color  = szItemArray[8];										//01 咖啡
        car_mark  = szItemArray[9];										//03 三陽 (Honda)

        if(car_boxA.length > 1){
            if(Integer.parseInt(car_boxA[1]) == 1)
                hour = 1;
            else
                hour = 0.5;
        }else{
            if(car_boxA[0].substring(0,1).equals("A")){
                hour = 0.5;
            }else{
                hour = 1;
            }
        }

        count 	  = (int) (Double.parseDouble(szItemArray[10])/hour);	//hours * count = 時數

        if(count != 0){
            expenses  = Integer.parseInt(szItemArray[11])/count;			//expenses * count = 費用
        }
        szlocation = (szItemArray.length < 13)?"N/A":szItemArray[12];
        szBillStatus = (szItemArray.length < 14)?"1":szItemArray[13];

        photoCount   = (szItemArray.length < 15)?0:Integer.parseInt(szItemArray[14]);
        btn19.setText(String.valueOf(photoCount));

        t.setText("時間:" + szItemArray[3]);
        btn23.setText(car_boxA[0]);
        btn10.setText(car_type);
        btn11.setText(car_color);
        btn12.setText(car_mark);

        if(carNum.startsWith("軍"))					//軍用車
            isMili = true;
        else
            isMili = false;
        if(carNum.startsWith("臨"))					//臨時車
            isTemp = true;
        else
            isTemp = false;

        edit3.setText(carNum/*.substring(0, 2)*/);

        t19.setText("時數:" + String.valueOf(hour * count));
        t20.setText("停車費:" + String.valueOf(expenses * count));
        if(car_boxA.length > 1){
            if(Integer.parseInt(car_boxA[1]) == 3){
                if(Integer.valueOf(car_TypeA[0]) == 12){
                    t20.setText("停車費:" + String.valueOf(expenses * (count-2)));
                }
                if(Integer.valueOf(car_TypeA[0]) == 13){
                    t20.setText("停車費:" + String.valueOf(expenses * (count-4)));
                }
            }
        }

        boolean bCanceled = (Integer.parseInt(szBillStatus) == 0);
        t17.setText("單號:" +billingNumber+(bCanceled?" [注]":""));
        t17.setTextColor(bCanceled?android.graphics.Color.RED:android.graphics.Color.LTGRAY);

        nTrueId	= nId;
        nCurrentId = nIdx;
        CurrentArraryList = szCarArray;
        nStatus = 1;
    }

    public void SendData(){   //回傳資料
        getFilename();
        RequestParams params = new RequestParams();
        params.put(" record_grid",car_boxA[0]);
        params.put(" record_latitude",lat);
        params.put(" record_longitude",lon);

        AsyncHttpClient client = new AsyncHttpClient();
                client.post(ip + "/v1/vehicle/regulated?plt_no=" + carNum, params, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                        //Toast.makeText(Start.this,"上傳失敗",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, String s) {
                        //Toast.makeText(Start.this,"上傳成功 ",Toast.LENGTH_LONG).show();
                        if(s != null){
                            new AlertDialog.Builder(Start.this).setTitle("管制車輛")
                                    .setMessage(carNum + s)
                                    .setIcon(R.drawable.info).setPositiveButton("確認",new DialogInterface.OnClickListener()
                                    {
                                        public void onClick(DialogInterface dialoginterface,int i)
                                        {

                                        }
                                    }).show();
                        }
                    }
                });
    }

    public void Search(String carNum){
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(ip + "/v1/select/car/?car_id=" + carNum, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
            }
            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                String[] Car_Shape;
                Car_Shape = s.replace("\"","").split(";");
                if(Car_Shape.length > 2){
                    car_type = Car_Shape[0];
                    car_color = Car_Shape[1];
                    car_mark = Car_Shape[2];
                }
            }
        });
    }
    private boolean InitBlueTooth(){
        adapter = BluetoothAdapter.getDefaultAdapter();

        if(adapter == null){
            Toast.makeText(Start.this,"藍芽無法連接",Toast.LENGTH_LONG).show();
            return false;
        }

        if(!adapter.isEnabled()){
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(intent);
        }
        if(device == null){
            ScanDevice();
        }
        return  true;
    }

    private void listingFiles()
    {
        String szTemp;

        szFileList.clear();
        String szFilePath=	Environment.getExternalStorageDirectory() + "/Park_jy/" + sdtAll.format(d) + "/" + writedata1;
        File tmpFile = new File(szFilePath);

        if(!tmpFile.isFile())
            return;

        String[] arrayCars = Commin.readTXT(szFilePath, "\r\n");

        for (int i = 0; i < arrayCars.length; i++)
        {
            String[] arrayItem = arrayCars[i].split(";");

            if(arrayItem.length < 13)
                continue;

            String szForamt = String.format("%-8s", arrayItem[7]);
            szTemp = String.format("%03d  |  %s| %s| %s| %s          %s|  %03d",i+1,arrayItem[3],
                    arrayItem[5].split(" ")[0],szForamt.replaceAll("  ", "   "), arrayItem[10],arrayItem[1],Integer.parseInt(arrayItem[13]));

            szFileList.add(szTemp);
        }
    }
}
