package com.example.iot_controlhost.ui.dialog;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

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.base.BaseDialog;
import com.example.iot_controlhost.databinding.DialogWorkBinding;
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.model.net.WorkList;
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.control.infrared.MyInfraredUtils;
import com.example.iot_controlhost.utils.database.SilkwormDBManager;
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.google.android.flexbox.AlignContent;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.JustifyContent;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.rxutil2.rxjava.DisposablePool;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

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.Optional;
import java.util.stream.Collectors;

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

    PollingTask pollingTask;

    public WorkDialog(@NonNull Context context, WorkList model) {
        super(context);
        pollingTask = PollingTask.getInstance();
        binding.ivSignUp.setImageBitmap(QRCodeUtil.createQRCodeBitmap(RoomSetting.getAreaCode(), 300, 300,
                BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo_blue), 30));
        if (model != null) {
            //开始工作
            start(model);
        } else {
            stop();
        }
    }

    /**
     * 开始工作
     */
    private void start(WorkList model) {
        List<TextView> tvs = new ArrayList<>();
        Collections.addAll(tvs, binding.btnWork1, binding.btnWork2, binding.btnWork3, binding.btnWork4, binding.btnWork5, binding.btnWork6);
        View.OnClickListener work = view -> {
            String workName = ((TextView) view).getText().toString();
            //上传作业操作
            String tips = "确定要进行<" + workName + ">操作登记吗？";
            if ("消毒".equals(workName) && RoomSetting.isAirConditionForceCloseEnable()) {
                tips = tips + "消毒期间将自动关闭空调";
            }
            new ConfirmDialog(mContext, mContext.getString(R.string.warning), tips, () -> {
                startWork(workName);
                dismiss();
            }).show();
        };
        List<String> list = Optional.ofNullable(model.getData())
                .orElse(Collections.emptyList())
                .stream()
                .map(WorkList.Data::getName)
                .collect(Collectors.toList());
//        List<String> list = model.getData().stream().map(WorkList.Data::getName).collect(Collectors.toList());
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size() && i < tvs.size(); i++) {
                tvs.get(i).setText(list.get(i));
                tvs.get(i).setVisibility(View.VISIBLE);
                tvs.get(i).setOnClickListener(work);
            }
        } else {
            for (TextView tv : tvs) {
                tv.setVisibility(View.VISIBLE);
                tv.setOnClickListener(work);
            }
        }
        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();
            }
        });
    }

    /**
     * 结束工作
     */
    private void stop() {
        String workName = RoomSetting.getWorkState().get("name");
        binding.clTime.setVisibility(View.VISIBLE);
        binding.tvWorking.setText("正在进行" + workName + "作业");
        binding.flWork.setAlignContent(AlignContent.CENTER);
        binding.flWork.setAlignItems(AlignItems.CENTER);
        binding.flWork.setJustifyContent(JustifyContent.SPACE_AROUND);
        binding.btnCultivateStart.setText("结束" + workName + "工作");
        binding.btnCultivateStart.setBackground(mContext.getDrawable(R.drawable.bg_work_orange));
        binding.btnCultivateStart.setOnClickListener(view -> {
            //完成作业操作
            new ConfirmDialog(mContext, mContext.getString(R.string.warning), "确定要进行结束<" + workName + ">工作登记吗？", () -> {
                stopWork(workName);
                dismiss();
            }).show();
        });
        pollingTask.startPollingTaskOnUIThread(RxTag.WORK_TIME, 1, () -> {
            Date startWork = getStartWorkTime();
            binding.tvHour.setText(String.valueOf(Math.abs(TimeUtils.getTimeSpanByNow(startWork, TimeConstants.HOUR))));
            binding.tvMinute.setText(String.valueOf(Math.abs(TimeUtils.getTimeSpanByNow(startWork, TimeConstants.MIN) % 60)));
            binding.tvSecond.setText(String.valueOf(Math.abs(TimeUtils.getTimeSpanByNow(startWork, TimeConstants.SEC) % 60)));
        });
    }

    /**
     * 开始作业-网络请求
     */
    public void startWork(String workName) {
        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());
                new WorkDialog(mContext, null).show();
//                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) {
        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());
            }

            @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);
    }
}
