package com.example.iot_controlhost.ui.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;

import androidx.annotation.NonNull;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.base.BaseDialog;
import com.example.iot_controlhost.databinding.DialogStartCoeducationBinding;
import com.example.iot_controlhost.model.Silkworm;
import com.example.iot_controlhost.model.SilkwormNew;
import com.example.iot_controlhost.model.net.Batch;
import com.example.iot_controlhost.model.net.CommonResponse;
import com.example.iot_controlhost.ui.view.CustomSpinnerAdapter;
import com.example.iot_controlhost.utils.DialogUtil;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.database.SilkwormDBManager;
import com.example.iot_controlhost.utils.global.AIModelSet;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.RxTag;
import com.example.iot_controlhost.utils.network.Url;
import com.example.iot_controlhost.utils.network.XHttpManager;
import com.example.iot_controlhost.utils.network.XHttpShorthand;
import com.example.iot_controlhost.utils.log.UserLog;
import com.example.iot_controlhost.utils.log.MyLog;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;

import org.xutils.http.RequestParams;
import org.xutils.x;

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

/**
 * @Description 开始共育弹窗
 * @Author DuanKaiji
 * @CreateTime 2024年03月06日 09:39
 */
public class StartCultivateDialog extends BaseDialog<DialogStartCoeducationBinding> {

    public StartCultivateDialog(@NonNull Context context, List<Batch.DataDTO> batchs) {
        super(context, true);
        List<String> seasons = new ArrayList<>();
        for (Batch.DataDTO season : batchs) {
            seasons.add(season.getBatchName());
        }
        //初始化界面控件
        binding.textView3.setText("开始" + (RoomSetting.getType() == 4 ? "催青" : "共育"));
        binding.btnYes.setText("开始" + (RoomSetting.getType() == 4 ? "催青" : "共育"));
        binding.tvSeason.setAdapter(new CustomSpinnerAdapter(mContext, seasons.toArray(new String[0])));
        binding.tiDays.setText("1");
        binding.tvSeason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本改变时执行的操作
                binding.tvVariety.setText(null);
                for (Batch.DataDTO dto : batchs) {
                    if (s.toString().equals(dto.getBatchName())) {
                        List<String> variety = new ArrayList<>();
                        for (Batch.DataDTO.ItemsDTO v : dto.getItems()) {
                            variety.add(v.getSilkwormEggName());
                        }
                        binding.tvVariety.setAdapter(new CustomSpinnerAdapter(mContext, variety.toArray(new String[0])));
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.btnYes.setOnClickListener(view -> {
            //记录开始养蚕的所有信息
            if (binding.tvSeason.getText().toString().isEmpty()) {
                infoTips("请选择蚕季");
                return;
            }
            if (binding.tvVariety.getText().toString().isEmpty()) {
                infoTips("请选择品种");
                return;
            }
            int age;
            double number;
            try {
                age = Integer.parseInt(binding.tiDays.getText().toString());
            } catch (Exception e) {
                infoTips("请正确填写蚕龄");
                return;
            }
            try {
                number = Double.parseDouble(binding.tiNumber.getText().toString());
            } catch (Exception e) {
                infoTips("请正确填写数量");
                return;
            }
            for (Batch.DataDTO dto : batchs) {
                if (binding.tvSeason.getText().toString().equals(dto.getBatchName())) {
                    for (Batch.DataDTO.ItemsDTO v : dto.getItems()) {
                        if (binding.tvVariety.getText().toString().equals(v.getSilkwormEggName())) {
                            startCultivate(v.getSilkwormEggId(), dto.getBatchName(), binding.tvVariety.getText().toString(), age, number);
                            MMKVUtil.put(AIModelSet.AI_CONTROL_PROGRAM_ID, v.getIntelligentControlProgramID());
//                            MMKVUtil.put(AIModelSet.AI_CONTROL_PROGRAM_TOTAL_DAYS, days);//todo 需要共育总天数
                            dismiss();
                            return;
                        }
                    }
                }
            }
        });
        binding.tiNumber.setOnClickListener(v -> new NumberInputDialog(mContext, binding.tiNumber).show());
        binding.tiDays.setOnClickListener(v -> new NumberInputDialog(mContext,  binding.tiDays).show());
    }

    /**
     * 开始共育-网络请求
     *
     * @param season  蚕季/批次
     * @param variety 蚕种
     * @param age     蚕龄
     * @param number  数量
     */
    private void startCultivate(String SilkwormEggId, String season, String variety, int age, double number) {
        //此次蚕期
        Date startTime = TimeUtils.getDateByNow(-(age - 1), TimeConstants.DAY);
        //网络请求
        DialogUtil.showLoadingDialog(mContext, "正在记录中，请稍等...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.startCultivate);
        params.addParameter("areaCode", RoomSetting.getAreaCode());
        params.addParameter("SilkwormEggId", SilkwormEggId);
        params.addParameter("FeedingNum", String.valueOf(number));
        params.addParameter("StartTime", MyUtil.getFormatDateTime(startTime));
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                //记录此次蚕期
                SilkwormDBManager.INSTANCE.init(new SilkwormNew(model.getData().toString(), season, startTime, null, number, variety));
                String cultivateType = RoomSetting.getType() == 4 ? "催青" : "共育";
                UserLog.task("开始" + cultivateType + "登记：批次=" + season);
                MyLog.app("开始" + cultivateType + "登记成功：批次=" + season + "，品种=" + variety
                        + "，数量=" + number + "，起始龄期=" + age + "天");
                //开始共育后切换为自动模式
                dismiss();
                RxBusUtils.get().post(RxTag.UPDATE_MAIN, 7);
//                MyUtil.relaunchApp();
            }

            @Override
            public void onSuccessError(CommonResponse data) {
                String cultivateType = RoomSetting.getType() == 4 ? "催青" : "共育";
                UserLog.taskError("开始" + cultivateType + "登记失败");
                MyLog.networkError("开始" + cultivateType + "登记失败：" + data.getMessage());
                errorTips("服务器-开始"+(RoomSetting.getType() == 4 ? "催青" : "共育")+"失败:" + data.getMessage());
            }

            @Override
            public void error(Throwable e) {
                String cultivateType = RoomSetting.getType() == 4 ? "催青" : "共育";
                UserLog.taskError("开始" + cultivateType + "登记失败");
                MyLog.networkError("开始" + cultivateType + "登记网络请求失败：" + e.getMessage());
                errorTips("开始"+(RoomSetting.getType() == 4 ? "催青" : "共育")+"网络请求失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUtil.hideLoadingDialog();
            }

        });
    }
}
