<template>
  <div class="parameter-adjustment">
    <s-header :name="paramsTitle" :noback="false" />

    <div class="content-container">
      <!-- 设备信息卡片 -->
      <div class="device-card">
        <div class="device-header">
          <van-icon name="desktop-o" class="icon" />
          <h3 class="device-name">
            {{ equipmentName }}
          </h3>
        </div>
      </div>

      <!-- 参数配置区 -->
      <div class="parameter-container">
        <!-- 温湿度监控模式 -->
        <div v-if="type === '3'" class="monitoring-grid">
          <div
            v-for="item in monitoringParams"
            :key="item.key"
            class="parameter-card"
          >
            <van-icon :name="item.icon" class="param-icon" />
            <div class="param-info">
              <div class="param-label">{{ $t(item.label) }}</div>
              <div class="param-value">
                {{ deviceDetal[item.key] ?? $t("device.noData") }}
                <span v-if="deviceDetal[item.key] !== null">{{
                  $t(item.unit)
                }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 调试参数模式 -->
        <div v-if="type === '2'" class="debug-panel">
          <div class="parameter-card">
            <van-icon name="weapp-nav" class="param-icon" />
            <div class="param-info">
              <div class="param-label">
                {{ $t("device.humidityInCabinet") }}
              </div>
              <div class="param-value">
                {{ deviceDetal.cabinetHd ?? $t("device.noData") }}
                <span v-if="deviceDetal.cabinetHd !== null">{{
                  $t("device.humidity")
                }}</span>
              </div>
            </div>
          </div>

          <div class="control-group">
            <van-field
              v-model="interval"
              :label="$t('device.increaseOrDecrease')"
              class="smart-field"
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  @click="updateInterval(0)"
                  class="action-btn"
                >
                  {{ $t("device.submitUpdates") }}
                </van-button>
              </template>
            </van-field>

            <div class="preset-buttons">
              <van-button
                v-for="preset in presets"
                :key="preset.type"
                type="primary"
                @click="updateInterval(preset.type)"
                class="preset-btn"
              >
                {{ $t(preset.label) }}
              </van-button>
            </div>
          </div>
        </div>

        <!-- 通用参数列表 -->
        <div class="parameter-list">
          <div
            v-for="(item, key) in paramsList"
            :key="key"
            class="parameter-item"
          >
            <van-field
              v-if="!checkBtn(item.name)"
              v-model="item.val"
              :label="paramName[key]"
              @update:model-value="onUpdateParameters(item, key, $event)"
              class="smart-field"
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  @click="updateParams(item, key)"
                  class="action-btn"
                >
                  {{ $t("device.submitUpdates") }}
                </van-button>
              </template>
            </van-field>

            <div v-else class="switch-control">
              <span class="switch-label">{{ paramName[key] }}</span>
              <van-switch
                :model-value="checked[key]"
                @update:model-value="onUpdateValue(item, key)"
                size="24px"
                class="custom-switch"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { useRoute, useRouter } from "vue-router";
import {
  getDeviceDetal,
  getParameters,
  updateParameters,
  humidityParameters,
} from "@/service/device";
import {
  showFailToast,
  showSuccessToast,
  showConfirmDialog,
  showToast,
} from "vant";
import { useI18n } from "vue-i18n";
import { styleUrl } from "../../../common/js/utils";

export default {
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    const route = useRoute();
    const router = useRouter();
    const deviceId = route.query.deviceId;
    const machineType = route.query.machineType;
    const deviceDetal = ref([]);
    const paramsTitle = ref("");
    const paramsList = ref([]);
    const comParams = ref([]);
    const paramName = ref([]);
    const checked = ref([]);
    const type = ref("");
    const isChange = ref(false);
    const howLong = ref([]);
    const interval = ref("");
    const equipmentName = route.query.name;

    const monitoringParams = ref([
      {
        key: "numberOne",
        label: "device.numberOneTm",
        unit: "device.degree",
        icon: "fire",
      },
      {
        key: "furnaceTm",
        label: "device.furnaceHeadTemperature",
        unit: "device.degree",
        icon: "fire",
      },
      {
        key: "candyGeneratorTm",
        label: "device.candyGeneratorTm",
        unit: "device.degree",
        icon: "fire",
      },
      {
        key: "cabinetTm",
        label: "device.temperatureInCabinet",
        unit: "device.degree",
        icon: "fire",
      },
      {
        key: "cabinetHd",
        label: "device.humidityInCabinet",
        unit: "device.humidity",
        icon: "weapp-nav",
      },
      {
        key: "outsideTm",
        label: "device.outsideTm",
        unit: "device.degree",
        icon: "fire",
      },
      {
        key: "outsideHd",
        label: "device.outsidehd",
        unit: "device.humidity",
        icon: "weapp-nav",
      },
    ]);

    const presets = ref([
      { type: 1, label: "device.winterParameters" },
      { type: 2, label: "device.summerParameters" },
    ]);

    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl("paramsSet");
      type.value = route.query.type;
      if (route.query.type === "0") {
        paramsTitle.value = t("device.generalParameterConfiguration");
      }
      if (route.query.type === "1") {
        paramsTitle.value = t("device.advancedParameterConfiguration");
      }
      if (route.query.type === "2") {
        paramsTitle.value = t("device.debuggingParameterConfiguration");
      }
      if (route.query.type === "3") {
        paramsTitle.value = t("device.humidityParameterConfiguration");
      }
      getDeviceDetalFun();
    });
    // 判断是否为按钮
    const checkBtn = (name) => {
      return name.includes("M");
    };
    // 获取设备列表数据
    const getDeviceDetalFun = async () => {
      const { data } = await getDeviceDetal({ id: deviceId });
      if (data.code === "00000") {
        deviceDetal.value = data.data;
        if (route.query.type != "2") {
          getParametersFun();
        }
      } else {
        showFailToast(data.message);
      }
    };
    // 获取参数列表
    const getParametersFun = async () => {
      paramsList.value = [];
      const params = {
        id: deviceId,
        status: route.query.type,
        clientId: deviceDetal.value.clientId,
      };
      const { data } = await getParameters(params);
      if (data.code) {
        paramsList.value = data.data;
        paramsList.value.forEach((paramItem) => {
          comParams.value.push(paramItem.name);
          if (machineType == 0) {
            paramName.value.push(t("paramNames." + paramItem.name));
          }
          if (machineType == 1) {
            paramName.value.push(t("popParams." + paramItem.name));
          }
          if (paramItem.val === "1") {
            checked.value.push(true);
          } else {
            checked.value.push(false);
          }
          howLong.value.push(paramItem.val != null ? paramItem.val.length : 0);
        });
      } else {
        showToast(t("device.noParameterData"));
      }
    };

    const onUpdateParameters = (item, key, e) => {
      if (howLong.value[key] != e.length) {
        isChange.value = true;
      } else {
        isChange.value = false;
      }
      item.val = e;
    };

    // 更新参数值
    const updateParams = async (item, key) => {
      const params = {
        id: deviceId,
        name: item.name,
        val: item.val,
      };
      showConfirmDialog({
        title: t("device.tips"),
        message:
          t("device.isUpdate") +
          paramName.value[key] +
          t("device.to") +
          item.val +
          "？" +
          (isChange.value ? t("device.attention") : ""),
      })
        .then(async () => {
          const { data } = await updateParameters(params);
          if (data.code) {
            showSuccessToast(t("device.modificationSucceeded"));
          } else {
            showFailToast(data.message);
          }
        })
        .catch(() => {});
    };
    const onUpdateValue = (item, key) => {
      console.log(item);
      const params = {
        id: deviceId,
        name: item.name,
        val: item.val == "0" ? "1" : "0",
      };
      showConfirmDialog({
        title: t("device.tips"),
        message: t("device.content"),
      })
        .then(async () => {
          const { data } = await updateParameters(params);
          if (data.code) {
            checked.value[key] = !checked.value[key];
            showSuccessToast(t("device.modificationSucceeded"));
            setTimeout(() => {
              router.go(-1);
            }, 1000);
          } else {
            showFailToast(data.message);
          }
        })
        .catch(() => {
          // on cancel
        });
    };

    // 一键递增递减
    const updateInterval = (value) => {
      const params = {
        id: deviceId,
        name: "allUpdate",
        val: interval.value,
      };
      if (value === 0) {
        params.name = "allUpdate";
        params.val = interval.value;
      } else if (value === 1) {
        params.name = "winter";
        params.val = "winter";
      } else {
        params.name = "summer";
        params.val = "summer";
      }
      showConfirmDialog({
        title: t("device.tips"),
        message: t("device.isUpdate") + "？",
      })
        .then(async () => {
          const { data } = await humidityParameters(params);
          if (data.code) {
            showSuccessToast(t("device.modificationSucceeded"));
          } else {
            showFailToast(data.message);
          }
        })
        .catch(() => {});
    };

    return {
      deviceDetal,
      paramsTitle,
      paramsList,
      // getParamName,
      updateParams,
      paramName,
      checked,
      onUpdateValue,
      type,
      onUpdateParameters,
      interval,
      updateInterval,
      checkBtn,
      monitoringParams,
      presets,
      equipmentName,
    };
  },
};
</script>
<style lang="less" scoped>
@primary-color: #4d6add;
@card-bg: #ffffff;
@text-primary: #2d3436;
@border-color: #e4e7ec;

.parameter-adjustment {
  background: #f8fafb;
  min-height: 100vh;
}

.content-container {
  background: #f5f6fa;
  // padding: 16px;
  height: calc(100% - 50px);
  overflow: auto;
  overflow-x: hidden;
}

.device-card {
  background: @card-bg;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin: 10px;
  padding: 16px;

  .device-header {
    display: flex;
    align-items: center;

    .icon {
      font-size: 18px;
      color: @primary-color;
      margin-right: 10px;
    }

    .device-name {
      font-size: 15px;
      color: #404d74;
      margin: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.parameter-container {
  .monitoring-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 12px;
  }

  .parameter-card {
    background: @card-bg;
    border-radius: 8px;
    margin: 0 10px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    display: flex;
    align-items: center;

    .param-icon {
      font-size: 24px;
      color: @primary-color;
      margin-right: 12px;
    }

    .param-label {
      font-size: 12px;
      color: #666;
      margin-bottom: 4px;
    }

    .param-value {
      font-size: 14px;
      color: @text-primary;
      font-weight: 500;

      span {
        color: #999;
        margin-left: 4px;
      }
    }
  }

  .control-group {
    background: @card-bg;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    margin: 10px;

    .smart-field {
      // margin-bottom: 12px;

      :deep(.van-field__label) {
        color: @primary-color;
        font-weight: 500;
      }
    }

    .preset-buttons {
      display: grid;
      gap: 12px;
      // margin: 10px;
      padding: 15px;
    }

    .preset-btn {
      width: 100%;
    }
  }

  .parameter-list {
    .parameter-item {
      background: @card-bg;
      border-radius: 8px;
      margin: 10px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      border: 1px solid #e4e7ec;
      transition: border-color 0.3s;

      &:focus-within {
        border-color: @primary-color;
        box-shadow: 0 0 0 2px rgba(77, 194, 148, 0.1);
      }

      :deep(.van-field__label) {
        font-weight: 500;
      }

      .switch-control {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 25px;

        .switch-label {
          flex: 1;
          padding-right: 16px;
          color: @primary-color;
        }
      }
    }
  }
}

.action-btn {
  background: @primary-color;
  border: none;
  transition: transform 0.2s;

  &:active {
    transform: scale(0.95);
  }
}

.safe-area {
  height: 50px;
}

:deep(.van-field__control) {
  /* 输入框容器样式 */
  border: 1px solid #e4e7ec;
  border-radius: 8px;
  padding: 5px;
  transition: border-color 0.3s;
}

:deep(.van-field) {
  /* 输入框容器样式 */
  border-radius: 8px;
  transition: border-color 0.3s;

  /* label文本居中对齐 */
  .van-field__label {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 120px;
    margin-right: 16px;
    color: @primary-color;
    font-weight: 500;

    /* 小屏幕适配 */
    @media (max-width: 480px) {
      width: 100px;
      font-size: 13px;
    }
  }

  /* 输入框内边距调整 */
  .van-field__body {
    padding: 8px 0;
  }

  /* 按钮样式微调 */
  .van-button {
    margin-left: 12px;
  }
}

@media (max-width: 480px) {
  .monitoring-grid {
    grid-template-columns: 1fr !important;
  }

  .parameter-card {
    padding: 12px !important;
  }
}
</style>
