<template>
  <view class="controller_home">
    <view class="body">
      <nut-cell>
        <nut-row>
          <nut-col :span="24">
            <nut-steps :current="current">
              <nut-step title="第一步" />
              <nut-step title="第二步" />
              <nut-step title="第三步" />
              <nut-step title="第四步" />
            </nut-steps>
          </nut-col>
        </nut-row>
      </nut-cell>
      <nut-config-provider :theme-vars="themeVars1">
        <nut-cell>
          <nut-row v-if="current === 1">
            <nut-col :span="24" class="font_36 f_weight c_222">
              检查设备
            </nut-col>
            <nut-col :span="24" class="font_32 c_666 m_t_20">
              请检查设备是否上电，网络指示灯处于常亮状态。
            </nut-col>
          </nut-row>
          <nut-row v-else-if="current === 2">
            <nut-col :span="24" class="font_36 f_weight c_222">
              请选择当前进线电压
            </nut-col>
            <nut-col :span="24" class="font_36 f_weight c_222 m_t_20">
              220V
            </nut-col>
            <nut-col :span="24" class="m_t_20">
              <nut-radio-group v-model="inputVoltage" direction="horizontal">
                <nut-radio :label="1" icon-size="20">
                  <template #checkedIcon>
                    <IconFont :name="r_v" size="20" />
                  </template>
                  A相
                </nut-radio>
                <nut-radio :label="2" icon-size="20">
                  <template #checkedIcon>
                    <IconFont :name="r_v" size="20" />
                  </template>
                  B相
                </nut-radio>
                <nut-radio :label="3" icon-size="20">
                  <template #checkedIcon>
                    <IconFont :name="r_v" size="20" />
                  </template>
                  C相
                </nut-radio>
              </nut-radio-group>
            </nut-col>
            <nut-col :span="24" class="font_36 f_weight c_222 m_t_20">
              380V
            </nut-col>
            <nut-col :span="24" class="m_t_20">
              <nut-radio-group v-model="inputVoltage" direction="horizontal">
                <nut-radio :label="4" icon-size="20">
                  <template #checkedIcon>
                    <IconFont :name="r_v" size="20" />
                  </template>
                  ABC相
                </nut-radio>
              </nut-radio-group>
            </nut-col>
          </nut-row>
          <nut-row v-else-if="current === 3">
            <nut-col :span="24" class="font_36 f_weight c_222">
              请选择设备是否插入溶解氧探头
            </nut-col>
            <nut-col :span="24" class="m_t_20">
              <nut-radio-group v-model="isHave">
                <nut-radio :label="1" icon-size="20">
                  <template #checkedIcon>
                    <IconFont :name="r_v" size="20" />
                  </template>
                  有溶解氧探头
                </nut-radio>
                <nut-radio :label="2" icon-size="20">
                  <template #checkedIcon>
                    <IconFont :name="r_v" size="20" />
                  </template>
                  无溶解氧探头
                </nut-radio>
              </nut-radio-group>
            </nut-col>
          </nut-row>
          <nut-row v-else-if="current === 4">
            <nut-col :span="24" class="font_36 f_weight c_222">
              请选择要放置塘口的设备
            </nut-col>
            <nut-col :span="24" class="m_t_20">
              <nut-checkbox-group v-model="listPutPondPartId">
                <nut-checkbox
                  label="0"
                  :style="{ width: '100%' }"
                  v-if="isHave == 1"
                >
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                  溶解氧检测仪
                </nut-checkbox>
                <nut-checkbox
                  label="1"
                  :style="{ width: '100%' }"
                  class="m_t_15"
                >
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                  开关1
                </nut-checkbox>
                <nut-checkbox
                  label="2"
                  :style="{ width: '100%' }"
                  class="m_t_15"
                >
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                  开关2
                </nut-checkbox>
                <nut-checkbox
                  label="3"
                  :style="{ width: '100%' }"
                  class="m_t_15"
                >
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                  开关3
                </nut-checkbox>
                <nut-checkbox
                  label="4"
                  :style="{ width: '100%' }"
                  class="m_t_15"
                >
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                  开关4
                </nut-checkbox>
              </nut-checkbox-group>
            </nut-col>
          </nut-row>
        </nut-cell>
        <nut-cell v-if="current == 3 && isHave == 1">
          <nut-row>
            <nut-col :span="24" class="m_t_10">
              <nut-radio-group v-model="waterType" direction="horizontal">
                <nut-radio :label="1" icon-size="25">
                  淡水
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                </nut-radio>
                <nut-radio :label="2" icon-size="25">
                  海水
                  <template #icon>
                    <IconFont :name="check" />
                  </template>
                  <template #checkedIcon>
                    <IconFont :name="check_a" />
                  </template>
                </nut-radio>
              </nut-radio-group>
            </nut-col>
            <nut-col :span="24" v-if="waterType == 2">
              <nut-config-provider :theme-vars="themeVars">
                <nut-cell
                  title="请设置您的盐度"
                  is-link
                  :desc="salt + '‰'"
                  @click="setSalt"
                ></nut-cell>
              </nut-config-provider>
            </nut-col>
            <nut-col :span="24" class="c_888 font_28">
              <view>淡水养殖无需设置，海水根据实际盐度设置。</view>
              <!-- <view>(盐度输入数值0-40‰)</view> -->
            </nut-col>
            <nut-col :span="24" class="m_t_20">
              <nut-config-provider :theme-vars="themeVars">
                <nut-cell
                  title="设置告警值"
                  is-link
                  :desc="String(alarm)"
                  @click="setAlarm"
                ></nut-cell>
              </nut-config-provider>
            </nut-col>
            <nut-col :span="24" class="c_888 font_28">
              <view>当溶解氧低于设定数值时会电话告警</view>
              <view>(数值默认为3，可设定最低值不能低于1.5) </view>
            </nut-col>
          </nut-row>
        </nut-cell>
      </nut-config-provider>
      <view>
        <nut-button
          block
          shape="square"
          size="large"
          :loading="isLoading"
          :style="{
            fontWeight: 'bold',
            fontSize: '14px !important',
            borderRadius: '10px',
            marginBottom: '15px',
          }"
          @click="prev"
          v-if="current != 1"
        >
          上一步
        </nut-button>
        <nut-button
          block
          shape="square"
          type="primary"
          size="large"
          :style="{
            fontWeight: 'bold',
            fontSize: '14px !important',
            borderRadius: '10px',
          }"
          @click="next"
          >{{ current == 4 ? "添加" : "下一步" }}</nut-button
        >
      </view>
      <nut-config-provider :theme-vars="themeVars">
        <nut-dialog v-model:visible="saltShow" text-align="left" no-footer>
          <view :style="{ height: '100%' }">
            <view class="d_body">
              <nut-row>
                <nut-col :span="24">
                  <view class="d_title">请设置您的盐度</view>
                </nut-col>
                <nut-col :span="24">
                  <nut-divider class="divider" />
                </nut-col>
                <nut-col :span="24" class="view_f">
                  <view :style="{ width: '20%' }" class="font_32 c_444"
                    >盐度</view
                  >
                  <view :style="{ width: '80%' }">
                    <nut-input
                      type="digit"
                      @blur="upValue"
                      v-model="salt"
                      placeholder="(盐度输入数值0-40‰)"
                      :border="false"
                      input-align="right"
                      max-length="5"
                      clearable
                      :cursor="String(salt).length"
                    >
                      <template #right>
                        <text class="c_222">‰</text>
                      </template>
                    </nut-input>
                  </view>
                </nut-col>
                <nut-col :span="24">
                  <nut-divider class="divider" />
                </nut-col>
              </nut-row>
            </view>
            <view class="d_btn">
              <nut-row>
                <nut-col
                  :span="12"
                  :style="{ border: '1px solid #eee', color: '#222' }"
                  @click="saltShow = false"
                >
                  取消
                </nut-col>
                <nut-col
                  :span="12"
                  :style="{ border: '1px solid #eee', color: '#15BBC5' }"
                  @click="saltShow = false"
                >
                  确定
                </nut-col>
              </nut-row>
            </view>
          </view>
        </nut-dialog>
        <nut-dialog v-model:visible="alarmShow" text-align="left" no-footer>
          <view :style="{ height: '100%' }">
            <view class="d_body">
              <nut-row>
                <nut-col :span="24">
                  <view class="d_title">低溶解氧告警值</view>
                </nut-col>
                <nut-col :span="24">
                  <nut-divider class="divider" />
                </nut-col>
                <nut-col :span="24" class="view_f">
                  <view :style="{ width: '20%' }" class="font_32 c_444"
                    >告警值</view
                  >
                  <view :style="{ width: '80%' }">
                    <nut-input
                      type="digit"
                      @blur="upAlarmValue"
                      v-model="alarm"
                      placeholder="1.5~20"
                      :border="false"
                      input-align="right"
                      max-length="5"
                      clearable
                      :cursor="String(alarm).length"
                    >
                      <template #right>
                        <text class="c_222">Mg/L</text>
                      </template>
                    </nut-input>
                  </view>
                </nut-col>
                <nut-col :span="24">
                  <nut-divider class="divider" />
                </nut-col>
              </nut-row>
            </view>
            <view class="d_btn">
              <nut-row>
                <nut-col
                  :span="12"
                  :style="{ border: '1px solid #eee', color: '#222' }"
                  @click="alarmShow = false"
                >
                  取消
                </nut-col>
                <nut-col
                  :span="12"
                  :style="{ border: '1px solid #eee', color: '#15BBC5' }"
                  @click="alarmShow = false"
                >
                  确定
                </nut-col>
              </nut-row>
            </view>
          </view>
        </nut-dialog>
      </nut-config-provider>
    </view>
    <!-- 弹出层提示 -->
    <nut-toast
      :msg="state.msg"
      v-model:visible="state.show"
      :type="state.type"
    />
  </view>
</template>
<script lang="ts" setup>
import Taro from "@tarojs/taro";
import { stateType } from "@/utils/types";
import { addDeviceController, checkDeviceStatus } from "@/api/device";
import { IconFont } from "@nutui/icons-vue-taro";
import { imgUrl } from "@/utils/imgUrl";

definePageConfig({
  navigationBarTitleText: "添加测控一体机",
});
const instance = Taro.getCurrentInstance();
const r = instance.router.params.params;
const page = instance.router.params.page;

console.log('URL参数原始值', r);
let params: any = undefined;
try {
  if (r) {
    // URL解码后再解析JSON
    const decodedParams = decodeURIComponent(r);
    console.log('URL解码后', decodedParams);
    params = JSON.parse(decodedParams);
    console.log('解析后的参数', params);
  } else {
    console.error('未获取到params参数');
  }
} catch (e) {
  console.error('参数解析失败', e, '原始参数:', r);
  // 参数解析失败，显示提示后返回
  Taro.showModal({
    title: '提示',
    content: '参数错误，请重新进入',
    showCancel: false,
    success: () => {
      Taro.navigateBack();
    }
  });
}
const check = `https://www.yuceyun.cn/wechat/check.png`;
const check_a = `https://www.yuceyun.cn/wechat/check_a.png`;
const r_v = `https://www.yuceyun.cn/wechat/r_v.png`;
// const params = {
//     devNum: "12312399",
//     devType: 2,
//     pondId: [1],
//     pondName: "我的一号塘口"
// }
// 步骤
const current = ref<number>(1);
const themeVars = ref({
  cellBoxShadow: "0px 0px 0px 0px",
  cellPadding: "0",
  cellColor: "#666666",
  cellTitleFont: "32rpx",
  cellTitleDescFont: "30rpx",
  cellDescFont: "30rpx",
  cellDescColor: "#222222",
  popupBorderRadius: "10rpx",
  checkboxLabelFontSize: "30rpx",
});
const themeVars1 = ref({
  radioLabelFontSize: "30rpx",
});
// 盐度
const salt = ref<number>(40);
// 电压
const inputVoltage = ref<number>(1);
const saltShow = ref<boolean>(false);
const alarm = ref<number>(3);
const alarmShow = ref<boolean>(false);
const isHave = ref<number>(1);
const listPutPondPartId = ref(["0"]);
const state: stateType = reactive({
  msg: "",
  type: "text",
  center: true,
  show: false,
});
const status = ref(0);
const isLoading = ref<boolean>(false);
const waterType = ref<number>(1);

/** ----------------metod start------------------ */
// 监测设备在线状态
function getCheckDevice() {
  if (!params) {
    console.error('params参数为空');
    state.show = true;
    state.msg = '参数错误';
    return;
  }
  
  const data = {
    devicetype: params.devType,
    serialnum: params.devNum,
  };
  console.log('检查设备状态', data);
  isLoading.value = true;
  checkDeviceStatus(data)
    .then((res: any) => {
      if (res.code == 200) {
        status.value = res.data;
        if (status.value == 0) {
          state.show = true;
          state.msg = "设备未激活";
        } else if (status.value == 1) {
          current.value = 2;
        } else if (status.value == 3) {
          state.show = true;
          state.msg = "设备离线";
        } else if (status.value == 8) {
          state.show = true;
          state.msg = "设备禁用";
        } else {
          state.show = true;
          state.msg = "设备异常";
        }
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
}
function next() {
  if (!params) {
    state.show = true;
    state.msg = '参数错误';
    return;
  }
  
  const num = current.value;
  if (num == 4) {
    // 验证参数，发起添加设备请求
    if (salt.value) {
      if (Number(salt.value) < 0 || Number(salt.value) > 40) {
        state.show = true;
        state.msg = "盐度范围为0-40";
        return;
      }
    } else {
      state.show = true;
      state.msg = "请录入盐度";
      return;
    }
    if (alarm.value) {
      if (Number(alarm.value) < 1.5 || Number(alarm.value) > 20) {
        state.show = true;
        state.msg = "告警值范围为1.5-20";
        return;
      }
    } else {
      state.show = true;
      state.msg = "请录入告警值";
      return;
    }
    if (listPutPondPartId.value.length <= 0) {
      state.show = true;
      state.msg = "请选择放置的设备";
      return;
    }
    // 发起添加设备请求
    const data = {
      serialNum: params.devNum,
      pondId: params.pondId[0],
      salinityCompensation: waterType.value == 1 ? 0 : Number(salt.value),
      oxyWarnLower: Number(alarm.value),
      inputVoltage: Number(inputVoltage.value),
      listPutPondPartId: listPutPondPartId.value,
      isOxygenUsed:isHave.value==1?true:false
    };
    console.log('添加设备数据', data);
    addDeviceController(data).then((res) => {
      if (res.code == 200) {
        Taro.redirectTo({
          url: "/my/addDevSuccess?name=添加测控一体机&page=" + page,
        });
      }
    });
  } else {
    if (num != 1 && status.value == 1) {
      current.value = num + 1;
    }
    if (num == 1) {
      // 检查设备状态
      getCheckDevice();
    } else {
    }
    return;
  }
}
// 上一步
function prev() {
  const num = current.value;
  current.value = num - 1;
}
// 设置盐度弹框
function setSalt() {
  saltShow.value = true;
}
// 验证输入框内容
function upValue() {
  const val = salt.value;
  if (Number(val) < 0 || Number(val) > 40) {
    salt.value = 40;
  }
}
// 设置高净值弹框
function setAlarm() {
  alarmShow.value = true;
}
// 验证输入框内容
function upAlarmValue() {
  const val = alarm.value;
  if (Number(val) < 1.5 || Number(val) > 20) {
    alarm.value = 20;
  }
}
/** ----------------metod end-------------------- */
</script>

<style lang="scss">
.controller_home {
  width: 100%;
  height: 100%;
  background-image: url("https://www.yuceyun.cn/wechat/bg.jpg");
  background-color: #e5ebed;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: fixed;
  margin: 0;

  font-size: 32px;
  font-family: "PingFang SC";
  font-weight: 400;

  .body {
    padding: 15px;

    .title {
      font-size: 32px;
      color: #222;
      font-weight: bold;
    }

    .time {
      font-size: 24px;
      color: #666666;
    }

    .mt {
      margin-top: 10px;
    }

    .content {
      margin-top: 10px;
      font-size: 28px;
      color: #444;
    }

    .tag {
      background: RGB(21, 137, 233, 0.1);
      border-radius: 4px;
      color: #1589e9;
      font-size: 28rpx;
      margin-left: 10px;
    }

    .price {
      font-size: 48px;
      color: #444444;
      font-weight: bold;
      text-align: right;
    }

    .nut-dialog {
      padding: 0;
    }

    .nut-dialog__content {
      margin: 0;
    }

    .nut-input {
      padding: 20rpx 0;
    }
  }
}
</style>
