package com.example.iot_controlhost.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.R;
import com.example.iot_controlhost.adapter.StageAdapter;
import com.example.iot_controlhost.adapter.WorkAdapter;
import com.example.iot_controlhost.adapter.WorkAdapterInterface;
import com.example.iot_controlhost.base.BaseDialog;
import com.example.iot_controlhost.databinding.DialogNewWorkBinding;
import com.example.iot_controlhost.databinding.ItemBtnBinding;
import com.example.iot_controlhost.model.net.Batch;
import com.example.iot_controlhost.model.net.CommonResponse;
import com.example.iot_controlhost.model.net.ControlMode;
import com.example.iot_controlhost.model.net.StageList;
import com.example.iot_controlhost.model.net.WorkList;
import com.example.iot_controlhost.model.net.WorkStage;
import com.example.iot_controlhost.model.thread.QueueIOTask;
import com.example.iot_controlhost.utils.DialogUtil;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.PollingTask;
import com.example.iot_controlhost.utils.QRCodeUtil;
import com.example.iot_controlhost.utils.database.SilkwormDBManager;
import com.example.iot_controlhost.utils.database.TempTHVDBManager;
import com.example.iot_controlhost.utils.global.AutoModelSet;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.RxTag;
import com.example.iot_controlhost.utils.log.UserLog;
import com.example.iot_controlhost.utils.log.MyLog;
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.xuexiang.rxutil2.rxbus.RxBusUtils;

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

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import es.dmoral.toasty.Toasty;

/**
 * @Description 登记工作/开始共育弹窗
 * @Author DuanKaiji
 * @CreateTime 2024年03月06日 09:04
 */
public class WorkNewDialog extends BaseDialog<DialogNewWorkBinding> {
    /**
     * 作业开始时间
     */
    public static String START_WORK_TIME = "START_WORK_TIME";

    PollingTask pollingTask;
    WorkList workList;
    StageList stageList;
    WorkAdapter workAdapter;
    StageAdapter stageAdapter;

    public WorkNewDialog(@NonNull Context context) {
        super(context);
        pollingTask = PollingTask.getInstance();
        binding.btnScan.setOnClickListener(v -> {
            showImageDialog(mContext, QRCodeUtil.createQRCodeBitmap(RoomSetting.getAreaCode(), 300, 300,
                    BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo_blue), 30));
        });
        binding.btnStopStage.setOnClickListener(v -> {
            // 结束阶段
            String stoppedStage = binding.tvStageCurrent.getText().toString();
            binding.tvStageCurrent.setText("");
            binding.tvStageContent.setText("");
            if (RoomSetting.getMode() != 0) {
                // 进入手动模式
                RxBusUtils.get().post(RxTag.UPDATE_MAIN, 5);
            }
            TempTHVDBManager.INSTANCE.setStage(null, null);
            UserLog.task("结束作业阶段：" + (stoppedStage.isEmpty() ? "未命名阶段" : stoppedStage));
            MyLog.app("结束作业阶段，控制模式切换为手动模式：" + stoppedStage);
        });
        binding.btnStopWork.setOnClickListener(v -> {
            // 结束作业
            binding.tvWorkCurrent.setText("");
            binding.tvWorkContent.setText("");
            stopWork();
            // 恢复之前的设置
            TempTHVDBManager.INSTANCE.appSet();
            if (RoomSetting.getMode() == 1) {
                // 如果是自动模式，则刷新自动模式参数
                RxBusUtils.get().post(RxTag.UPDATE_AUTO, 3);
            }
        });
        String state = (SilkwormDBManager.isStarting() ? "结束" : "开始") + (RoomSetting.getType() == 4 ? "催青" : "共育");
        binding.btnCultivateStart.setText(state);
        binding.btnCultivateStart.setBackground(mContext.getDrawable(SilkwormDBManager.isStarting() ? R.drawable.bg_work_orange : R.drawable.bg_work_blue));
        binding.btnCultivateStart.setOnClickListener(view -> {
            if (SilkwormDBManager.isStarting()) {
                //结束共育
                new ConfirmDialog(mContext, mContext.getString(R.string.warning), "您确定要结束" + (RoomSetting.getType() == 4 ? "催青" : "共育") + "吗？", () -> stopCultivate()).show();
            } else {
                //开始共育
                loadSeason();
            }
        });
        workAdapter = new WorkAdapter(new ArrayList<>(), ItemBtnBinding.class, binding.tvWorkCurrent, binding.tvWorkContent, content -> startWork(content));
        binding.rvWork.setAdapter(workAdapter);
        binding.rvWork.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        stageAdapter = new StageAdapter(new ArrayList<>(), ItemBtnBinding.class,
                binding.tvStageCurrent, binding.tvStageContent);
        binding.rvStage.setAdapter(stageAdapter);
        binding.rvStage.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        refreshNewWorkList();
        // 初始化界面
        if (RoomSetting.getWorkState() != null) {
            binding.tvWorkCurrent.setText(RoomSetting.getWorkState().get("name"));
            binding.tvWorkContent.setText("正在作业中");
            binding.btnStopWork.setVisibility(View.VISIBLE);
        } else {
            binding.tvWorkCurrent.setText("");
            binding.tvWorkContent.setText("");
            binding.btnStopWork.setVisibility(View.GONE);
        }
        if (TempTHVDBManager.INSTANCE.getStageName() != null) {
            binding.tvStageCurrent.setText(TempTHVDBManager.INSTANCE.getStageName());
            binding.tvStageContent.setText(TempTHVDBManager.INSTANCE.getStageContent());
        } else {
            binding.tvStageCurrent.setText("");
            binding.tvStageContent.setText("");
        }
    }

    public void showImageDialog(Context context, Bitmap bitmap) {
        Dialog dialog = new Dialog(context);
        ImageView imageView = new ImageView(context);
        imageView.setImageBitmap(bitmap);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setAdjustViewBounds(true);
        imageView.setOnClickListener(v -> dialog.dismiss());
        dialog.setContentView(imageView);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
    }

    public void refreshNewWorkList() {
        // 获取新作业、阶段信息
        DialogUtil.showLoadingDialog(mContext, "正在读取作业列表中...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getWorkList);
        params.addParameter("areaCode", RoomSetting.getAreaCode());
        x.http().get(params, new XHttpShorthand<WorkList>() {
            @Override
            public void success(WorkList model) {
                workList = model;
                workAdapter.setDataList(workList.getData());
            }

            @Override
            public void error(Throwable e) {
                errorTips("作业列表获取失败，请检查网络");
                MyLog.networkError("作业列表获取失败：" + e.getMessage());
            }

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

        });
        DialogUtil.showLoadingDialog(mContext, "正在读取阶段列表中...");
        RequestParams params2 = XHttpManager.getInstance().getRequestParams(Url.getStageList);
        params2.addParameter("areaCode", RoomSetting.getAreaCode());
        x.http().get(params2, new XHttpShorthand<StageList>() {
            @Override
            public void success(StageList model) {
                stageList = model;
                stageAdapter.setDataList(stageList.getData());
            }

            @Override
            public void error(Throwable e) {
                errorTips("阶段列表获取失败，请检查网络");
                MyLog.networkError("阶段列表获取失败：" + e.getMessage());
            }

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

    /**
     * 开始作业-网络请求
     */
    public void startWork(String workName) {
        if (RoomSetting.getWorkState() != null) {
            Toasty.info(mContext, "当前已在进行" + RoomSetting.getWorkState().get("name") + "作业，请先结束当前作业").show();
            return;
        }
        DialogUtil.showLoadingDialog(mContext, mContext.getString(R.string.in_process));
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.startWork);
        params.addParameter("AreaCode", RoomSetting.getAreaCode());
        params.addParameter("Content", workName);
        params.addParameter("JobUserName", RoomSetting.getUserName());
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                successTips("作业开始-登记成功");
                Map<String, String> map = new HashMap<>();
                if ("消毒".equals(workName) && RoomSetting.isAirConditionForceCloseEnable()) {
                    //消毒期间将自动关闭空调
                    MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> RoomController.airConditionInfrared.setPowerSupply(false)));
                    MMKVUtil.put(RoomSetting.IS_AIR_CONDITION_FORCE_CLOSE, true);
                }
                map.put("name", workName);
                map.put("data", model.getData().toString());
                MMKVUtil.put(RoomSetting.WORK_STATE, GsonUtils.toJson(map));
                UserLog.task(workName + "作业开始-已登记");
                setStartWorkTime(new Date());
                binding.btnStopWork.setVisibility(View.VISIBLE);
//                MyLog.test(getString(R.string.work_sign_success) + "获取作业码：" + model.getData());
            }

            @Override
            public void error(Throwable e) {
                errorTips(workName + "作业开始-登记失败");
                UserLog.taskError(mContext.getString(R.string.work_sign_failed));
            }

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

    /**
     * 结束工作-网络请求
     */
    public void stopWork() {
        String workName = RoomSetting.getWorkState().get("name");
        DialogUtil.showLoadingDialog(mContext, mContext.getString(R.string.in_process));
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.stopWork);
        params.addParameter("JobRecordUniqueCode", RoomSetting.getWorkState().get("data"));
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                successTips(workName + "作业结束-登记成功");
                MMKVUtil.put(RoomSetting.WORK_STATE, null);
                UserLog.task(workName + "作业结束-已登记");
                MMKVUtil.put(RoomSetting.IS_AIR_CONDITION_FORCE_CLOSE, false);
//                MyLog.test(workName + "作业结束-登记成功,请求结果：" + model.getData());
                binding.btnStopWork.setVisibility(View.INVISIBLE);
            }

            @Override
            public void error(Throwable e) {
                errorTips(workName + "作业结束-登记失败");
                UserLog.taskError(mContext.getString(R.string.work_sign_failed));
            }

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

    /**
     * 加载蚕季信息
     */
    public void loadSeason() {
        DialogUtil.showLoadingDialog(mContext, "正在加载蚕季信息，请稍等...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getBatchPlan);
        params.addParameter("areaCode", RoomSetting.getAreaCode());
        params.addParameter("datetime", MyUtil.getDateDay());
//        params.addParameter("datetime", "2023-5-06"); //有数据
        x.http().get(params, new XHttpShorthand<Batch>() {
            @Override
            public void success(Batch model) {
                if (model.getData() == null || model.getData().size() == 0) {
                    infoTips("暂无蚕季信息");
                } else {
                    new StartCultivateDialog(mContext, model.getData()).show();
                }
            }

            @Override
            public void error(Throwable e) {
                errorTips("获取蚕季信息失败");
            }

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

    /**
     * 结束共育-网络请求
     */
    public void stopCultivate() {
        //网络请求
        DialogUtil.showLoadingDialog(mContext, "正在结束" + (RoomSetting.getType() == 4 ? "催青" : "共育") + "中，请稍等...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.stopCultivate);
        params.addParameter("UniqueCode", SilkwormDBManager.INSTANCE.getData().getId());
        params.addParameter("EndTime", MyUtil.getDateTime());
        x.http().request(HttpMethod.PUT, params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                //返回200即结束成功
                DialogUtil.hideLoadingDialog();
                //记录此次蚕期
                SilkwormDBManager.updateCurDate();
                UserLog.task("结束" + (RoomSetting.getType() == 4 ? "催青" : "共育") + "登记成功");
                //停止共育后刷新共育状态
                RxBusUtils.get().post(RxTag.UPDATE_MAIN, 7);
//                MyUtil.relaunchApp();
            }

            @Override
            public void error(Throwable e) {
                String cultivateType = RoomSetting.getType() == 4 ? "催青" : "共育";
                UserLog.taskError("结束" + cultivateType + "登记失败");
                MyLog.networkError("结束" + cultivateType + "登记失败：" + e.getMessage());
                errorTips("服务器-结束失败");
            }

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

    public static Date getStartWorkTime() {
        try {
            return DateFormat.getDateTimeInstance().parse(MMKVUtil.get(START_WORK_TIME, "2024-03-06 10:45:49"));
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

    public static void setStartWorkTime(Date startWorkTime) {
        MMKVUtil.put(START_WORK_TIME, DateFormat.getDateTimeInstance().format(startWorkTime));
    }

    @Override
    public void dismiss() {
        super.dismiss();
        pollingTask.stopPollingTask(RxTag.WORK_TIME);
    }

    public static String getInfo(WorkStage model, boolean isWork) {
        StringBuffer content = new StringBuffer();
        Map<String, Object> map = new HashMap<>();
        for (WorkStage.Data data : model.getData()) {
            ControlMode info = GsonUtils.fromJson(data.getConfigJson(), ControlMode.class);
            content.append(data.getEnvTypeName()).append("：");
            if (info.getTargetValue() != 0.0) {
                content.append("目标值：").append(info.getTargetValue()).append("，");
            }
            if (info.getWarningMaxValue() != 0.0) {
                content.append("最大值：").append(info.getWarningMaxValue()).append("，");
            }
            if (info.getWarningMinValue() != 0.0) {
                content.append("最小值：").append(info.getWarningMinValue()).append("，");
            }
            if (info.getOpenTime() != 0) {
                content.append("开启时长：").append(info.getOpenTime()).append("分钟，");
            }
            if (info.getCloseTime() != 0) {
                content.append("关闭时长：").append(info.getCloseTime()).append("分钟，");
            }
            // 删除末尾可能多余的“，”
            int len = content.length();
            if (content.charAt(len - 1) == '，') {
                content.deleteCharAt(len - 1);
            }
            content.append("\n");
            if ("温度".equals(data.getEnvTypeName())) {
                MMKVUtil.put(AutoModelSet.AUTO_TEMPERATURE, true);
                if (isWork) {
                    // 作业，保存现在的设置 在作业结束后需要恢复
                    map.put(AutoModelSet.TARGET_TEMPERATURE, AutoModelSet.getTargetTemperature());
                    map.put(AutoModelSet.MIN_TEMPERATURE, AutoModelSet.getMinTemperature());
                    map.put(AutoModelSet.MAX_TEMPERATURE, AutoModelSet.getMaxTemperature());
                }
                if (info.getTargetValue() != 0.0) {
                    MMKVUtil.put(AutoModelSet.TARGET_TEMPERATURE, info.getTargetValue());
                } else {
                    info.setTargetValue(AutoModelSet.getTargetTemperature());
                }
                if (info.getWarningMinValue() != 0.0) {
                    MMKVUtil.put(AutoModelSet.MIN_TEMPERATURE, info.getWarningMinValue());
                } else {
                    info.setWarningMinValue(AutoModelSet.getMinTemperature());
                }
                if (info.getWarningMaxValue() != 0.0) {
                    MMKVUtil.put(AutoModelSet.MAX_TEMPERATURE, info.getWarningMaxValue());
                } else {
                    info.setWarningMaxValue(AutoModelSet.getMaxTemperature());
                }
            } else if ("湿度".equals(data.getEnvTypeName())) {
                if (isWork) {
                    // 作业，保存现在的设置 在作业结束后需要恢复
                    map.put(AutoModelSet.TARGET_HUMIDITY, AutoModelSet.getTargetHumidity());
                    map.put(AutoModelSet.MIN_HUMIDITY, AutoModelSet.getMinHumidity());
                    map.put(AutoModelSet.MAX_HUMIDITY, AutoModelSet.getMaxHumidity());
                }
                MMKVUtil.put(AutoModelSet.AUTO_HUMIDITY, true);
                if (info.getTargetValue() != 0.0) {
                    MMKVUtil.put(AutoModelSet.TARGET_HUMIDITY, info.getTargetValue());
                } else {
                    info.setTargetValue(AutoModelSet.getTargetHumidity());
                }
                if (info.getWarningMinValue() != 0.0) {
                    MMKVUtil.put(AutoModelSet.MIN_HUMIDITY, info.getWarningMinValue());
                } else {
                    info.setWarningMinValue(AutoModelSet.getMinHumidity());
                }
                if (info.getWarningMaxValue() != 0.0) {
                    MMKVUtil.put(AutoModelSet.MAX_HUMIDITY, info.getWarningMaxValue());
                } else {
                    info.setWarningMaxValue(AutoModelSet.getMaxHumidity());
                }
            } else if ("通风".equals(data.getEnvTypeName())) {
                if (isWork) {
                    // 作业，保存现在的设置 在作业结束后需要恢复
                    map.put(AutoModelSet.CYCLE_START, AutoModelSet.getCycleStart());
                    map.put(AutoModelSet.CYCLE_STOP, AutoModelSet.getCycleStop());
                }
                MMKVUtil.put(AutoModelSet.AUTO_VENTILATOR, true);
                if (info.getOpenTime() != 0) {
                    MMKVUtil.put(AutoModelSet.CYCLE_START, info.getOpenTime());
                } else {
                    info.setOpenTime(AutoModelSet.getCycleStart());
                }
                if (info.getCloseTime() != 0) {
                    MMKVUtil.put(AutoModelSet.CYCLE_STOP, info.getCloseTime());
                } else {
                    info.setCloseTime(AutoModelSet.getCycleStop());
                }
            }
            // 保存当前的设置
            if (isWork) {
                // 作业，保存现在的设置 在作业结束后需要恢复
                TempTHVDBManager.INSTANCE.init(map);
            }
        }
        // 去掉最后一个换行符
        if (content.length() > 0 && content.charAt(content.length() - 1) == '\n') {
            content.deleteCharAt(content.length() - 1);
        }
        return content.toString();
    }
}
