package com.tofly.ghrq_route.common.ui.view;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.esri.arcgisruntime.geometry.Point;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.ui.activity.UiAdjustDeviceRepair;
import com.tofly.ghrq_route.common.ui.activity.UiCommonDeviceRepair;
import com.tofly.ghrq_route.common.ui.adapter.ChildRepairHistoryAdapter;
import com.tofly.ghrq_route.common.util.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.image.ImageUtil;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.planPointRepair.PointRepairTool;
import com.tofly.ghrq_route.module.planPointRepair.controller.PointRepairCallBack;
import com.tofly.ghrq_route.module.planPointRepair.domain.NFCInfoBean;
import com.tofly.ghrq_route.module.planPointRepair.domain.PlanPointRepair;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Amu on 2017/2/21.
 */

public class BottomSheetRepairDetail extends LinearLayout {
    @BindView(R.id.bottom_sheet_detail_header_close)
    ImageView imageViewBottomDetailClose;
    @BindView(R.id.bottom_sheet_detail_header)
    RelativeLayout bottomSheetDetailHeader;
    @BindView(R.id.text_repair_sid)
    TextView textRepairSid;
    @BindView(R.id.text_repair_subtype)
    TextView textRepairSubtype;
    @BindView(R.id.text_repair_code)
    TextView textRepairCode;
    @BindView(R.id.text_repair_addr)
    TextView textRepairAddr;
/*    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;*/
    @BindView(R.id.layout_device_info)
    LinearLayout layoutDeviceInfo;
    @BindView(R.id.layout_nfc_info)
    LinearLayout layoutNFCInfo;
    @BindView(R.id.layout_nfc_dhtw)
    LinearLayout layoutNFCDhtw;
    @BindView(R.id.layout_dhtw_area)
    LinearLayout layoutDhtwArea;
    @BindView(R.id.layout_nfc_pttw)
    LinearLayout layoutNFCPttw;
    @BindView(R.id.layout_pttw_area)
    LinearLayout layoutPttwArea;
    @BindView(R.id.layout_repair_history)
    LinearLayout layoutRepairHistory;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;
    @BindView(R.id.btn_repair_route_add)
    Button btnRouteAdd;
    @BindView(R.id.detail_cardview)
    LinearLayout detailCardview;
    @BindView(R.id.layout_detail_root)
    LinearLayout layoutDetailRoot;

    private Context mContext;

    private ImageUtil imageUtil;

    private OfflinePathBean mPlanPoint;
    private PlanBean mPlan;
    private Point mLocation;

    private BottomSheetBehavior bottomSheetBehavior = null;
    private boolean isBottomSheetDetailShow = false;
    private boolean isDialogMode = false;
    private boolean isEditable = false;
    private PointRepairTool repairTool;

    private boolean mbIsRefreshing = false;

    private ChildRepairHistoryAdapter repairHistoryAdapter;

    private List<PlanPointRepair> mRepairHistoryList;

    private ArrayList<String> nfcPics = new ArrayList<>();

    private int pageindex = 1;

    private final static int PHOTO_LOCAL_STATE = 0;
    private final static int PHOTO_UPLOADING = 1;
    private final static int PHOTO_UPLOADED = 2;
    private final static int PHOTO_UPLOAD_FAILED = 3;

    private onDetailButtonCloseClicked mOnDetailButtonCloseClicked;

    final int BOTTOM_SHEET_BOTTOM = BaseApp.dip2px(56);
    final int BOTTOM_SHEET_MIDDLE = BaseApp.dip2px(400);
    final int BOTTOM_SHEET_TOP = ViewGroup.LayoutParams.MATCH_PARENT;

    public BottomSheetRepairDetail(Context context) {
        this(context, null);
    }

    public BottomSheetRepairDetail(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomSheetRepairDetail(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
        repairTool = PointRepairTool.getInstance();
        imageUtil = new ImageUtil(context);

        initAttrs(attrs);
        initView();
        initListener();
    }

    public boolean isBottomSheetDetailShowing() {
        return isBottomSheetDetailShow;
    }

    public interface onDetailButtonCloseClicked {
        void onClicked();
    }

    public void setOnDetailButtonCloseClicked(onDetailButtonCloseClicked closeClicked) {
        mOnDetailButtonCloseClicked = closeClicked;
    }

    public void setEditable(boolean enable) {
        isEditable = enable;
        btnRouteAdd.setEnabled(isEditable);
    }

    private void initAttrs(AttributeSet attrs){
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BottomSheetRepairDetail);
        try {
            isDialogMode = typedArray.getBoolean(R.styleable.BottomSheetRepairDetail_DialogMode, false);
        }finally {
            typedArray.recycle();
        }
    }

    private void initView() {
        inflate(mContext, R.layout.layout_bottom_sheet_repair_detail, this);
        ButterKnife.bind(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        mRepairHistoryList = new ArrayList<>();
        repairHistoryAdapter = new ChildRepairHistoryAdapter(mContext, mRepairHistoryList);
        recyclerView.setAdapter(repairHistoryAdapter);

        if (isDialogMode)
            imageViewBottomDetailClose.setVisibility(View.GONE);
    }

    private void initListener() {
        if (!isDialogMode) {
            imageViewBottomDetailClose.setOnClickListener(v -> hideSelf());

            bottomSheetDetailHeader.setOnClickListener(view -> {
                if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
            });
        }

        recyclerView.setOnRefreshListener(() -> refreshData());

        repairHistoryAdapter.setOnItemClickListener((view, position) -> {
            PlanPointRepair recordBean = repairHistoryAdapter.getItem(position);
            gotoUiPointRepairHistory(recordBean);
        });

        btnRouteAdd.setOnClickListener(v -> gotoUiPointRepair());
    }

    private void gotoUiPointRepair() {
        if (mPlanPoint != null && mPlan != null){
            Bundle bundle = new Bundle();
            bundle.putSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY, mPlanPoint);
            bundle.putSerializable(PlanBean.PLAN_BEAN_KEY, mPlan);
            bundle.putBoolean(PlanPointRepair.POINT_REPAIR_IS_NEW_KEY, true);
            bundle.putBoolean(PlanPointRepair.POINT_REPAIR_IS_LOCAL_KEY, false);
            if (mLocation != null) {
                LocationUtil_xu.CoordinateClass coordinate = new LocationUtil_xu.CoordinateClass(mLocation.getX(), mLocation.getY());
                bundle.putSerializable(LocationUtil.CURRENT_LOCATION_KEY, coordinate);
            }
            boolean isCommonDevice = mPlan.isCommonDeviceType();
            Intent intent = new Intent();
            if (isCommonDevice) {
                /*阀门设备*/
                intent.setClass(mContext, UiCommonDeviceRepair.class);
            }else {
                intent.setClass(mContext, UiAdjustDeviceRepair.class);
            }
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    }

    private void gotoUiPointRepairHistory(PlanPointRepair pointRepair) {
        if (mPlanPoint != null && pointRepair != null){
            Bundle bundle = new Bundle();
            bundle.putSerializable(PlanPointRepair.POINT_REPAIR_BEAN_KEY, pointRepair);
            bundle.putSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY, mPlanPoint);
            bundle.putSerializable(PlanBean.PLAN_BEAN_KEY, mPlan);
            bundle.putBoolean(PlanPointRepair.POINT_REPAIR_EDITABLE_KEY, true);
            bundle.putBoolean(PlanPointRepair.POINT_REPAIR_REMOVABLE_KEY, true);
            boolean isCommonDevice = mPlan.isCommonDeviceType();
            if (isCommonDevice) {
                /*阀门设备*/
                Intent intent = new Intent();
                intent.setClass(mContext, UiCommonDeviceRepair.class);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }else {
                Intent intent = new Intent();
                intent.setClass(mContext, UiAdjustDeviceRepair.class);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }
        }
    }

    public void hideSelf() {
        isBottomSheetDetailShow = false;
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) this.getLayoutParams();
        if (layoutParams.height == BOTTOM_SHEET_TOP) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    BottomSheetRepairDetail.this.setVisibility(View.INVISIBLE);
                    if (mOnDetailButtonCloseClicked != null) {
                        mOnDetailButtonCloseClicked.onClicked();
                    }
                }
            }, 50);
        } else {
            this.setVisibility(View.INVISIBLE);
            if (mOnDetailButtonCloseClicked != null) {
                mOnDetailButtonCloseClicked.onClicked();
            }
        }
    }

    public void setBottomDetailState(@BottomSheetBehavior.State int state) {
        if (bottomSheetBehavior != null) {
            if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED
                    && state == BottomSheetBehavior.STATE_COLLAPSED) {
                bottomSheetBehavior.setState(state);
            } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED
                    && state == BottomSheetBehavior.STATE_EXPANDED) {
                bottomSheetBehavior.setState(state);
            }
        }
    }

    public void initBottomSheetDetail(OfflinePathBean planPoint, PlanBean planBean, Point location) {
        isBottomSheetDetailShow = true;

        mPlanPoint = planPoint;
        mPlan = planBean;
        mLocation = location;

        if (mPlanPoint != null){
            String pointId = mPlanPoint.getPoint_id();
            if (pointId != null && !pointId.isEmpty()){
                String sid = pointId;
                int index = pointId.lastIndexOf("-");
                if (index != -1){
                    sid = pointId.substring(index + 1);
                }
                textRepairSid.setText(sid);
            }

            String subtype = mPlan.getDevice_type_name();
            textRepairSubtype.setText(subtype);

            String code = mPlanPoint.getCode();
            textRepairCode.setText(code);

            String addr = mPlanPoint.getAddr();
            textRepairAddr.setText(addr);

            /*加载nfc设备信息*/
            if (C.bPlanDetailNFCModual_debug){
                if (mPlan != null) {
                    String rfid = mPlanPoint.getRfid();
                    if (rfid != null && !rfid.isEmpty()){
                        loadNFCInfo(rfid, mPlan.getDevice_type_id());
                    }
                }
            }
        }

        btnRouteAdd.setEnabled(isEditable);

        if (mPlan != null) {
            repairHistoryAdapter.setDeviceTypeId(mPlan.getDevice_type_id());
        }
        recyclerView.setRefreshing(true);
        loadRepairHistoryList();

        if (isDialogMode) {
            bottomSheetDetailHeader.setOnClickListener(null);
        }

        if (!isDialogMode) {
            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) this.getLayoutParams();
            layoutParams.height = BOTTOM_SHEET_MIDDLE;
            setLayoutParams(layoutParams);
            bottomSheetBehavior = BottomSheetBehavior.from(this);

            bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

            final float[] offset = {0};
            bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                @Override
                public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomSheet.getLayoutParams();
                    switch (newState) {
                        case BottomSheetBehavior.STATE_DRAGGING:
                            layoutParams.height = BOTTOM_SHEET_TOP;
                            bottomSheet.setLayoutParams(layoutParams);
                            break;
                        case BottomSheetBehavior.STATE_COLLAPSED:
                            break;
                        case BottomSheetBehavior.STATE_SETTLING:
                            if (offset[0] >= 0 && offset[0] <= 1) {
                                if (offset[0] > 0.7 && offset[0] < 1) {
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_MIDDLE);
                                    layoutParams.height = BOTTOM_SHEET_TOP;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                                } else if (offset[0] > 0.4 && offset[0] < 0.7) {
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_MIDDLE;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                                } else if (offset[0] != 0) {
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_MIDDLE;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                                }
                            }
                            break;
                        case BottomSheetBehavior.STATE_EXPANDED:
                            break;
                    }
                }

                @Override
                public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                    offset[0] = slideOffset;
                }
            });
        }
    }

    private void loadNFCInfo(String rfid, int deviceTypeId){
        repairTool.getRepairNFCInfo(mContext, rfid, deviceTypeId, new PointRepairCallBack(){
            @Override
            public void onGetRepairNFCInfo(boolean isSuccess, int errorCode, String errMsg, NFCInfoBean nfcInfo) {
                super.onGetRepairNFCInfo(isSuccess, errorCode, errMsg, nfcInfo);
                if (isSuccess){
                    if (nfcInfo != null){
                        initNfcArea(nfcInfo);
                    }
                }
            }
        });
    }

    private void initNfcArea(NFCInfoBean nfcInfo){
        if (nfcInfo != null){
            layoutNFCInfo.setVisibility(VISIBLE);

            LayoutInflater inflater = LayoutInflater.from(mContext);

            /*导航图文*/
            TextView textDhtwText = layoutDhtwArea.findViewById(R.id.text_title);
            HorizontalScrollView layoutDhtwPicArea = layoutDhtwArea.findViewById(R.id.pic_area);
            LinearLayout dhtwGallery = layoutDhtwArea.findViewById(R.id.gallery);

            String nfcDhtwText = nfcInfo.getDhtw();
            List<String> dhtwPics = nfcInfo.getDhtwpicture();
            if ((nfcDhtwText == null || nfcDhtwText.isEmpty()) && (dhtwPics == null || dhtwPics.size() == 0)){
                layoutDhtwArea.setVisibility(GONE);
            }else {
                if (nfcDhtwText != null && !nfcDhtwText.isEmpty())
                    textDhtwText.setText(nfcDhtwText);
                else
                    textDhtwText.setVisibility(GONE);

                if (dhtwPics != null && dhtwPics.size() > 0){
                    layoutDhtwPicArea.setVisibility(VISIBLE);
                    for (String pic : dhtwPics){
                        String path = NetRequestURL.getHttpHead() + pic;
                        View view = imageUtil.getViewFromUrl(path);
                        dhtwGallery.addView(view);
                    }
                    nfcPics.addAll(dhtwPics);
                }else {
                    layoutDhtwPicArea.setVisibility(GONE);
                }
            }

            /*普通图文*/
            List<NFCInfoBean.TwBean> twBeans = nfcInfo.getPttw();
            if (twBeans == null || twBeans.isEmpty()){
                layoutPttwArea.setVisibility(GONE);
            }else {
                for (NFCInfoBean.TwBean twBean : twBeans){
                    if (twBean != null){
                        final View rootView = inflater.inflate(R.layout.layout_nfc_picture,null);
                        TextView textPttwName = rootView.findViewById(R.id.text_title);
                        HorizontalScrollView layoutPttwPicArea = rootView.findViewById(R.id.pic_area);
                        LinearLayout pttwGallery = rootView.findViewById(R.id.gallery);
                        textPttwName.setText(twBean.getChnName());
                        List<String> pttwPics = twBean.getPic();
                        if (pttwPics != null && pttwPics.size() > 0){
                            for (String pic : pttwPics){
                                String path = NetRequestURL.getHttpHead() + pic;
                                View view = imageUtil.getViewFromUrl(path);
                                pttwGallery.addView(view);
                            }
                            nfcPics.addAll(pttwPics);
                        }else {
                            layoutPttwPicArea.setVisibility(GONE);
                        }
                        layoutPttwArea.addView(rootView);
                    }
                }
            }
        }
    }

    private void stopRefreshing(){
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.setRefreshing(false);
                recyclerView.hideMoreProgress();
                mbIsRefreshing = false;
            }
        }, 2000);
    }

    private void loadRepairHistoryList(){
        if (mPlanPoint != null && mPlan != null) {
            boolean isCommonDevice = mPlan.isCommonDeviceType();
            if (isCommonDevice){
                loadCommonDeviceRepairHistoryList();
            }else {
               loadAdjustDeviceRepairHistoryList();
            }
        }
    }

    private void loadCommonDeviceRepairHistoryList(){
        mbIsRefreshing = true;
        repairTool.loadCommonDeviceRepairHistoryList(mContext,  mPlanPoint.getPlan_id(), mPlanPoint.getPoint_id(), pageindex, new PointRepairCallBack(){
            @Override
            public void onGetPointChildRepairList(boolean isSuccess, int errorCode, String errMsg, List<PlanPointRepair> repairList, int total) {
                super.onGetPointChildRepairList(isSuccess, errorCode, errMsg, repairList, total);
                stopRefreshing();
                if (isSuccess && repairList != null) {
                    if (pageindex == 1) {
                        repairHistoryAdapter.clear();
                        recyclerView.setTotal(total);
                    }
                    repairHistoryAdapter.addAll(repairList);
                } else {
                    recyclerView.setTotal(0);
                    repairHistoryAdapter.clear();
                }
            }
        });
    }

    private void loadAdjustDeviceRepairHistoryList(){
        mbIsRefreshing = true;
        repairTool.loadAdjustDeviceRepairHistoryList(mContext, mPlanPoint.getPlan_id(), mPlanPoint.getPoint_id(), pageindex, new PointRepairCallBack(){
            @Override
            public void onGetPointChildRepairList(boolean isSuccess, int errorCode, String errMsg, List<PlanPointRepair> repairList, int total) {
                super.onGetPointChildRepairList(isSuccess, errorCode, errMsg, repairList, total);
                stopRefreshing();
                if (isSuccess) {
                    if (pageindex == 1) {
                        repairHistoryAdapter.clear();
                        recyclerView.setTotal(total);
                    }
                    if (repairList != null && repairList.size() > 0) {
                        repairHistoryAdapter.addAll(repairList);
                    }
                } else {
                    recyclerView.setTotal(0);
                    repairHistoryAdapter.clear();
                }
            }
        });
    }

    public void refreshData(){
        pageindex = 1;
        recyclerView.setRefreshing(true);
        loadRepairHistoryList();
    }
}
