<template>
  <!-- 设备信息修改 -->
  <div class="deviceSetPage flex-col">
    <s-header :name="$t('device.deviceInformation')" :noback="false"></s-header>
    <van-form @submit="updateDeviceFun">
      <div class="bd1 flex-col">
        <div class="bd3 flex-col">
          <div class="mod1 flex-col">
            <span class="word2">{{ $t("device.essentialInformation") }}</span>
            <img class="pic1" referrerpolicy="no-referrer"
              src="../../assets/line.png" />
          </div>
          <div class="mod2 flex-col"></div>
        </div>
        <van-field readonly v-model="deviceDetal.clientId" :label="`${$t('device.equipmentCode')}`" placeholder="" />
        <div class="cust_vantBorder">
          <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'),
              },
            ]" />
          <van-field clearable v-model="deviceDetal.selfName" :label="`${$t('device.equipmentRemarksLabel')}`"
            :placeholder="$t('device.equipmentRemarksPlaceholder')" />
          <div></div>
        </div>
        <van-field readonly v-model="deviceDetal.adminUserName" :label="`${$t('device.affiliatedMerchant')}`" />
        <!-- 地区 -->
        <!-- <div v-if="areaShow" class="bd7 l-flex-between">
          <div class="l-flex-RC">
            <div class="cust_vantBorder">
              <div class="filedInpPad">
                <van-field colon @click-input="fieldValueInpClk" readonly clearable v-model="fieldValue"
                  :label="`${$t('device.affiliatedArea')}`" :placeholder="$t('user.regionPlace')">
                  <template #right-icon>
                    <div class="l-flex-RC">
                      <van-icon v-if="fieldValue" @click="
                        fieldValue = '';
                      deviceDetal.areaId = '';
                      " class="o-mr-6" name="clear" />
                      <van-icon @click="fieldValueInpClk" name="arrow-down" />
                    </div>
                  </template>
                  <template #extra>
                    <van-icon @click="areaShow = !areaShow" size="20" name="edit" />
                  </template>
                </van-field>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="bd7 l-flex-between">
          <van-field colon readonly v-model="fieldValue" :label="`${$t('device.affiliatedArea')}`" placeholder="">
            <template #extra>
              <van-icon @click="areaShow = !areaShow" size="20" name="edit" />
            </template>
          </van-field>
        </div> -->
        <van-field readonly v-model="equimentType" :label="`${$t('device.machineType')}`" placeholder="" />
        <!-- mg280才有到期时间 -->
        <template v-if="deviceDetal?.equimentType?.indexOf('mg280') !== -1">
          <van-field readonly v-model="deviceDetal.lastUseDate" :label="`${$t('device.expirationTime')}`"
            placeholder="" />
        </template>
        <div class="bd9 l-f">
          <van-field readonly :label="`${$t('device.equipmentLabel')}`" placeholder="">
            <template #input>
              <div class="box2 l-flex-RC l-flex-w" v-if="tagsList.arr.length > 0">
                <div class="word8 o-mr-6 o-p-6 c-radius-2 o-mb-10" v-for="(item, index) in tagsList.arr" :key="index">
                  {{ item.name }}
                </div>
              </div>
            </template>
            <template #extra>
              <div @click="toTagSet" class="ImageText1 flex-col">
                <div class="box3 flex-row justify-between">
                  <div class="bd10 flex-col"></div>
                  <div class="TextGroup1 flex-col">
                    <span class="word9">{{ $t("device.edit") }}</span>
                  </div>
                </div>
              </div>
            </template>
          </van-field>
        </div>
        <div class="custom-line"></div>
        <div v-if="isAdmind" class="bd9 l-f">
          <van-field readonly :label="`${$t('device.adRule')}`" placeholder="">
            <template #input>
              <div class="box2 l-flex-RC l-flex-w" v-if="adRuleList.length > 0">
                <div class="word8 o-mr-6 o-p-6 c-radius-2 o-mb-5" v-for="(item, index) in adRuleList" :key="index">
                  {{ item.name }}
                </div>
              </div>
            </template>
            <template #extra>
              <div @click="toEditAdRule" class="ImageText1 flex-col">
                <div class="box3 flex-row justify-between">
                  <div class="bd10 flex-col"></div>
                  <div class="TextGroup1 flex-col">
                    <span class="word9">{{ $t("device.edit") }}</span>
                  </div>
                </div>
              </div>
            </template>
          </van-field>
          <div class="custom-line"></div>
        </div>
        <!-- 优惠券 -->
        <!-- <van-field readonly :label="`${$t('device.coupon')}`" placeholder=""
          v-if="user.type < 2 && user.ifForeign === '0'">
          <template #input>
            <div class="l-flex-RC">
              <span>{{ couponStatusNameComp }}</span>
              <van-switch class="o-ml-5" @change="couponStatusChg" v-model="deviceDetal.couponStatus" size="23px"
                active-value="1" inactive-value="0" />
            </div>
          </template>
        </van-field> -->
        <div class="cust_vantBorder">
          <van-field required clearable v-model="deviceDetal.operationalName" name="operationalName"
            :label="`${$t('device.nameOfOperatorLabel')}`" :placeholder="$t('device.nameOfOperatorPlaceholder')" :rules="[
              {
                required: true,
                message: $t('device.nameOfOperatorPlaceholder'),
              },
            ]" />
          <van-field required clearable v-model="deviceDetal.operationalPhone" name="operationalPhone"
            :label="`${$t('device.operatorTelephoneLabel')}`" :placeholder="$t('device.operatorTelephonePlaceholder')"
            :rules="[
              {
                required: true,
                message: $t('device.operatorTelephonePlaceholder'),
              },
            ]" />

          <!-- <van-field clearable v-model="deviceDetal.timeRuleId" :label="`${$t('device.advertisingRulesLabel')}:`"
            :placeholder="$t('device.advertisingRulesPlaceholder')" /> -->
        </div>
        <div class="custom-line"></div>
        <div class="cust_vantBorder">
          <van-field clearable label-width="32%" v-model="deviceDetal.messageReceiver1"
            :label="`${$t('device.messageReceiver1')}`" :placeholder="$t('device.equipmentmessageReceiverPlaceholder')" />
          <van-field clearable label-width="32%" v-model="deviceDetal.messageReceiver2"
            :label="`${$t('device.messageReceiver2')}`" :placeholder="$t('device.equipmentmessageReceiverPlaceholder')" />
          <van-field clearable label-width="32%" v-model="deviceDetal.messageReceiver3"
            :label="`${$t('device.messageReceiver3')}`" :placeholder="$t('device.equipmentmessageReceiverPlaceholder')" />
        </div>
        <div class="custom-line"></div>
        <!-- <div class="cust_vantBorder">
        </div>
        <div class="cust_vantBorder">
        </div> -->
        <!-- 支付方式 -->
        <!-- <van-field v-if="user.ifForeign == '0'" colon readonly label-width="18%" :label="`${$t('device.paymentMethod')}`"
          placeholder="">
          <template #input>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="deviceDetal.payType" direction="horizontal">
                <van-radio name="0" icon-size="18px">{{
                  $t("device.onlinePayment")
                }}</van-radio>
                <van-radio name="1" icon-size="18px">{{
                  $t("device.offlinePayment")
                }}</van-radio>
                <van-radio name="2" icon-size="18px">{{
                  $t("device.onlineAndOfflinePayment")
                }}</van-radio>
              </van-radio-group>
            </div>
          </template>
        </van-field> -->
        <!-- 新支付方式，暂时没用屏蔽掉，后续再添加 -->
        <!-- <van-field v-model="paymentValue" is-link readonly :label="`${$t('device.paymentMethod')}`" placeholder="选择支付方式"
          @click="showPayment = true" />
        <van-popup v-model:show="showPayment" round position="bottom">
          <van-picker :columns="paymentColumns" @cancel="showPayment = false" @confirm="onConfirm" />
        </van-popup> -->
        <!-- 通信通道 -->
        <template v-if="isAdmind">
          <van-field readonly :label="`${$t('device.communiChannel')}`" placeholder="">
            <template #input>
              <div class="van-cell__value van-field__value radioBox">
                <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>
              </div>
            </template>
          </van-field>
        </template>
        <!-- 花型种类 -->
        <template v-if="isAdmind && machineType === '0'">
          <van-field readonly :label="`${$t('device.flowerType')}`" placeholder="">
            <template #input>
              <div class="van-cell__value van-field__value radioBox">
                <van-radio-group v-model="deviceDetal.flowers" direction="horizontal">
                  <van-radio name="18" icon-size="16px">18</van-radio>
                  <van-radio name="22" icon-size="16px">22</van-radio>
                  <van-radio name="26" icon-size="16px">26</van-radio>
                  <van-radio name="30" icon-size="16px">30</van-radio>
                  <van-radio name="42" icon-size="16px">42</van-radio>
                  <van-radio name="60" icon-size="16px">60</van-radio>
                </van-radio-group>
              </div>
            </template>
          </van-field>
        </template>
        <!-- 版本号 -->
        <van-field readonly v-model="deviceDetal.apkVersion" :label="`${$t('device.versionNo')}`" placeholder="" />
        <!-- url -->
        <div v-if="isAdmind">
          <van-field center clearable class="input1" v-model="deviceDetal.url" :label="$t('device.url')"
            :placeholder="$t('device.urlPlace')">
            <template #button>
              <van-button class="updateBtn" @click="updateUrlClk" type="primary">&nbsp;&nbsp;{{ $t("device.update")
              }}&nbsp;&nbsp;</van-button>
            </template>
          </van-field>
        </div>
        <div class="l-flex-center o-mtb-30">
          <van-button round type="primary" class="info7" native-type="submit">{{
            $t("device.submitAndPushDeviceUpdates") }}</van-button>
        </div>
      </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>
  </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, onBeforeRouteLeave } from "vue-router";
import {
  getDeviceDetal,
  updateDevice,
  Api_getTApkInfo_updateApk,
  Api_getDiscCodeStatus,
} from "@/service/device/index";
import { showFailToast, showSuccessToast, showToast } from "vant";
import { useI18n } from "vue-i18n";
import dateUtil from "@/utils/dateUtil";
import { styleUrl } from "../../common/js/utils";

export default {
  name: "deviceSet",
  components: { sHeader, kCascader, kDialog },
  // // 路由守卫
  // beforeRouteEnter(to, from, next) {
  //   console.log("to", to);
  //   console.log("from", from);
  //   // 不能获取组件实例
  //   // 因为当守卫执行前，组件实例还没被创建
  //   if (from.name === "editTag") {
  //     let tagList = sessionStorage.getItem("tagList") || "[]";
  //     this.tagsList.arr = JSON.parse(tagList);
  //     sessionStorage.removeItem("tagList");
  //   }
  //   next();
  // },
  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: "",
      operationalName: "",
      operationalPhone: "",
      timeRuleId: "",
      payType: "",
      channel: "",
      flowers: "18",
      messageReceiver1: "",
      messageReceiver2: "",
      messageReceiver3: "",
    });
    const equimentType = ref('');
    let tagsList = reactive({
      arr: [],
    });
    onBeforeRouteLeave((to, from, next) => {
      if (isUpdate.value) {
        console.log("to.meta.keepAlive", to.meta.keepAlive);
        to.meta.keepAlive = false;
      }
      next();
    });
    // 过滤时间
    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;
      console.log(deviceDetal.value.payType);
      showPayment.value = false;
    };
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('deviceSet');
      // 从标签设置回来
      // let tagList = sessionStorage.getItem("tagList") || "[]";
      // tagsList.arr = JSON.parse(tagList);
      // sessionStorage.removeItem("tagList");
      getDeviceDetalFun();
      getLabelDetail();
      // 如果user.type<2那么则是公司人员
      if (user.type < 2) {
        isAdmind.value = true;
      }
    });
    // 获取标签
    const getLabelDetail = () => {
      Api_getGetEquipmentToLabel({ equipmentId: route.query.deviceId }).then(
        (res) => {
          // console.log("res", 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);
          }
        }
        if (data.data.machineType === '1') {
          machineType.value = '1';
        }
        if (data.data.equimentType === 'MG320') {
          equimentType.value = 'SC320';
        } else if (data.data.equimentType === 'MG330') {
          equimentType.value = 'SC330';
        }
      } 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: 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);
      const { data } = await updateDevice(params);
      if (data.code === "00000") {
        isUpdate.value = true;
        showSuccessToast(t("device.modificationSucceeded"));
        router.push({ path: "/device" });
      } else {
        showFailToast(data.message);
      }
    };

    // 点击去到编辑标签页
    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 confirmClk = () => {
      Api_getTApkInfo_updateApk({
        id: deviceDetal.value.id,
        url: deviceDetal.value.url,
      }).then((res) => {
        showToast(res.data.message);
        setTimeout(() => {
          getDeviceDetalFun();
        }, 1000);
      });
    };
    // 点击优惠券开关
    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) },
      });
    };
    return {
      deviceDetal,
      updateDeviceFun,
      filterDate,
      toTagSet,
      tagsList,
      areaShow,
      fieldValue,
      kCascaderRef,
      fieldValueInpClk,
      areaPopFinish,
      getAreaName,
      isAdmind,
      updateUrlClk,
      confirmClk,
      kDialogRef,
      couponStatusChg,
      couponStatusNameComp,
      toEditAdRule,
      adRuleList,
      machineType,
      user,
      paymentValue,
      paymentColumns,
      onConfirm,
      showPayment,
      equimentType,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common";
@import "../../styles/deviceSet/index.less";

.custom-line {
  height: 1px;
  background-color: #ebedf0;
  /* 设置线条颜色 */
  // margin-bottom: 10px; /* 根据需要调整线条与上方内容的间距 */
  margin: 0 15px;
}
</style>
