package com.police.policedatasystem.data.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.police.policedatasystem.R;
import com.police.policedatasystem.apply.activity.ApplyActivity;
import com.police.policedatasystem.apply.activity.QueryApplyResultActivity;
import com.police.policedatasystem.apply.model.ApplyType;
import com.police.policedatasystem.apply.model.DetailQueryResult;
import com.police.policedatasystem.data.model.PoliceEmergencyDetail;
import com.police.policedatasystem.databinding.ActivityPoliceEmergencyDetailBinding;
import com.police.policedatasystem.http.CustomCallBack;
import com.police.policedatasystem.http.RequestClient;
import com.police.policedatasystem.main.App;
import com.police.policedatasystem.util.Constants;
import com.police.policedatasystem.util.UiUtils;

import java.util.List;

import okhttp3.Call;

/**
 * 警情详情页面
 */
public class PoliceEmergencyDetailActivity extends Activity {

    private ActivityPoliceEmergencyDetailBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPoliceEmergencyDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.wm.setTextSize(50);
        binding.wm.setText(Constants.SFZH);
        binding.ivBack.setOnClickListener(view -> finish());
        PoliceEmergencyDetail detail = new Gson().fromJson(getIntent().getStringExtra("param"), PoliceEmergencyDetail.class);
        if (UiUtils.isNotEmpty(detail.getZp())) {
            Glide.with(App.getApp()).asBitmap().load(detail.getZp()).into(binding.includePersonInfo.ivZp);
        }
        setText(binding.includeBaseInfo.tvJcjbh, detail.getJcjbh());//报警编号
        setText(binding.includeBaseInfo.tvBjjyqk, detail.getBjjyqk());//报警内容
        setText(binding.includeBaseInfo.tvBjrlxdh, detail.getBjrlxdh());//报警电话
        setText(binding.includeBaseInfo.tvJjsj, UiUtils.formatTime(detail.getJjsj()));//报警时间
        setText(binding.includeBaseInfo.tvAsjfsdddzmc, detail.getAsjfsdddzmc());//报警位置
        setText(binding.includeBaseInfo.tvCjdwgajgjgdm, detail.getCjdwgajgjgdm());//出警单位
        setText(binding.includeBaseInfo.tvCjrxm, detail.getCjrxm());//出警民警
        setText(binding.includeBaseInfo.tvJqlb, detail.getJqlb());//警情类别
        setText(binding.includeBaseInfo.tvCllb, detail.getCllx());//处理类型
        setText(binding.includeBaseInfo.tvCljg, detail.getCljg());//处理结果

        setText(binding.includePersonInfo.tvBq, detail.getBq());//标签
        setText(binding.includePersonInfo.tvJg, detail.getJg());//籍贯
        setText(binding.includePersonInfo.tvXm, detail.getXm());//姓名
        setText(binding.includePersonInfo.tvXb, detail.getXb());//性别
        setText(binding.includePersonInfo.tvMz, detail.getMz());//民族
        setText(binding.includePersonInfo.tvHyzk, detail.getHyzk());//婚姻状况
        setText(binding.includePersonInfo.tvSfzh, detail.getBjrzjhm());//身份证号
        setText(binding.includePersonInfo.tvNl, detail.getNl());//年龄
        setText(binding.includePersonInfo.tvFwcs, detail.getFwcs());//服务场所
        setText(binding.includePersonInfo.tvLsbjcs, detail.getLsbjcs());//历史报警次数

        setText(binding.includeCjyaInfo.tvContent, detail.getLsbjcs());//todo 处警预案

        binding.includeQueryInfo.tvQueryType1.setOnClickListener(view -> {
            queryType = 1;
            changeView();
        });
        binding.includeQueryInfo.tvQueryType2.setOnClickListener(view -> {
            queryType = 2;
            changeView();
        });
        binding.includeQueryInfo.tvQueryType3.setOnClickListener(view -> {
            queryType = 3;
            changeView();
        });
        binding.includeQueryInfo.tvQueryBtn.setOnClickListener(view -> {
            sendQuery();
        });
        binding.includeApplyInfo.tvQueryResult.setOnClickListener(view -> {
            //跳转到赋能详情
            jumpApplyDetail(detail.getJcjbh());
        });
        binding.includeApplyInfo.tvGoApply.setOnClickListener(view -> {
            jumpApplyFragment(detail.getJcjbh());
        });
        binding.includeApplyInfo.tvMakeCall.setOnClickListener(view -> {
            //拨打电话660110
            makeCall();
        });
    }

    private void jumpApplyFragment(String jqbh) {
        RequestClient.instance().getApplyType(new CustomCallBack<List<ApplyType>>() {
            @Override
            public void onError(Call call, @NonNull Exception e) {

            }

            @Override
            public void onSuccess(List<ApplyType> value) {
                if (value.isEmpty()) {
                    Toast.makeText(PoliceEmergencyDetailActivity.this, "用户未在大数据实战赋能系统登记，无法填写工单", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(PoliceEmergencyDetailActivity.this, ApplyActivity.class);
                    intent.putExtra("jqbh", jqbh);
                    startActivity(intent);
                }
            }
        });

    }

    private void jumpApplyDetail(String jqbh) {
        RequestClient.instance().getApplyType(new CustomCallBack<List<ApplyType>>() {
            @Override
            public void onError(Call call, @NonNull Exception e) {

            }

            @Override
            public void onSuccess(List<ApplyType> value) {
                if (value.isEmpty()) {
                    Toast.makeText(PoliceEmergencyDetailActivity.this, "用户未在大数据实战赋能系统登记，无法查看结果", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(PoliceEmergencyDetailActivity.this, QueryApplyResultActivity.class);
                    intent.putExtra("jqbh", jqbh);
                    startActivity(intent);
                }
            }
        });
    }

    private void makeCall() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            // 权限尚未被授予
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    500);
        } else {
            // 权限已经被授予，可以拨打电话
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:660110"));
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (requestCode == 500) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以拨打电话
                makeCall();
            }
        }
    }

    private void sendQuery() {
        String str = binding.includeQueryInfo.etInput.getText().toString();
        if (str.isEmpty()) {
            Toast.makeText(this, "请输入查询内容", Toast.LENGTH_SHORT).show();
            return;
        }
        RequestClient.instance().policeEmergencyDetailQuery(queryType, str, new CustomCallBack<DetailQueryResult>() {
            @Override
            public void onError(Call call, @NonNull Exception e) {
                Toast.makeText(PoliceEmergencyDetailActivity.this, "查询失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(DetailQueryResult value) {
                binding.includeQueryInfo.tvQueryResult.setText(value.getGOBACK());
            }
        });
    }

    private int queryType = 1;

    private void changeView() {
        binding.includeQueryInfo.tvQueryType1.setTextColor(queryType == 1 ? getColor(R.color.white) : getColor(R.color.color_999));
        binding.includeQueryInfo.tvQueryType2.setTextColor(queryType == 2 ? getColor(R.color.white) : getColor(R.color.color_999));
        binding.includeQueryInfo.tvQueryType3.setTextColor(queryType == 3 ? getColor(R.color.white) : getColor(R.color.color_999));
        binding.includeQueryInfo.tvQueryType1.setBackgroundResource(queryType == 1 ? R.drawable.all_7_main_bg : R.drawable.all_7_999_border_bg);
        binding.includeQueryInfo.tvQueryType2.setBackgroundResource(queryType == 2 ? R.drawable.all_7_main_bg : R.drawable.all_7_999_border_bg);
        binding.includeQueryInfo.tvQueryType3.setBackgroundResource(queryType == 3 ? R.drawable.all_7_main_bg : R.drawable.all_7_999_border_bg);
    }

    public static void startAction(Context context, String num) {
        Intent intent = new Intent(context, PoliceEmergencyDetailActivity.class);
        intent.putExtra("param", num);
        context.startActivity(intent);
    }

    private void setText(TextView view, String str) {
        if (UiUtils.isNotEmpty(str)) {
            view.setText(str);
        } else {
            view.setText("无");
        }
    }
}