<template>
  <div class="device-settings">
    <s-header :name="$t('device.deviceInformation')" :noback="false" />

    <van-form @submit="updateDeviceFun" class="device-settings-form">
      <!-- 基础信息卡片 -->
      <div class="settings-card">
        <div class="card-header">
          <span class="header-icon"></span>
          <h3 class="card-title">{{ $t("device.essentialInformation") }}</h3>
        </div>

        <van-field
          readonly
          v-model="deviceDetal.clientId"
          :label="$t('device.equipmentCode')"
          class="form-item"
        />

        <div class="form-group">
          <van-field
            required
            clearable
            v-model="deviceDetal.name"
            name="name"
            :label="$t('device.equipmentNameLabel')"
            :placeholder="$t('device.equipmentNamePlaceholder')"
            :rules="[
              {
                required: true,
                message: $t('device.equipmentNamePlaceholder'),
              },
            ]"
            class="form-item"
          />
          <van-field
            clearable
            v-model="deviceDetal.selfName"
            :label="$t('device.equipmentRemarksLabel')"
            :placeholder="$t('device.equipmentRemarksPlaceholder')"
            class="form-item"
          />
        </div>
      </div>

      <!-- 设备状态卡片 -->
      <div class="settings-card">
        <van-field
          readonly
          v-model="deviceDetal.adminUserName"
          :label="$t('device.affiliatedMerchant')"
          class="form-item"
        />
        <van-field
          readonly
          v-model="deviceDetal.equimentType"
          :label="$t('device.machineType')"
          class="form-item"
        />
        <!-- 版本号 -->
        <van-field
          readonly
          v-model="deviceDetal.apkVersion"
          :label="`${$t('device.versionNo')}`"
          class="form-item"
        />
        <van-field
          readonly
          :label="$t('device.equipmentLabel')"
          class="tag-field"
        >
          <template #input>
            <div class="tag-container" v-if="tagsList.arr.length > 0">
              <van-tag
                v-for="(item, index) in tagsList.arr"
                :key="index"
                class="tag-item"
              >
                {{ item.name }}
              </van-tag>
            </div>
          </template>
          <template #extra>
            <van-button icon="edit" class="edit-btn" @click="toTagSet" />
          </template>
        </van-field>
      </div>

      <!-- 标签管理卡片 -->
      <div class="settings-card">
        <van-field
          required
          clearable
          class="form-item"
          v-model="deviceDetal.contactName"
          name="contactName"
          :label="`${$t('device.nameOfOperatorLabel')}`"
          :placeholder="$t('device.nameOfOperatorPlaceholder')"
          :rules="[
            {
              required: true,
              message: $t('device.nameOfOperatorPlaceholder'),
            },
          ]"
        />
        <van-field
          required
          clearable
          class="form-item"
          v-model="deviceDetal.contactPhone"
          name="contactPhone"
          :label="`${$t('device.operatorTelephoneLabel')}`"
          :placeholder="$t('device.operatorTelephonePlaceholder')"
          :rules="[
            {
              required: true,
              message: $t('device.operatorTelephonePlaceholder'),
            },
          ]"
        />
        <van-field
          clearable
          class="form-item"
          v-model="deviceDetal.messageReceiver1"
          :label="`${$t('device.messageReceiver1')}`"
          :placeholder="$t('device.equipmentmessageReceiverPlaceholder')"
        />
        <van-field
          clearable
          class="form-item"
          v-model="deviceDetal.messageReceiver2"
          :label="`${$t('device.messageReceiver2')}`"
          :placeholder="$t('device.equipmentmessageReceiverPlaceholder')"
        />
        <van-field
          clearable
          class="form-item"
          v-model="deviceDetal.messageReceiver3"
          :label="`${$t('device.messageReceiver3')}`"
          :placeholder="$t('device.equipmentmessageReceiverPlaceholder')"
        />
      </div>

      <!-- 操作卡片 -->
      <div class="settings-card" v-if="isAdmind">
        <van-field readonly :label="$t('device.adRule')" class="tag-field">
          <template #input>
            <div class="tag-container" v-if="adRuleList.length > 0">
              <van-tag
                v-for="(item, index) in adRuleList"
                :key="index"
                class="tag-item"
              >
                {{ item.name }}
              </van-tag>
            </div>
          </template>
          <template #extra>
            <van-button icon="edit" class="edit-btn" @click="toEditAdRule" />
          </template>
        </van-field>

        <van-field
          v-if="machineType === '0' || machineType === '1'"
          v-model="deviceDetal.flowers"
          readonly
          :label="machineType === '1' ? '口味种类' : $t('device.flowerType')"
          :placeholder="machineType === '1' ? '选择口味种类' : '选择花型种类'"
          @click="clickFlowerPicker"
          class="form-item"
        >
          <!-- <template #button>
           <van-button size="small" type="primary" @click="pushFlower">{{
             $t("advertManage.push")
           }}</van-button>
         </template> -->
        </van-field>

        <van-field
          readonly
          :label="$t('device.communiChannel')"
          class="form-item"
        >
          <template #input>
            <van-radio-group
              v-model="deviceDetal.channel"
              direction="horizontal"
            >
              <van-radio name="1" icon-size="16px">{{
                $t("device.tweets")
              }}</van-radio>
              <van-radio name="2" icon-size="16px">{{
                $t("device.mq")
              }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- <van-field
          v-model="deviceDetal.url"
          center
          autosize
          type="textarea"
          clearable
          class="form-item"
          :label="$t('device.url')"
          :placeholder="$t('device.urlPlace')"
        >
          <template #button>
            <van-button size="small" type="primary" @click="updateUrlClk">{{
              $t("device.update")
            }}</van-button>
          </template>
        </van-field> -->

        <van-field
          v-model="mqttUrl"
          center
          autosize
          type="textarea"
          clearable
          class="form-item"
          label="URL"
          :placeholder="$t('device.urlPlace')"
        >
          <template #button>
            <van-button size="small" type="primary" @click="mqttUrlClk">{{
              $t("device.update")
            }}</van-button>
          </template>
        </van-field>
      </div>

      <!-- 操作按钮 -->
      <div class="action-container">
        <van-button
          round
          type="primary"
          native-type="submit"
          class="submit-btn"
        >
          {{ $t("device.submitAndPushDeviceUpdates") }}
        </van-button>
      </div>
    </van-form>
    <!-- 地区弹窗 -->
    <kCascader
      @getareaname="getAreaName"
      :selectId="deviceDetal.areaId"
      @areapopfinish="areaPopFinish"
      ref="kCascaderRef"
    >
    </kCascader>
    <!-- 更新弹窗 -->
    <kDialog
      :dialogTitle="$t('user.logOutTips')"
      :cancelBtnTxt="$t('user.cancelLog')"
      :confirmBtnTxt="$t('user.confirmLog')"
      ref="kDialogRef"
      :dialogContent="$t('device.sureUpdate')"
      @confirmclk="confirmClk"
    >
    </kDialog>
    <!-- 花型种类 -->
    <van-popup v-model:show="showFlowerPicker" round position="bottom">
      <van-picker
        v-model="selectedFlower"
        :columns="flowerColumns"
        @cancel="showFlowerPicker = false"
        @confirm="pushFlower"
      />
    </van-popup>
  </div>
</template>
<script>
// 导入接口
import { Api_getAdRuleDetail } from "@/service/advertManage";
// 引入弹窗
import kDialog from "@/components/commom/kDialog/index.vue";
// 导入公用方法
import { setLocal, getLoginUser } from "@/common/js/utils";
// 导入vuex
import { useStore } from "vuex";
// 导入接口
import { Api_getGetEquipmentToLabel } from "@/service/labelMan";
// 导入地区弹窗
import kCascader from "@/components/commom/kCascader/index.vue";
import { computed, onMounted, reactive, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { useRoute, useRouter } from "vue-router";
import {
  getDeviceDetal,
  updateDevice,
  Api_getTApkInfo_updateApk,
  Api_getDiscCodeStatus,
  getGoodsNumber,
  pushAppUpdate,
  pushGoods,
} from "@/service/device/index";
import {
  showFailToast,
  showSuccessToast,
  showToast,
  closeToast,
  showConfirmDialog,
} from "vant";
import { useI18n } from "vue-i18n";
import dateUtil from "@/utils/dateUtil";

export default {
  name: "deviceSet",
  components: { sHeader, kCascader, kDialog },
  setup() {
    // 广告规则列表
    const adRuleList = ref([]);
    // 获取用户信息
    const user = getLoginUser();
    // 导入vuex
    const store = useStore();
    const { t } = useI18n();
    const route = useRoute();
    const router = useRouter();
    const isUpdate = ref(false);
    const deviceDetal = ref({
      name: "",
      selfName: "",
      contactName: "",
      contactPhone: "",
      operationalName: "",
      operationalPhone: "",
      timeRuleId: "",
      payType: "",
      channel: "",
      flowers: "18",
      messageReceiver1: "",
      messageReceiver2: "",
      messageReceiver3: "",
    });
    let tagsList = reactive({
      arr: [],
    });
    // 过滤时间
    const filterDate = (date) => {
      if (date) {
        return dateUtil.formateDate(new Date(date), dateUtil.DATE_yyyy_MM_dd());
      }
      return "";
    };
    // 是否管理员
    const isAdmind = ref(false);
    // 设备类型
    const machineType = ref("0");

    const paymentColumns = [
      {
        text: t("device.onlinePayment"),
        value: 0,
      },
      {
        text: t("device.offlinePayment"),
        value: 1,
      },
      {
        text: t("device.onlineAndOfflinePayment"),
        value: 2,
      },
    ];
    const paymentValue = ref("");
    const showPayment = ref(false);
    const onConfirm = ({ selectedOptions }) => {
      paymentValue.value = selectedOptions[0].text;
      deviceDetal.value.payType = selectedOptions[0].value;
      showPayment.value = false;
    };
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      // 从标签设置回来
      getDeviceDetalFun();
      getLabelDetail();
      // 如果user.type<2那么则是公司人员
      if (user.type < 2) {
        isAdmind.value = true;
      }
    });
    // 获取标签
    const getLabelDetail = () => {
      Api_getGetEquipmentToLabel({ equipmentId: route.query.deviceId }).then(
        (res) => {
          if (res.data.code === "00000") {
            tagsList.arr = res.data.data;
            // 储存数据到vuex
            store.commit("MUTA_LABELLIST", tagsList.arr);
            setLocal("deviceSet-tagsList", JSON.stringify(tagsList.arr));
          }
        }
      );
    };

    // 获取设备列表数据
    const getDeviceDetalFun = async () => {
      const { data } = await getDeviceDetal({ id: route.query.deviceId });
      if (data.code === "00000") {
        if (data.data.lastUseDate) {
          data.data.lastUseDate = filterDate(data.data.lastUseDate);
        }
        // channel如果为null，那么默认是个推
        if (!data.data.channel) {
          data.data.channel = "1";
        }
        // couponStatus如果是null，默认是关闭
        if (data.data.couponStatus != 1) {
          data.data.couponStatus = "0";
        }
        deviceDetal.value = data.data;
        // 查询地址回显
        kCascaderRef.value.init(deviceDetal.value.areaId);
        // 获取广告规则详情
        if (isAdmind.value) {
          if (data.data.timeRuleId) {
            getDetail(data.data.timeRuleId);
          }
        }
        machineType.value = data.data.machineType;
        if (machineType.value == "0" || machineType.value == "1") {
          selectedFlower.value = [deviceDetal.value.flowers];
          getFlowerNumber(machineType.value);
        }
      } else {
        showFailToast(data.message);
      }
    };
    // 获取广告规则详情
    const getDetail = (id) => {
      Api_getAdRuleDetail({ id }).then((res) => {
        const resData = res.data.data;
        // console.log("resData", resData);
        adRuleList.value = [{ name: resData.name, id: resData.id }];
      });
    };
    // 修改设备详情
    const updateDeviceFun = async () => {
      let params = Object.assign({}, deviceDetal.value);
      params = [params].map((item) => {
        return {
          id: item.id,
          name: item.name,
          selfName: item.selfName,
          areaId: item.areaId,
          contactName: item.contactName,
          contactPhone: item.contactPhone,
          flowers: user.type <= 1 ? item.flowers : "",
          operationalName: item.operationalName,
          operationalPhone: item.operationalPhone,
          timeRuleId: item.timeRuleId,
          channel: item.channel,
          messageReceiver1: item.messageReceiver1,
          messageReceiver2: item.messageReceiver2,
          messageReceiver3: item.messageReceiver3,
          payType: item.payType,
        };
      })[0];
      // console.log(params);
      if (params.name.length > 25) {
        showToast(t("device.nameLength"));
        return;
      }
      const { data } = await updateDevice(params);
      if (data.code === "00000") {
        isUpdate.value = true;
        showSuccessToast(t("device.modificationSucceeded"));
        setTimeout(() => {
          router.push({ path: "/device" });
        }, 1500);
      } else if (data.code === "A0001") {
        // 设备名称重复
        showToast(t("device.existsFailed"));
      } else {
        showFailToast(t("device.editFailed"));
      }
    };

    // 选中的花型种类
    const selectedFlower = ref([]);
    // 花型种类数据
    const flowerColumns = [];
    // 显示弹窗
    const showFlowerPicker = ref(false);
    // 获取花型种类下拉列表
    const getFlowerNumber = async (machineType) => {
      const { data } = await getGoodsNumber({ machineType: machineType });
      if (data.code === "00000") {
        data.data.forEach((item) => {
          flowerColumns.push({ text: item, value: item + "" });
        });
      }
    };
    //确认选择
    const onFlowerConfirm = ({ selectedOptions }) => {
      showFlowerPicker.value = false;
      deviceDetal.value.flowers = selectedOptions[0].text;
      showToast({
        message: "提示：\n修改花型后需要重新设置价格",
        duration: 3000,
        forbidClick: true,
      });
    };

    // 点击去到编辑标签页
    const toTagSet = () => {
      router.push({
        path: "/editTag",
        query: { deviceId: route.query.deviceId },
      });
    };
    // 地区的显示
    const areaShow = ref(false);
    // 地区弹窗
    const fieldValue = ref("");
    const kCascaderRef = ref(null);
    // 点击地区输入框
    const fieldValueInpClk = () => {
      kCascaderRef.value.openPop();
    };
    // 选择地区完成
    const areaPopFinish = async (e) => {
      // console.log("e", e);
      fieldValue.value = e.selectName;
      deviceDetal.value.areaId = e.selectId;
    };
    // 获取回显的值
    const getAreaName = (e) => {
      fieldValue.value = e;
    };
    // 退出登录弹窗
    const kDialogRef = ref(null);
    // 点击更新url
    const updateUrlClk = () => {
      if (!deviceDetal.value.url) {
        showToast(t("device.urlPlace"));
        return;
      }
      kDialogRef.value.openDialog();
    };
    const mqttUrl = ref("");
    // 点击MQTT的推送app
    const mqttUrlClk = () => {
      showConfirmDialog({
        title: "提醒",
        message: "是否推送app更新？",
      }).then(async () => {
        const { data } = await pushAppUpdate({
          id: deviceDetal.value.id,
          url: mqttUrl.value,
        });
        if (data.code === "00000") {
          showSuccessToast("推送成功");
          setTimeout(() => {
            router.go(-1);
          }, 1500);
        } else {
          showFailToast(data.message);
        }
      });
    };
    // 点击更新弹窗的确定
    const confirmClk = () => {
      Api_getTApkInfo_updateApk({
        id: deviceDetal.value.id,
        url: deviceDetal.value.url,
      }).then((res) => {
        showToast(res.data.message);
        setTimeout(() => {
          getDeviceDetalFun();
        }, 1000);
      });
    };
    // 推送花型
    const pushFlower = ({ selectedOptions }) => {
      deviceDetal.value.flowers = selectedOptions[0].text;
      showConfirmDialog({
        title: "提醒",
        message: "确认推送？",
      }).then(async () => {
        const { data } = await pushGoods({
          id: deviceDetal.value.id,
          flowers: deviceDetal.value.flowers,
        });
        if (data.code === "00000") {
          // showSuccessToast("推送成功");
          showFlowerPicker.value = false;
          showToast({
            message: "推送成功,\n修改花型后需要重新设置价格",
            duration: 3000,
            forbidClick: true,
          });
          setTimeout(() => {
            router.go(-1);
          }, 3500);
        }
      });
    };
    // 点击优惠券开关
    const couponStatusChg = (couponStatus) => {
      Api_getDiscCodeStatus({
        equipmentId: deviceDetal.value.id,
        couponStatus,
      }).then((res) => {
        showToast(res.data.message);
        setTimeout(() => {
          getDeviceDetalFun();
        }, 1500);
      });
    };
    const couponStatusNameComp = computed(() => {
      if (deviceDetal.value.couponStatus != 1) {
        return t("device.close");
      } else {
        return t("device.open");
      }
    });
    // 点击广告规则的编辑
    const toEditAdRule = () => {
      router.push({
        path: "/editAdRule",
        query: {
          deviceId: route.query.deviceId,
          adRuleList: JSON.stringify(adRuleList.value),
        },
      });
    };
    const clickFlowerPicker = () => {
      const toast = showToast({
        duration: 0,
        forbidClick: true,
        message:
          "提示：\n请确认PLC版本支持修改的花型，避免出现程序错乱，导致客诉！！！倒计时 3 S",
      });

      let second = 4;
      const timer = setInterval(() => {
        second--;
        if (second) {
          toast.message = `提示：\n请确认PLC版本支持修改的花型，避免出现程序错乱，导致客诉！！！倒计时 ${second} S`;
        } else {
          clearInterval(timer);
          closeToast();
          showFlowerPicker.value = true;
        }
      }, 1000);
    };
    return {
      deviceDetal,
      updateDeviceFun,
      filterDate,
      toTagSet,
      tagsList,
      areaShow,
      fieldValue,
      kCascaderRef,
      fieldValueInpClk,
      areaPopFinish,
      getAreaName,
      isAdmind,
      updateUrlClk,
      mqttUrl,
      mqttUrlClk,
      pushFlower,
      confirmClk,
      kDialogRef,
      couponStatusChg,
      couponStatusNameComp,
      toEditAdRule,
      adRuleList,
      machineType,
      user,
      paymentValue,
      paymentColumns,
      onConfirm,
      showPayment,
      flowerColumns,
      showFlowerPicker,
      selectedFlower,
      onFlowerConfirm,
      clickFlowerPicker,
    };
  },
};
</script>
<style lang="less" scoped>
@primary-color: #4d6add;
@card-bg: #ffffff;
@text-primary: #2d3436;
@border-color: #e4e7ec;

.device-settings {
  // padding: 16px;
  background: #f8fafb;
  min-height: 100vh;
}

.device-settings-form {
  height: calc(100% - 50px);
  overflow: auto;
  overflow-x: hidden;
}

.settings-card {
  background: @card-bg;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin: 15px;

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid @border-color;

    .header-icon {
      width: 3px;
      height: 16px;
      background: @primary-color;
      margin-right: 8px;
      border-radius: 2px;
    }

    .card-title {
      font-size: 15px;
      color: @text-primary;
      margin: 0;
    }
  }
}

.form-item {
  padding: 15px;

  :deep(.van-field__label) {
    width: 120px;
    color: #666;
    font-size: 13px;
  }

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

.status-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.tag-field {
  padding: 12px 0;

  :deep(.van-field__label) {
    width: 120px;
    color: #666;
  }

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

  .tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .tag-item {
    background: rgba(@primary-color, 0.1);
    color: @primary-color;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  .edit-btn {
    color: @primary-color;
    border: none;

    // padding: 4px;
  }
  :deep(.van-button) {
    height: auto !important;
  }
}

.action-container {
  text-align: center;
  padding: 24px 0;

  .submit-btn {
    width: 80%;
    max-width: 400px;
    font-size: 16px;
    height: 44px;
    box-shadow: 0 4px 12px rgba(77, 194, 148, 0.2);
  }
}

@media (max-width: 480px) {
  .settings-card {
    padding: 12px;
    border-radius: 8px;
  }

  .form-item {
    padding: 8px 0;
  }

  .submit-btn {
    width: 100%;
    font-size: 14px;
  }
}
</style>
