<template>
  <!-- 设备参数调整 -->
  <div class="paramsSetPage flex-col">
    <s-header :name="paramsTitle" :noback="false"></s-header>
    <div class="paramsSetBox mod1 flex-col">
      <div class="wrap2 flex-col van-hairline--bottom">
        <div class="outer1 flex-row justify-between">
          <div class="block1 flex-col"></div>
          <span class="txt2">{{ $t('device.equipmentName') }}：{{ deviceDetal ? deviceDetal.name : "" }}</span>
        </div>
      </div>
      <!-- <van-divider :style="{ margin: '5px 16px' }" /> -->
      <div class="" v-if="type == '3'">
        <van-field :label="$t('device.numberOneTm')" :model-value="(deviceDetal.numberOne == null ? $t('device.noData') : deviceDetal.numberOne + $t('device.degree'))" readonly />
        <van-field :label="$t('device.furnaceHeadTemperature')" :model-value="(deviceDetal.furnaceTm == null ? $t('device.noData') : deviceDetal.furnaceTm + $t('device.degree'))" readonly />
        <van-field :label="$t('device.candyGeneratorTm')" :model-value="(deviceDetal.candyGeneratorTm == null ? $t('device.noData') : deviceDetal.candyGeneratorTm + $t('device.degree'))" readonly />
        <van-field :label="$t('device.temperatureInCabinet')" :model-value="(deviceDetal.cabinetTm == null ? $t('device.noData') : deviceDetal.cabinetTm + $t('device.degree'))" readonly />
        <van-field :label="$t('device.humidityInCabinet')" :model-value="(deviceDetal.cabinetHd == null? $t('device.noData') : deviceDetal.cabinetHd + $t('device.humidity'))" readonly />
        <van-field :label="$t('device.outsideTm')" :model-value="(deviceDetal.outsideTm == null ? $t('device.noData') : deviceDetal.outsideTm + $t('device.degree'))" readonly />
        <van-field :label="$t('device.outsidehd')" :model-value="(deviceDetal.outsideHd == null? $t('device.noData') : deviceDetal.outsideHd + $t('device.humidity'))" readonly />
      </div>
      <div class="paramsList" v-for="(item, key) in paramsList" :key="key">
        <van-field :model-value="item.val" @update:model-value="onUpdateParameters(item, key, $event)" v-if="item.name != 'M502' && item.name != 'M506'" name="phone" type="tel"
          :label="paramName[key]">
          <template #button>
            <van-button size="small" type="primary" class="updataButton" @click="updateParams(item, key)">{{
              $t('device.submitUpdates') }}</van-button>
          </template>
        </van-field>
        <div class="flex-row" v-else>
          <span class="txt3 o-pl-15 o-mtb-18" v-if="item.name != 'M502'">{{ paramName[key] }}
          </span>
          <van-switch v-if="item.name != 'M502'" class="o-mt-8" :model-value="checked[key]" @update:model-value="onUpdateValue(item, key)">
          </van-switch>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { useRoute } from "vue-router";
import { getDeviceDetal, getParameters, updateParameters } 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 deviceId = route.query.deviceId;
    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([]);

    // 初始化页面获取列表
    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 getDeviceDetalFun = async () => {
      const { data } = await getDeviceDetal({ id: deviceId });
      if (data.code === "00000") {
        deviceDetal.value = data.data;
        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);
          paramName.value.push(t("paramNames." + 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);
        })
        // console.log("longs", howLong.value)

      } else {
        showToast(t('device.noParameterData'));
      }
    };

    const onUpdateParameters = (item, key, e) => {
      // console.log(e);
      // console.log(howLong.value[key]);
      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'));
        } else {
          showFailToast(data.message);
        }
      }).catch(() => {
        // on cancel
      });
    };
    return {
      deviceDetal,
      paramsTitle,
      paramsList,
      // getParamName,
      updateParams,
      paramName,
      checked,
      onUpdateValue,
      type,
      onUpdateParameters,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../../common/style/common";

.paramsValue {
  margin: 0 40px;
}
</style>