package kr.co.compcareworker.Fragment.Enterprise;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentResult;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.MainActivity;
import kr.co.compcareworker.Activity.QRCodeActivity;
import kr.co.compcareworker.Activity.WebviewAct;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.CompanyData;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.Fragment.FragmentIntentIntegrator;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ContentAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.MonitoringDialog;
import kr.co.compcareworker.Util.CustomView.PartnerMemoDialog;
import kr.co.compcareworker.Util.ServiceThread;

@SuppressLint("ValidFragment")
public class Enterprise_Fragment extends Fragment {

    private Handler handler, hdr;
    String cp_idx;
    String agency_id, user_id;
    boolean equipment = false;

    //    ScrollView scroll;
    NestedScrollView scroll;
    SwipeRefreshLayout swipe;

    /**
     * 매출 내역
     */
    TextView ll_act_enterprise_year_list;

    /**
     * 명함관리
     */
    TextView enterprise_card_list;


    /**
     * 상단 업체정보
     */
    TextView tv_act_enterprise_name, tv_act_enterprise_office, tv_act_enterprise_representative,
            tv_act_enterprise_corporate_number,
            tv_act_enterprise_address1,
            tv_act_enterprise_address2,
            tv_act_enterprise_ceo,
            tv_act_enterprise_responsibility1,
            tv_act_enterprise_responsibility2,
            mae,
            su,
            misu,
            year,
            line,
            add_line,
            enterprise_addr_copyTV;

    ImageView plus;

    LinearLayout maeFrame, suFrame, addFrame, qrLL, enterprise_callLL;
    String call_hp;

    /**
     * 네비, 보유기종관리
     */

    TextView tv_act_enterprise_navigation, ll_act_enterprise_work_accept, refresh;

    /**
     * 보유장비
     */
    RecyclerView rv_act_enterprise_list;
    TextView tv_act_enterprise_list_content;
    //    EnterpriseRecyclerAdapter adapter;
    ContentAdapter adapter;

    /**
     * 하단 버튼들
     */
    LinearLayout ll_act_enterprise_work_list, ll_act_enterprise_memo,
            ll_act_enterprise_deal_list, ll_act_enterprise_kakao;

    FragmentActivity fa;

    TextView ll_act_enterprise_picture_list, ll_act_enterprise_estimate_list;

    /**
     * 비고수정
     **/
    TextView enterprise_partner_memoTV;

    ServiceThread thread;
    int finalPosition;
    int air_line_position;
    ArrayList<MachineItem> machineItems;
    ArrayItem_<CompanyData> machineData;
    Enterprise_Fragment.MonitoringServiceHandler holder_hdr;
    LinearLayout machineLL;

    TextView add_machineTV;

    public Enterprise_Fragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        Get_Contents();
        MyApplication.finishMonitoring = false;
    }

    @Override
    public void onPause() {
        super.onPause();
        MyApplication.finishMonitoring = true;
    }

    @Override
    public void onStop() {
        super.onStop();
        if (MyApplication.serviceThreads.size() > 0) {
            for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                MyApplication.serviceThreads.get(i).stopForever();
            }
            MyApplication.serviceThreads.clear();
        }
        MyApplication.finishMonitoring = true;
    }

    @SuppressLint("ValidFragment")
    public Enterprise_Fragment(Handler handler, String cp_idx) {
        this.hdr = handler;
        this.cp_idx = cp_idx;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_enterprise, container, false);

        swipe = v.findViewById(R.id.swipe);
        scroll = v.findViewById(R.id.scroll);
        plus = v.findViewById(R.id.plus);
        addFrame = v.findViewById(R.id.addFrame);

        /**매출 내역*/
        ll_act_enterprise_year_list = v.findViewById(R.id.ll_act_enterprise_year_list);

        /**명함관리*/
        enterprise_card_list = v.findViewById(R.id.enterprise_card_list);


        /** 상단 업체정보*/
        tv_act_enterprise_name = v.findViewById(R.id.tv_act_enterprise_name);
        tv_act_enterprise_office = v.findViewById(R.id.tv_act_enterprise_office);
//        tv_act_enterprise_representative = v.findViewById(R.id.tv_act_enterprise_representative);
        tv_act_enterprise_corporate_number = v.findViewById(R.id.tv_act_enterprise_corporate_number);
        tv_act_enterprise_address1 = v.findViewById(R.id.tv_act_enterprise_address1);
        tv_act_enterprise_address2 = v.findViewById(R.id.tv_act_enterprise_address2);
        tv_act_enterprise_ceo = v.findViewById(R.id.tv_act_enterprise_ceo);
//        tv_act_enterprise_responsibility1 = v.findViewById(R.id.tv_act_enterprise_responsibility1);
//        tv_act_enterprise_responsibility2 = v.findViewById(R.id.tv_act_enterprise_responsibility2);
        year = v.findViewById(R.id.year);
        mae = v.findViewById(R.id.mae);
        su = v.findViewById(R.id.su);
        misu = v.findViewById(R.id.misu);
        maeFrame = v.findViewById(R.id.maeFrame);
        suFrame = v.findViewById(R.id.suFrame);
        enterprise_addr_copyTV = v.findViewById(R.id.enterprise_addr_copyTV);

        /** 네비, 보유기종관리*/
        tv_act_enterprise_navigation = v.findViewById(R.id.tv_act_enterprise_navigation);
        ll_act_enterprise_work_accept = v.findViewById(R.id.ll_act_enterprise_work_accept);
        refresh = v.findViewById(R.id.refresh);


        /** 보유장비*/
        rv_act_enterprise_list = v.findViewById(R.id.rv_act_enterprise_list);
        tv_act_enterprise_list_content = v.findViewById(R.id.tv_act_enterprise_list_content);
        /***/

        /** 하단 버튼들*/
        //ll_act_enterprise_work_list = v.findViewById(R.id.ll_act_enterprise_work_list);
        ll_act_enterprise_picture_list = v.findViewById(R.id.ll_act_enterprise_picture_list);
        // ll_act_enterprise_deal_list = v.findViewById(R.id.ll_act_enterprise_deal_list);
        ll_act_enterprise_estimate_list = v.findViewById(R.id.ll_act_enterprise_estimate_list);
        // ll_act_enterprise_memo = v.findViewById(R.id.ll_act_enterprise_memo);
        //ll_act_enterprise_kakao = v.findViewById(R.id.ll_act_enterprise_kakao);

        /**머신 등록*/
        qrLL = v.findViewById(R.id.qrLL);

        /**비고수정**/
        enterprise_partner_memoTV = v.findViewById(R.id.enterprise_partner_memoTV);

        enterprise_callLL = v.findViewById(R.id.enterprise_callLL);

        machineLL = v.findViewById(R.id.machineLL);

        add_machineTV = v.findViewById(R.id.add_machineTV);

        init_Handler();
        init_Listener();

        Get_Contents();

        ll_act_enterprise_picture_list.setText(Html.fromHtml("서비스 <b>  사진</b>"));

        return v;
    }

    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        new ApiClient(data, "proc_company_view", hdr);
    }

    void Set_Contents() {
        tv_act_enterprise_name.setText(fa.enterpriseItem.getArrayitem().getPtName());
        tv_act_enterprise_office.setText(fa.enterpriseItem.getArrayitem().getCpName());
//        tv_act_enterprise_representative.setText(fa.enterpriseItem.getArrayitem().getPtCeo());
        tv_act_enterprise_corporate_number.setText(fa.enterpriseItem.getArrayitem().getPtCode());
        tv_act_enterprise_address1.setText(fa.enterpriseItem.getArrayitem().getCpAddr());
        tv_act_enterprise_address2.setText(Common.getInstance().isNull(fa.enterpriseItem.getArrayitem().getCpAddrSub()).toString());
        tv_act_enterprise_ceo.setText(Common.getInstance().isNull(fa.enterpriseItem.getArrayitem().getPtCeo()).toString());
//        tv_act_enterprise_responsibility1.setText(Common.getInstance().isNull(fa.enterpriseItem.getArrayitem().getPtMan()).toString());
//        tv_act_enterprise_responsibility2.setText(Common.getInstance().isNull(fa.enterpriseItem.getArrayitem().getPtManSub()).toString());
        call_hp = fa.enterpriseItem.getArrayitem().getCallHp();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy년");
        Calendar cal = Calendar.getInstance();
        year.setText(sdf.format(cal.getTime()));


        misu.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(fa.enterpriseItem.getArrayitem().getPtSellwillMoney())) + "원");

        if (!TextUtils.isEmpty(fa.userItem.getArrayitem().getMbType2()) && fa.userItem.getArrayitem().getMbType2().equals("eng")) {
            maeFrame.setVisibility(View.GONE);
            suFrame.setVisibility(View.GONE);
        } else {
            mae.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(fa.enterpriseItem.getArrayitem().getPtSellMoney())) + "원");
            su.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(fa.enterpriseItem.getArrayitem().getPtSellokMoney())) + "원");
        }

        if (fa.enterpriseItem.getArrayitem().getAlMachineData().size() != 0) {
            /** 어댑터 세팅*/
//            adapter = new EnterpriseRecyclerAdapter(getContext(), fa.userItem.getArrayitem().getAgency().getMbId(), fa.userItem.getArrayitem().getMbId());

            machineItems = new ArrayList<>();

            for (int i = 0; i < fa.enterpriseItem.getArrayitem().getAlMachineData().size(); i++) {
                machineItems.addAll(fa.enterpriseItem.getArrayitem().getAlMachineData().get(i).getItems());
            }

            String cp_air_line = fa.enterpriseItem.getArrayitem().getCpAirline().toString();
            String[] air_lines = cp_air_line.split(",");

            for (String air_line : air_lines) {

                int cnt = 1;

                for (int i = 0; i < machineItems.size(); i++) {

                    if (machineItems.get(i).getMcAirline().equals(air_line)) {
                        machineItems.get(i).setIndex(cnt);

                        if (cnt == 1) {
                            machineItems.get(i).setShow_position(true);
                            machineItems.get(i).setLast_position(true);

                        } else if (cnt > 1) {
                            machineItems.get(i - 1).setLast_position(false);
                            machineItems.get(i).setLast_position(true);
                        }
                        cnt++;
                    }
                }
            }

            adapter = new ContentAdapter(getContext(),/* new ContentAdapter.optionListener() {
                @Override
                public void clickBtn(Bundle bundle) {
                    Intent intent = new Intent(getContext(), FragmentActivity.class);
                    intent.putExtra("title", "기계 옵션설정");
                    intent.putExtra("type", "machine_option");
                    intent.putExtra("value1", bundle.getString("mc_idx"));
                    startActivity(intent);
                }
            },*/ new ContentAdapter.chartClickListener() {
                @Override
                public void clickBtn(Bundle bundle) {

                    String mc_idx = bundle.getString("mc_idx");
                    String mac = bundle.getString("mac");
                    MachineItem machineItem = null;

                    for (int i = 0; i < machineItems.size(); i++) {
                        if (machineItems.get(i).getMcIdx().equals(mc_idx)) {
                            machineItem = machineItems.get(i);
                        }
                    }

                    if (TextUtils.isEmpty(mac) || mac.equals("0")) {
                        Toast.makeText(getContext(), "연결된 IoT 기기가 없습니다.", Toast.LENGTH_SHORT).show();

                    } else {

                        MonitoringDialog dialog = new MonitoringDialog(getContext(), fa.userItem.getArrayitem().getAgIdx(), bundle.getString("pt_idx"), bundle.getString("cp_idx"),
                                mc_idx, bundle.getString("chart_type"), mac, machineItem);
                        dialog.show();
                    }
                }
            });

            rv_act_enterprise_list.setAdapter(adapter);
            adapter.addItem(machineItems);
            equipment = true;

            //메인화면 로딩시 첫번째 아이템이 mac주소가 있으면 데이터를 가져온다.
            holder_hdr = new Enterprise_Fragment.MonitoringServiceHandler();

            if (machineItems.size() > 0) {

                if (thread != null) {
                    thread.stopForever();
                    thread = null;
                }

                if (machineItems.get(0).getMcIotMac() != null) {

                    thread = new ServiceThread(holder_hdr, "monitoring", machineItems.get(0).getMcIotMac(), "0");
                    air_line_position = 0;
                    finalPosition = 0;
                    thread.start();
                }

                int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
                for (int i = 0; i < machineItems.size(); i++) {
                    if (machineItems.get(i).getMcIotMac() != null) {
                        if (machineItems.size() > 4) {
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150 * px);
                            machineLL.setLayoutParams(lp);
                            break;
                        } else {
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            machineLL.setLayoutParams(lp);
                            break;
                        }

                    } else {
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        machineLL.setLayoutParams(lp);
                    }
                }

            } else {
                rv_act_enterprise_list.setVisibility(View.GONE);
                tv_act_enterprise_list_content.setVisibility(View.VISIBLE);
                equipment = false;
            }

            RecyclerView.ItemAnimator animator = rv_act_enterprise_list.getItemAnimator();
            if (animator instanceof SimpleItemAnimator) {
                ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
            }

            air_line_position = -1;
            rv_act_enterprise_list.setItemViewCacheSize(machineItems.size());
            rv_act_enterprise_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {

                }

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    GridLayoutManager layoutManager = ((GridLayoutManager) recyclerView.getLayoutManager());
                    int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
                    int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
                    start_thread(firstVisiblePosition, lastVisiblePosition);
                }
            });

        } else {
            rv_act_enterprise_list.setVisibility(View.GONE);
            tv_act_enterprise_list_content.setVisibility(View.VISIBLE);
            equipment = false;
        }
    }

    void start_thread(int start, int end) {

        if (start != air_line_position) {

            if (MyApplication.serviceThreads.size() > 0) {
                for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                    MyApplication.serviceThreads.get(i).stopForever();
                }
                MyApplication.serviceThreads.clear();
            }

            for (int i = start; i <= end; i++) {
                if (machineItems.get(i).getMcIotMac() != null) {
                    ServiceThread thread = new ServiceThread(holder_hdr, "monitoring", machineItems.get(i).getMcIotMac(), i + "");
                    MyApplication.serviceThreads.add(thread);
                    thread.start();
                }
            }

            air_line_position = start;
        }
    }

    class MonitoringServiceHandler extends Handler {
        @Override
        public void handleMessage(android.os.Message msg) {

            String msg_data = msg.obj.toString();
            String get_mac = msg_data.substring(0, msg_data.indexOf("i"));
            String i = msg_data.substring(msg_data.indexOf("i") + 1);

            MyApplication.stop_ui_change = true;

            HashMap<String, String> data = new HashMap<>();
            data.put("mac", get_mac);
            data.put("i", i);
            new ApiClient(data, "proc_monitoring", hdr);
        }
    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");
                    Log.e("init_Handler", url);
                    if (url.equals("proc_company_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        fa.enterpriseItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                        }.getType());

                        if (fa.enterpriseItem.isSuccess()) {
                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), fa.enterpriseItem.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    } else if (url.equals("proc_monitoring")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        ArrayItem<MonitoringData> monitoringArray;
                        monitoringArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                        }.getType());

                        int position = Integer.parseInt(result_item.get("resultItem").getAsJsonObject().get("message").getAsString());

                        //모니터링 데이터를 정상적으로 가져왔을 때
                        if (monitoringArray.isSuccess()) {

                            machineItems.get(position).setRunning(true);
                            machineItems.get(position).setMonitoring(monitoringArray);
                            adapter.notifyItemChanged(position, null);
                            MyApplication.stop_ui_change = false;
                        }
                        //모니터링 데이터를 가져오는 것을 실패했을 때
                        else {
                            machineItems.get(position).setRunning(true);
                            machineItems.get(position).setMonitoring(null);
                            adapter.notifyItemChanged(position, null);

                            MyApplication.stop_ui_change = false;
                        }
                    } else if (url.equals("proc_get_qr_exist")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Intent intent = new Intent(getContext(), FragmentActivity.class);
                            intent.putExtra("title", "머신 등록");
                            intent.putExtra("type", "add_machine3");
                            intent.putExtra("value1", cp_idx);
                            intent.putExtra("value2", fa.enterpriseItem.getArrayitem().getPtIdx());
                            intent.putExtra("value3", result_item.get("resultItem").getAsJsonObject().get("message").getAsString());
                            startActivity(intent);
                            getActivity().finish();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        };
    }

    private void init_Listener() {
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Get_Contents();
                Toast.makeText(getContext(), "새로고침 완료", Toast.LENGTH_LONG).show();
                swipe.setRefreshing(false);
            }
        });

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Get_Contents();
            }
        });

        /** 네비게이션 연결*/

        tv_act_enterprise_navigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //우편번호가 없을 때
                if (fa.enterpriseItem.getArrayitem().getCpZip() == null || fa.enterpriseItem.getArrayitem().getCpZip().equals("") ||
                        fa.enterpriseItem.getArrayitem().getCpMapx() == null || fa.enterpriseItem.getArrayitem().getCpMapx().equals("") ||
                        fa.enterpriseItem.getArrayitem().getCpMapy() == null || fa.enterpriseItem.getArrayitem().getCpMapy().equals("")) {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("우편번호 혹은 주소가 잘못되어 연결이 불가합니다.\n주소를 복사하여 외부 네비게이션을 사용해주세요.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();

                } else {
                    Common.getInstance().navigationDialog(getContext(), fa.enterpriseItem.getArrayitem().getPtName(), Double.parseDouble(fa.enterpriseItem.getArrayitem().getCpMapy()), Double.parseDouble(fa.enterpriseItem.getArrayitem().getCpMapx()));
                }
            }
        });


        /** 장소 정보 수정*/
        addFrame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "장소 정보 수정");
                intent.putExtra("type", "place_adjust1");
                getContext().startActivity(intent);
            }
        });


        /**서비스 접수*/
        ll_act_enterprise_work_accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "서비스 접수");
                intent.putExtra("type", "service_register");
                intent.putExtra("value1", cp_idx);
                getContext().startActivity(intent);
            }
        });

        /**매출 내역 2020-05-19*/

        ll_act_enterprise_year_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String incodeUrl = URLEncoder.encode("https://" + fa.userItem.getArrayitem().getAgency().getMbId() +
                        ".compcare.co.kr/sell/invoice/invoice_total_item/?ag_idx=" + fa.userItem.getArrayitem().getAgIdx() + "&cp_idx=" + fa.enterpriseItem.getArrayitem().getCpIdx() + "&pt_idx=" + fa.enterpriseItem.getArrayitem().getPtIdx());
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "매출 내역");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });

        /**명함관리 2020-05-20*/
        enterprise_card_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "명함 관리");
                intent.putExtra("type", "business_card_management");
                intent.putExtra("value1", cp_idx);

                getContext().startActivity(intent);
            }
        });

        /** 머신 등록*/
        qrLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Intent intent = new Intent(getContext(), FragmentActivity.class);
//                intent.putExtra("title", "QR코드 등록");
//                intent.putExtra("type", "qr");
//                intent.putExtra("value1", cp_idx);
//                intent.putExtra("value2", tv_act_enterprise_office.getText().toString());
//                getContext().startActivity(intent);
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "QR코드 등록");
                intent.putExtra("type", "qr");
                intent.putExtra("value1", fa.enterpriseItem.getArrayitem().getAgIdx());
                intent.putExtra("value2", fa.enterpriseItem.getArrayitem().getPtIdx());
                intent.putExtra("value3", fa.enterpriseItem.getArrayitem().getCpIdx());
                getContext().startActivity(intent);
            }
        });

        /**서비스 사진**/
        ll_act_enterprise_picture_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "서비스 사진");
                intent.putExtra("type", "service_image");
                intent.putExtra("value1", fa.enterpriseItem.getArrayitem().getAgIdx());
                intent.putExtra("value2", fa.enterpriseItem.getArrayitem().getPtIdx());
                startActivity(intent);
            }
        });

        /**비고란**/
        enterprise_partner_memoTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MyApplication.finishMonitoring = true;

                String partner_memo = fa.enterpriseItem.getArrayitem().getPtMemo();
                String partner_name = fa.enterpriseItem.getArrayitem().getPtName();

                PartnerMemoDialog dialog = new PartnerMemoDialog(getContext(), partner_name, partner_memo, fa.enterpriseItem.getArrayitem().getPtIdx(), new PartnerMemoDialog.PartnerMemoDialogListener() {
                    @Override
                    public void clickBtn() {

                        Get_Contents();
                    }
                });
                dialog.show();
            }
        });

        /**견적서관리**/
        ll_act_enterprise_estimate_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "견적서 관리");
                intent.putExtra("type", "estimate_list");
                intent.putExtra("value1", fa.enterpriseItem.getArrayitem().getAgIdx());
                intent.putExtra("value2", fa.enterpriseItem.getArrayitem().getCpIdx());
                startActivity(intent);
            }
        });

        /**주소복사**/
        enterprise_addr_copyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("copy_addr", tv_act_enterprise_address1.getText());
                clipboard.setPrimaryClip(clipData);
                Toast.makeText(getContext(), "주소가 복사되었습니다.", Toast.LENGTH_SHORT).show();
            }
        });

        /**전화걸기**/
        enterprise_callLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String call = fa.enterpriseItem.getArrayitem().getCpTel();
                if (TextUtils.isEmpty(call) || call.equals("")) {
                    Toast.makeText(getContext(), "전화번호가 없습니다.", Toast.LENGTH_LONG).show();
                    return;
                }
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("전화연결 하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        try {
                            Uri uri = Uri.parse("tel:" + call);
                            getContext().startActivity(new Intent("android.intent.action.DIAL", uri));
                            dialog.dismiss();
                        } catch (Exception e) {
                            Toast.makeText(getContext(), "전화번호 형식이 올바르지 않습니다.", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });

        /**머신등록2**/
        add_machineTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentIntentIntegrator integrator = new FragmentIntentIntegrator(Enterprise_Fragment.this);
                integrator.setCaptureActivity(QRCodeActivity.class);
                integrator.setBarcodeImageEnabled(true);
                integrator.setOrientationLocked(false);
                integrator.initiateScan();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        IntentResult result = FragmentIntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result.getContents() != null && !result.getContents().equals("")) {

            HashMap<String, String> get_data = new HashMap<>();
            get_data.put("cp_idx", cp_idx);
            get_data.put("qr_code", result.getContents());
            new ApiClient(get_data, "proc_get_qr_exist", hdr);

//            Intent intent = new Intent(getContext(), FragmentActivity.class);
//            intent.putExtra("title", "머신 등록");
//            intent.putExtra("type", "add_machine3");
//            intent.putExtra("value1", cp_idx);
//            intent.putExtra("value2", fa.enterpriseItem.getArrayitem().getPtIdx());
//            intent.putExtra("value3", result.getContents());
//            startActivity(intent);
//            getActivity().finish();

        } else {
            Toast.makeText(getContext(), "qr코드가 정상적으로 인식되지 않았습니다.", Toast.LENGTH_LONG).show();
            getActivity().finish();
        }
    }

    void intentActivity(Class intentclass, String title, String type, String value1) {
        Intent intent = new Intent(getContext(), intentclass);
        intent.putExtra("title", title);
        intent.putExtra("type", type);
        intent.putExtra("value1", value1);
        getActivity().startActivity(intent);
    }

    void intentActivity(Class intentclass, String title, String type) {
        Intent intent = new Intent(getContext(), intentclass);
        intent.putExtra("title", title);
        intent.putExtra("type", type);
        getActivity().startActivity(intent);
    }

    void equipmentDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
        dialogBuilder.setTitle("콤프케어 작업자");
        dialogBuilder.setMessage("보유한 장비가 없습니다.");
        dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                dialog.dismiss();
            }
        });
        dialogBuilder.show();
    }
}
