package com.efounder.chat.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.form.application.ApplicationContainer;
import com.efounder.form.application.FormApplication;
import com.efounder.form.application.FormViewContainer;
import com.efounder.form.application.util.Form;
import com.efounder.form.application.util.FormAppUtil;
import com.efounder.form.builder.XML2Forms;
import com.efounder.frame.ViewSize;
import com.efounder.frame.arcmenu.ArcMenu;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.frame.fragment.EFAppAccountTabFragmentInterface;
import com.efounder.frame.title.EFTitleView;
import com.efounder.frame.title.EFTitleViewUtils;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.mobilemanager.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hudq on 2016/8/29. xx
 * 处理多个表单，用此类{区别于 @link EFAppAccountFormFragment}
 */

public class EFAppAccountFormListFragment extends EFFragment{
    private int position;
    private List<StubObject> stubList;
    private StubObject currentStub;

    private Handler handler = new MyHandler(this);
//    private ProgressDialog progressDialog;
    private LinearLayout rootLayout;

    private ApplicationContainer applicationContainer;

    private static class MyHandler extends Handler{
        WeakReference<EFAppAccountFormListFragment> weakReference;

        public MyHandler(EFAppAccountFormListFragment fragment) {
            this.weakReference = new WeakReference<EFAppAccountFormListFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            EFAppAccountFormListFragment fragment = weakReference.get();
            if (fragment == null) return;
            switch (msg.what){
                case 1:
//                    fragment.progressDialog.dismiss();
                    //添加当前Form
                    fragment.addCurrentForm(fragment.rootLayout,fragment.applicationContainer);
                    break;
            }
        }
    }

    public static EFAppAccountFormListFragment newInstance(int position, ArrayList<StubObject> stubList){
        EFAppAccountFormListFragment appAccountFragment = new EFAppAccountFormListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position",position);
        bundle.putSerializable("stubList", stubList);
        appAccountFragment.setArguments(bundle);
        return appAccountFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        position = getArguments().getInt("position");
        stubList = (List<StubObject>) getArguments().getSerializable("stubList");
        currentStub = stubList.get(position);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ef_fragment_app_account_form,container,false);
        TextView textView = (TextView) view.findViewById(R.id.textView_test);
//        textView.setText(position+"--" + stubList.get(position).getCaption() +"--"+ stubList.get(position).getString(EFXmlConstants.ATTR_FORM,""));

        rootLayout = (LinearLayout) view.findViewById(R.id.rootLayout);

        rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    rootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                //TODO 1.生成 form--ApplicationContainer（线程中） 2.添加 FormViewContainer 到界面

                //1.判断是否初始化所有Form
                StubObject parentStub = EFAppAccountRegistry.getStubByID(currentStub.getString(EFAppAccountRegistry.ATTR_PARENT_ID,""));
                final boolean isInitAllForm = parentStub.getString(EFXmlConstants.ATTR_IS_INIT_ALL_FORM,"0").equals("1");
                final String parentID = (String) parentStub.getID();
//                DialogUtils.showProgressDialog("正在构建应用场景...");
                EFTitleView titleView = EFTitleViewUtils.getEFTitleView(EFAppAccountFormListFragment.this);
                if (titleView != null){
                    titleView.showLeftProgressBar();
                }

                new Thread(){
                    @Override
                    public void run() {
                        super.run();
//                        if (Looper.myLooper() == null){
//                            Looper.prepare();
//                        }
                        if (isInitAllForm){
                            //此处注意，实例化多个EFAppAccountFormListFragment，会导致多个线程执行
                            synchronized (EFAppAccountFormListFragment.class){
                                //2.如果内存中没有applicationContainer就生成（可能被回收了）
                                applicationContainer = EFAppAccountUtils.applicationContainerMap.get(parentID);
                                Log.w("=====","applicationContainer=====" + applicationContainer);
                                if (applicationContainer == null){
                                    applicationContainer = generateAllForms(rootLayout);
                                    EFAppAccountTabFragmentInterface tabFragmentInterface = (EFAppAccountTabFragmentInterface) getParentFragment();
                                    ArcMenu arcMenu = tabFragmentInterface.getArcMenu();
                                    //TODO 根据购物车中已有的数据恢复角标
                                    //item.superscriptAddNumber(66);
                                    applicationContainer.putObject("arcMenu",arcMenu);
                                    EFAppAccountUtils.applicationContainerMap.put(parentID,applicationContainer);
                                }
                                handler.sendEmptyMessage(1);
                            }
                        }else {
                            applicationContainer = generateOneForm(rootLayout);
                            handler.sendEmptyMessage(1);
                        }
//                        Looper.loop();
                    }
                }.start();

            }

        });

        return view;
    }


    private ApplicationContainer generateAllForms(LinearLayout ll){
        List<Form> formList = new ArrayList();
        ViewSize viewSize = new ViewSize(ll.getMeasuredWidth(),ll.getMeasuredHeight());
        for (int i=0; i<stubList.size(); i++) {
            StubObject stub = stubList.get(i);
            //1.form
            String formNameXml = stub.getString(EFXmlConstants.ATTR_FORM,"");
            String formName = formNameXml.substring(0,formNameXml.indexOf(".xml"));
            String formPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + formNameXml;
            try {
                InputStream inputStream =  new FileInputStream(formPath);
                Form form = new Form();
                form.setFormName(formName);
                form.setInputStream(inputStream);
                form.setViewSize(viewSize);
                formList.add(form);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //2.attachForm(例如：购物车form)
            int bottomTabBarHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,50,getResources().getDisplayMetrics());
            ViewSize attachViewSize = new ViewSize(ll.getMeasuredWidth(),ll.getMeasuredHeight() + bottomTabBarHeight);
            String attachFormName = stub.getString(EFXmlConstants.ATTR_ATTACH_FORM,"");
            if (!"".equals(attachFormName)){
                String attachFormPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + attachFormName;
                String formNameLite = attachFormName.substring(0,attachFormName.indexOf(".xml"));
                try {
                    InputStream inputStream =  new FileInputStream(attachFormPath);
                    Form form = new Form();
                    form.setFormName(formNameLite);
                    form.setInputStream(inputStream);
                    form.setViewSize(attachViewSize);
                    formList.add(form);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

        }
        return FormAppUtil.generateForm(formList, null, EFAppAccountUtils.V8, new XML2Forms.FormCreationCompleteListener() {
            @Override
            public void onFormCreationComplete() {
//                progressDialog.dismiss();
//                DialogUtils.dismissProgressDialog();
                EFTitleView titleView = EFTitleViewUtils.getEFTitleView(EFAppAccountFormListFragment.this);
                if (titleView != null){
                    titleView.dismissLeftProgressBar();
                }
            }
        });
    }

    private  ApplicationContainer generateOneForm(LinearLayout ll){
        ApplicationContainer applicationContainer = null;
        try {
            String xmlName = currentStub.getString(EFXmlConstants.ATTR_FORM,"");
            String formName = xmlName.substring(0,xmlName.indexOf(".xml"));
            String formPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + xmlName;
            InputStream inputStream =  new FileInputStream(formPath);
            ViewSize viewSize = new ViewSize(ll.getMeasuredWidth(),ll.getMeasuredHeight());
            Form form = new Form();
            form.setFormName(formName);
            form.setInputStream(inputStream);
            form.setViewSize(viewSize);
            List<Form> formList = new ArrayList();
            formList.add(form);
            applicationContainer = FormAppUtil.generateForm(formList, null, EFAppAccountUtils.V8, new XML2Forms.FormCreationCompleteListener() {
                @Override
                public void onFormCreationComplete() {
//                    progressDialog.dismiss();
//                    DialogUtils.dismissProgressDialog();
                    EFTitleView titleView = EFTitleViewUtils.getEFTitleView(EFAppAccountFormListFragment.this);
                    if (titleView != null){
                        titleView.dismissLeftProgressBar();
                    }
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return applicationContainer;
    }

    private void addCurrentForm(LinearLayout ll ,ApplicationContainer applicationContainer) {
        String xmlName = currentStub.getString(EFXmlConstants.ATTR_FORM,"");
        String formName = xmlName.substring(0,xmlName.indexOf(".xml"));
        FormApplication formApplication = applicationContainer.getFormApplication(formName);
        if (formApplication == null) return;
        FormViewContainer formViewContainer = (FormViewContainer) formApplication.getFormContainer("form1");
        if (formViewContainer == null) {
            Log.e("ee","没有找到名称为form1的表单");
            return;
        }
        ViewGroup parent = (ViewGroup) formViewContainer.getParent();
        if (parent != null){
            parent.removeView(formViewContainer);
        }

        ll.removeAllViews();
        ll.addView(formViewContainer);
    }

}
