package com.example.beijing_daxing;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableBoolean;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.example.beijing_daxing.base.BaseActivity;
import com.example.beijing_daxing.base.MyRecultCall;
import com.example.beijing_daxing.base.MyResult;
import com.example.beijing_daxing.been.PmBasePenaltyType;
import com.example.beijing_daxing.been.PmBasePersonInfo;
import com.example.beijing_daxing.been.PmRecordPenalty;
import com.example.beijing_daxing.databinding.ActivitySelectPersonInfoBinding;
import com.example.beijing_daxing.dialog.LookPictureDialog;
import com.example.beijing_daxing.dialog.PersonPenaltyDialog;
import com.example.beijing_daxing.dialog.TipsDialog;
import com.example.beijing_daxing.uitls.SharedPreferencesUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.RequestBody;

public class SelectPersonInfoActivity extends BaseActivity implements OnOptionsSelectListener {
    private ActivitySelectPersonInfoBinding binding;
    private LookPictureDialog pictureDialog;
    private PmBasePersonInfo personInfo;
    private List<String> list1;
    private List<List<String>> list2;
    private OptionsPickerView opv;
    private List<PmBasePenaltyType> list;
    private ObservableBoolean state = new ObservableBoolean(false);
    private PmRecordPenalty recordPenalty;
    private TipsDialog tipsDialog;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private PersonPenaltyDialog personPenaltyDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_select_person_info);
        tipsDialog = new TipsDialog(this);
        initSan();
        pictureDialog = new LookPictureDialog(this);
        opv = new OptionsPickerBuilder(this, this).build();
        initCheckList();
        recordPenalty = new PmRecordPenalty();
        recordPenalty.setCreateBy(SharedPreferencesUtils.getstring("user", ""));
        binding.setState(state);
        binding.checkState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                state.set(position == 1);
                recordPenalty.setCheckState(position + "");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        personPenaltyDialog = new PersonPenaltyDialog(this);
    }

    private void initCheckList() {
        OkGo.<MyResult>post(url + "/selectPenaltyTypeList")
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        if (body.getCode() == 0) {
                            list =
                                    gson.fromJson(body.getJson(), new TypeToken<List<PmBasePenaltyType>>() {
                                    }.getType());
                            list1 = new ArrayList<>();
                            list2 = new ArrayList<>();
                            Map<Long, String> map = new HashMap<>();
                            list.forEach(penaltyType -> {
                                String penaltyInfo = penaltyType.getPenaltyInfo();// 处罚说明
                                Long parentId = penaltyType.getParentId();// 父id
                                Long penaltyTypeId = penaltyType.getPenaltyTypeId();// 自id
                                if (parentId == null) {// 如果是一级菜单
                                    if (!list1.contains(penaltyInfo)) {
                                        list1.add(penaltyInfo);
                                        map.put(penaltyTypeId, penaltyInfo);
                                        list2.add(new ArrayList<>());
                                    }
                                } else {// 如果是二级菜单
                                    String tag = map.get(parentId);
                                    int i = list1.indexOf(tag);
                                    String penaltyTypeCode = penaltyType.getPenaltyTypeCode();
                                    list2.get(i).add(penaltyTypeCode + "-" + penaltyInfo);
                                }
                            });
                            opv.setPicker(list1, list2, null);
                            return;
                        }
                        Toast.makeText(SelectPersonInfoActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void readTidReault(boolean b, String bytes2HexString, byte[] rdata) {
        super.readTidReault(b, bytes2HexString, rdata);
        binding.selectInfoEpc.setText(bytes2HexString);
        OkGo.<MyResult>post(url + "/selectPersonInfo")
                .params("epc", bytes2HexString)
                .params("user", SharedPreferencesUtils.getstring("user", ""))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        if (body.getCode() == 0) {
                            personInfo = gson.fromJson(body.getJson(), PmBasePersonInfo.class);
                            String joinDate = personInfo.getJoinDate();
                            if (joinDate != null) {
                                Date currentDate = new Date();
                                String nowDate = sdf.format(currentDate);

                                Date date = null;
                                try {
                                    date = sdf.parse(joinDate);
                                } catch (ParseException e) {
                                    throw new RuntimeException(e);
                                }

                                // 优化后的日期判断逻辑
                                if (currentDate.after(date) && !nowDate.equals(joinDate)) {
                                    tipsDialog.showImage(false, "人员已过期");
                                } else {
                                    tipsDialog.showImage(true, "人员有效");
                                }

                            }
                            recordPenalty.setBasePersonId(personInfo.getBasePersonId());
                            recordPenalty.setEpc(bytes2HexString);
                            binding.setPersonInfo(personInfo);
                            Glide.with(SelectPersonInfoActivity.this).load(url.replace("/api", "") + personInfo.getPhotoPath()).into(binding.selectInfoPhoto);

                            personPenaltyDialog.setList(personInfo.getPmRecordPenalties());
                        } else {
                            tipsDialog.showImage(false, "后台管理员未录入信息");
                            if (personInfo != null) {
                                personInfo.clearUi();
                            }
                            recordPenalty.setBasePersonId(null);
                            personInfo = null;
                        }

                    }
                });
    }

    public void selectInfoPhoto(View view) {
        if (personInfo == null) {
            Toast.makeText(this, "请先查询人员信息", Toast.LENGTH_SHORT).show();
            return;
        }
        pictureDialog.setPath(url.replace("/api", "") + personInfo.getPhotoPath());
        pictureDialog.show();
    }

    public void checkSelect(View view) {
        if (personInfo == null) {
            Toast.makeText(this, "请先查询人员信息", Toast.LENGTH_SHORT).show();
            return;
        }
        opv.show();
    }

    public void selectInfoSubmit(View view) {
        if (recordPenalty.getBasePersonId() ==null){
            Toast.makeText(this, "请先查询人员信息", Toast.LENGTH_SHORT).show();
            return;
        }
        OkGo.<MyResult>post(url + "/insertRrecordPenalty")
                .upRequestBody(RequestBody.create(JSON, gson.toJson(recordPenalty)))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        if (body.getCode() == 0) {
                            finish();
                        }
                        Toast.makeText(SelectPersonInfoActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    @Override
    public void onOptionsSelect(int options1, int options2, int options3, View v) {
        String type = list1.get(options1);
        String s = list2.get(options1).get(options2);
        binding.selectPenalty.setText(s);
        s = s.substring(s.indexOf("-") + 1, s.length());
        Log.e("TAG", "onOptionsSelect:" + type + ", " + s);
        PmBasePenaltyType penaltyType = new PmBasePenaltyType();
        penaltyType.setPenaltyInfo(s);
        int index = list.indexOf(penaltyType);
        PmBasePenaltyType penaltyType1 = list.get(index);
        // 设置处罚类型
        recordPenalty.setPenaltyType(type);
        recordPenalty.setPenaltyTypeCode(penaltyType1.getPenaltyTypeCode());
        recordPenalty.setPenaltyInfo(penaltyType1.getPenaltyInfo());
        recordPenalty.setPenaltyAmount(penaltyType1.getPenaltyAmount());

    }

    public void checkPenalty(View view) {
        if (personInfo == null) {
            Toast.makeText(this, "请先查询人员信息", Toast.LENGTH_SHORT).show();
            return;
        }
        if (personInfo.getPenaltyCount() == 0){
            Toast.makeText(this, "该人员暂无处罚记录", Toast.LENGTH_SHORT).show();
            return;
        }
        personPenaltyDialog.show();
    }
}