package com.uas.module.home.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.maning.mndialoglibrary.MProgressDialog;
import com.maning.mndialoglibrary.MToast;
import com.uas.module.common.base.BaseActivity;
import com.uas.module.common.utils.Constants;
import com.uas.module.common.utils.DisplayUtil;
import com.uas.module.common.utils.StatusBarUtil;
import com.uas.module.common.utils.StringUtils;
import com.uas.module.home.R;
import com.uas.module.home.model.GroupMessageBean;
import com.uas.module.home.model.MessageConfigBean;
import com.uas.module.home.network.grpc.Authentication;
import com.uas.module.home.network.grpc.MobileClientAuthenticationInterceptor;
import com.uas.module.widget.adapter.ItemPopListAdapter;
import com.uas.module.widget.model.ItemsSelectType1;
import com.usoftchina.uu.mobile.grpc.api.AccountServiceGrpc;
import com.usoftchina.uu.mobile.grpc.api.AccountSigninRequest;
import com.usoftchina.uu.mobile.grpc.api.AccountSigninResponse;
import com.usoftchina.uu.mobile.grpc.api.AuthedToken;
import com.usoftchina.uu.mobile.grpc.api.DeviceInfo;
import com.usoftchina.uu.mobile.grpc.api.ResponseHeader;
import com.usoftchina.uu.mobile.grpc.api.SwitchCompanyRequest;
import com.usoftchina.uu.mobile.grpc.api.SwitchCompanyResponse;

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

import de.hdodenhof.circleimageview.CircleImageView;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;


@Route(path = "/home/login")
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    public static final String PASS_WORDS = "PASS_WORDS";
    private CircleImageView mHeader;
    private EditText mPhoneNumberEdit;
    private EditText mPasswordEdit;
    private TextView tv_register, tv_findPwd, mLoginButton;
    private View mToastHead;
    private FrameLayout mToastLayout;

   @Autowired(name = "phone")
    String mPhone;
   @Autowired(name = "password")
    String mPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtil.immersive(this, 0x00000000, 0.0f);
        initView();
    }

    
    private void initView() {
        mToastHead = findViewById(R.id.login_toast_head);
        mToastLayout = findViewById(R.id.login_toast_fl);
        StatusBarUtil.setPaddingSmart(this, mToastHead);
        mPhoneNumberEdit = findViewById(R.id.phone_numer_edit);
        mPasswordEdit =  findViewById(R.id.password_edit);
        mHeader = findViewById(R.id.iv_head);
        tv_findPwd =  findViewById(R.id.tv_findPwd);
        tv_register = findViewById(R.id.tv_register);
        mLoginButton = findViewById(R.id.login_btn);
        mLoginButton.setOnClickListener(this);
        tv_findPwd.setOnClickListener(this);
        tv_register.setOnClickListener(this);
        mPhoneNumberEdit.addTextChangedListener(new MyTextWatcher());
        mPasswordEdit.addTextChangedListener(new MyTextWatcher());

       String phone= SPUtils.getInstance(Constants.spName).getString("phone");
       String password= SPUtils.getInstance(Constants.spName).getString("password");
       if(!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(password)){
           mPhoneNumberEdit.setText(phone);
           mPasswordEdit.setText(password);
       }
       
       if (!StringUtils.isEmpty(mPhone)&&!StringUtils.isEmpty(mPassword)){
           mPhoneNumberEdit.setText(mPhone);
           mPasswordEdit.setText(mPassword);
       }
    }
    

    class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String phone = mPhoneNumberEdit.getText().toString().trim();
            String password = mPasswordEdit.getText().toString();
            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(password)) {
                mLoginButton.setEnabled(false);
            } else {
                mLoginButton.setEnabled(true);
            }
        }
    }



    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.login_btn) {
            login();
        } else if (v.getId() == R.id.tv_register) {
            startActivity(new Intent(this, RegisterActivity.class));
        } else if (v.getId() == R.id.tv_findPwd) {

        }
    }

    private void login() {
        final String phoneNumber = mPhoneNumberEdit.getText().toString().trim();
        final String password = mPasswordEdit.getText().toString();
        MProgressDialog.showProgress(this,"");
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastUtils.showLong("手机号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtils.showLong("密码不能为空！");
            return;
        }
       
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ManagedChannel channel = ManagedChannelBuilder.forAddress("uu-api-test.usoftchina.com", 9620)
                            .intercept(new MobileClientAuthenticationInterceptor())
                            .usePlaintext(true)
                            .build();
                    AccountSigninResponse response = AccountServiceGrpc.newBlockingStub(channel).signin(AccountSigninRequest.newBuilder()
                            .setMobile(phoneNumber)
                            .setPassword(password)
                            .setDeviceInfo(DeviceInfo.newBuilder()
                                    .setOs(DeviceInfo.OS.ANDROID))
                            .build());
                    ResponseHeader header = response.getResponseHeader();
                    if (header.getSuccess()) {
                        MProgressDialog.dismissProgress();
                        System.out.println(response.getAccount());
                        AuthedToken token = response.getAuthedToken();
                        SPUtils.getInstance(Constants.spName).put("phone",phoneNumber);
                        SPUtils.getInstance(Constants.spName).put("password",password);
                        SPUtils.getInstance(Constants.spName).put("token",JSON.toJSONString(token));
                        SPUtils.getInstance(Constants.spName).put("user",JSON.toJSONString(response.getAccount()));
                        LogUtils.d("login token:"+token.getToken());
                        LogUtils.d("account:"+JSON.toJSONString(response.getAccount()));
                        // 登录成功后记录auth信息
                        Authentication.set(token.getToken());

                        if (response.getActiveCompanyId() > 0) {
                            System.out.println("current selected company " + response.getActiveCompanyId());
                        } else if (response.getCompanyCount() > 0) {
                            LogUtils.d("公司账套："+JSON.toJSONString(response.getCompanyList()));
                            SPUtils.getInstance(Constants.spName).put("companyList",JSON.toJSONString(response.getCompanyList()));
                            List<ItemsSelectType1> datas=new ArrayList<>();
                            for (int i=0;i<response.getCompanyList().size();i++){
                                ItemsSelectType1 model=new ItemsSelectType1();
                                model.setName(response.getCompanyList().get(i).getName());
                                model.setEn_name(String.valueOf(response.getCompanyList().get(i).getId()));
                                datas.add(model);
                            }
                            runOnUiThread(() -> showPopDialog(LoginActivity.this,datas));
                           
                        }
                        if (response.getMessageConfigCount() > 0) {
                            LogUtils.d("消息配置："+ JSON.toJSONString(response.getMessageConfigList()));
                        }
                        if (response.getAppGroupConfigCount() > 0) {
                            LogUtils.d("应用组配置："+JSON.toJSONString(response.getAppGroupConfigList()));
                        }
                        if (response.getHomeConfigCount() > 0) {
                            LogUtils.d("我的配置："+JSON.toJSONString(response.getHomeConfigList()));
                        }
                        if (response.getUnreadMessageCountCount() > 0) {
                            LogUtils.d("未读消息："+JSON.toJSONString(response.getUnreadMessageCountList()));
                        }
                    } else {
                        MProgressDialog.dismissProgress();
                      
                        runOnUiThread(()->MToast.makeTextLong(getApplicationContext(),header.getMessage()));
                    }
                } catch (StatusRuntimeException e) {
                    runOnUiThread(()-> MToast.makeTextLong(getApplicationContext(),e.getStatus().getDescription()));
                    MProgressDialog.dismissProgress();
                }
            }
        }).start();
        
    }



    public PopupWindow popupWindow = null;
    public int selectId = 0;
    public ItemPopListAdapter adapter;

    public void showPopDialog(final Activity ct, List<ItemsSelectType1> itemsSelectType1s) {
        if (ct == null) return;
        View view = null;
        popupWindow = null;
        WindowManager windowManager = (WindowManager) ct.getSystemService(Context.WINDOW_SERVICE);
        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) ct.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.pop_dialog_list, null);
            ListView plist = view.findViewById(R.id.mList);
            TextView tv_title = view.findViewById(R.id.tv_title);
            tv_title.setText("账套选择");
            List<ItemsSelectType1> datas = itemsSelectType1s;
            adapter = new ItemPopListAdapter(ct, datas);
            adapter.setSelectId(selectId);
            plist.setAdapter(adapter);
            plist.setSelection(selectId);
            Drawable drawable = ct.getResources().getDrawable(R.drawable.selector_check_items);
            plist.setSelector(drawable);
            plist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    popupWindow.dismiss();
                    selectId = position;
                    adapter.setSelectId(selectId);
                    adapter.notifyDataSetChanged();
                    ItemPopListAdapter.ViewHolder viewHolder = (ItemPopListAdapter.ViewHolder) view.getTag();
                    ItemsSelectType1 model = viewHolder.model;
                    
                    String companyId= model.getEn_name();
                    switchCompany(companyId);
                   
                }
            });
            popupWindow = new PopupWindow(view, 
                    windowManager.getDefaultDisplay().getWidth() - 
                    DisplayUtil.dip2px(getApplicationContext(),50),
                    LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(() -> DisplayUtil.backgroundAlpha(ct, 1f));
        DisplayUtil.backgroundAlpha(ct, 0.5f);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.showAtLocation(ct.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }





    /*切换公司-会产生新的Token*/
    public void switchCompany(String companyID) {
        runOnUiThread(()->MProgressDialog.showProgress(this,""));
        new Thread(() -> {
            ManagedChannel channel = ManagedChannelBuilder.forAddress("uu-api-test.usoftchina.com", 9620)
                    .intercept(new MobileClientAuthenticationInterceptor())
                    .usePlaintext(true)
                    .build();
            SwitchCompanyRequest request = SwitchCompanyRequest.newBuilder()
                    .setCompanyId(Integer.valueOf(companyID)).build();
            try {
                SwitchCompanyResponse response = AccountServiceGrpc.newBlockingStub(channel).switchCompany(request);
                ResponseHeader header = response.getResponseHeader();
                if (header.getSuccess()) {
                    runOnUiThread(()->MProgressDialog.dismissProgress());
                    // new authentication
                    AuthedToken token = response.getAuthedToken();
                    LogUtils.d("login token:"+token.getToken());
                    // 登录成功后记录auth信息
                    Authentication.set(token.getToken());
                    LogUtils.d(""+response.getAuthedToken());
                    
                    SPUtils.getInstance(Constants.spName).put("token",JSON.toJSONString(token));
//                    // 新的消息中心配置
//                    repeated MessageConfig messageConfig = 3;
//                    // 新的未读消息统计
//                    repeated UnreadMessageCount unreadMessageCount = 4;
//                    // 新的应用中心配置
//                    repeated AppGroupConfig appGroupConfig = 5;
//                    // 新的我的主页配置
//                    repeated HomeConfig homeConfig = 6;
                    if (response.getMessageConfigCount()>0){
                      String messageList=  JSON.toJSONString(response.getMessageConfigList());
                      SPUtils.getInstance(Constants.spName).put("messageList",messageList);
                      //LogUtils.d("messageList:"+messageList);
                      
                      List<MessageConfigBean> messageConfigs=
                              //JSON.parseObject(messageList,new TypeReference<List<MessageConfigBean>>(){}); // Json 转List
                              JSON.parseArray(messageList,MessageConfigBean.class);
                      //LogUtils.d("messageConfigs:"+JSON.toJSONString(messageConfigs));
                      
                    }
                    
                    if (response.getAppGroupConfigCount()>0){
                        String appGroupList=JSON.toJSONString(response.getAppGroupConfigList());
                        SPUtils.getInstance(Constants.spName).put("appGroupList",appGroupList);
                        LogUtils.d("appGroupList:"+appGroupList);
                        
                        List<GroupMessageBean> messageBeans=JSON.parseArray(appGroupList,GroupMessageBean.class);
                        LogUtils.d("appGroupList:"+JSON.toJSONString(messageBeans));
                        
                    }
                    
                    if (response.getHomeConfigCount()>0){
                        String homeList=JSON.toJSONString(response.getHomeConfigList());
                        SPUtils.getInstance(Constants.spName).put("homeList:",homeList);
                        //LogUtils.d("homeList:"+homeList);
                    }
                    
                    if (response.getUnreadMessageCountCount()>0){
                        String unreadMessageList=JSON.toJSONString(response.getUnreadMessageCountList());
                        SPUtils.getInstance(Constants.spName).put("unreadMessageList:",unreadMessageList);

                        //LogUtils.d("unreadMessageList:"+unreadMessageList);
                    }
                    
                    
                    //登录成功
                    ARouter.getInstance().build("/app/main").navigation();
                    finish();
                } else {
                    runOnUiThread(()->{
                        MProgressDialog.dismissProgress();
                        MToast.makeTextLong(getApplicationContext(),header.getMessage());
                    });
                }
            } catch (StatusRuntimeException e) {
                runOnUiThread(()->{MProgressDialog.dismissProgress();
                    MToast.makeTextLong(getApplicationContext(),e.getStatus().getDescription());
                });
            }
        }).start();
    }
    
    
}
