package com.qy.agv.activity;

import static com.qy.agv.comm.BaseApplication.mScanManager;
import static com.qy.agv.util.Constant.CACHE_LOGIN_KEY;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qy.agv.R;
import com.qy.agv.activity.appEnum.StatusEnum;
import com.qy.agv.activity.model.EventMessage;
import com.qy.agv.activity.model.OrderTaskModel;
import com.qy.agv.activity.model.UserModel;
import com.qy.agv.comm.BaseActivity;
import com.qy.agv.comm.CacheService;
import com.qy.agv.comm.Res;
import com.qy.agv.databinding.YgOrderTaskInfoBinding;
import com.qy.agv.util.Constant;
import com.qy.agv.util.HttpsUtil;
import com.qy.agv.util.MyProgress;
import com.qy.agv.util.StringUtils;
import com.qy.agv.util.ToastUtils;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class OrderTaskInfoActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(OrderTaskInfoActivity.class);

    private YgOrderTaskInfoBinding binding;
    private Context context;
    private UserModel user;
    private OrderTaskModel orderTaskModel;
    private PopupWindow popupWindow;
    private View popup_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgOrderTaskInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        registerReceiver();
        initCommonTop2();
        initView();
        initData();
    }


    private void initData(){
        String userStr = CacheService.getInstance(context).getCache(CACHE_LOGIN_KEY, "user");
        if(!StringUtils.isEmpty(userStr)) {
            user = new Gson().fromJson(userStr, UserModel.class);
        }
        String id = getParamString("id");
        loadTask(id);
    }

    private void parserData(){
        if(orderTaskModel == null){
            ToastUtils.showToast(context, "该设备没有登录");
            return;
        }
        if(orderTaskModel.getRunTime()==null){
            orderTaskModel.setRunTime(0L);
        }
        binding.tvTaskCode.setText(orderTaskModel.getTaskCode());
        binding.tvTaskName.setText(orderTaskModel.getTaskName());
        binding.tvStartPoint.setText(orderTaskModel.getFromAreaName()+"("+orderTaskModel.getFromAreaId()+")");
        binding.tvEndPoint.setText(orderTaskModel.getToAreaName()+"("+orderTaskModel.getToAreaId()+")");
        binding.tvStartTime.setText(orderTaskModel.getStartTime());
        binding.tvEndTime.setText(orderTaskModel.getEndTime());
        binding.tvRunTime.setText(orderTaskModel.getRunTime().toString());
        binding.tvCreateTime.setText(orderTaskModel.getCreateTime());
        StatusEnum status = StatusEnum.filter(orderTaskModel.getStatus());
        if(orderTaskModel.getStatus() == 1){
            binding.tvStatus.setTextColor(Color.BLUE);
        }else if(orderTaskModel.getStatus() == 2){
            binding.tvStatus.setTextColor(Color.parseColor("#ff00ff"));
        }else if(orderTaskModel.getStatus() == 3){
            binding.tvStatus.setTextColor(Color.GREEN);
        }else if(orderTaskModel.getStatus() == 4){
            binding.tvStatus.setTextColor(Color.RED);
        }else{
            binding.tvStatus.setTextColor(Color.DKGRAY);
        }
        binding.tvStatus.setText(status.getText());
        if(orderTaskModel.getStatus() == 1){
            openDialog();
        }
    }

    private void openDialog(){
        View v = binding.getRoot().getRootView();
        popup_view= LayoutInflater.from(context).inflate(R.layout.pw_order_task,null);
        TextView taskNameView = popup_view.findViewById(R.id.tv_task_name);
        taskNameView.setOnClickListener(view->{
            receiverTask("Loc-1-1-3");
            popupWindow.dismiss();
        });

        TextView startPointView = popup_view.findViewById(R.id.tv_start_point);
        taskNameView.setText(orderTaskModel.getTaskName());
        startPointView.setText(orderTaskModel.getFromAreaName());
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.9;
        popupWindow = new PopupWindow(v, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow.setContentView(popup_view);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow.setOnDismissListener(() -> setBackgroundAlpha(1.0f));
        setBackgroundAlpha(0.5f);
        popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
    }

    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void initView(){
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(v->{
            finish();
        });
        Button submit = findViewById(R.id.c_iv_common_submit);
        submit.setVisibility(View.GONE);

        binding.btnOk.setVisibility(View.GONE);
        binding.btnOk.setOnClickListener(v->{
            sendTask();
        });
    }

    private void registerReceiver() {
        if (mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            if(Constant.MODEL.contains("ET")) {
                filter.addAction(ET_SCAN_ACTION);
            }
            registerReceiver(mReceiver, filter);
        }
    }

    @Override
    protected String getCommonTopTitle() {
        return Res.getString("app_name");
    }

    @Override
    protected int getCommonTopICO() {
        return 0;
    }

    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        try {
            if (user == null) {
                ToastUtils.showToast(context, "该设备没有登录");
                finish();
                return;
            }
            if(!barcode.equals(orderTaskModel.getFromAreaId())){
                ToastUtils.showToast(context, "库位不存在");
            }else{
                ToastUtils.showToast(context, "核对成功");
                binding.btnOk.setVisibility(View.VISIBLE);
                popupWindow.dismiss();
            }
        }catch (Exception ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    private void loadTask(String id) {
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.ORDER_TASK_DETAIL);
        params.addBodyParameter("id", id);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") != 200) {
                        ToastUtils.showToast(context, "请求失败");
                    } else {
                        if (rs.getBoolean("success")) {
                            System.out.println(rs.get("data"));
                            orderTaskModel = new Gson().fromJson(rs.get("data").toString(), OrderTaskModel.class);
                            parserData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(OrderTaskInfoActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void sendTask(){
        if(orderTaskModel == null){
            ToastUtils.showToast(context, "任务单不能为空");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在提交");
        RequestParams params = httParams(Constant.PUSH_ORDER_TASK);
        params.addBodyParameter("id", orderTaskModel.getId());
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if(!rs.has("code")){
                        ToastUtils.showToast(context, "请求失败");
                    }else if (rs.getInt("code") != 200) {
                        ToastUtils.showToast(context, rs.getString("msg"));
                    } else {
                        if (rs.getBoolean("success")) {
                            ToastUtils.showToast(context, rs.getString("msg"));
                            new Handler().postDelayed(()->{
                                EventMessage message = new EventMessage(3, "刷新任务单");
                                EventBus.getDefault().post(message);
                            }, 100);
                            finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(OrderTaskInfoActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }
}