<template>
  <view class="container">
    <cu-custom
      ref="Dustom"
      id="custom"
      bgImage="https://yostest175549.obs.cn-east-2.myhuaweicloud.com:443/202306151686796745663B52544232.png"
      :isBack="true"
    >
      <block slot="backText">返回</block>
      <block slot="content"> 设备详情 </block>
    </cu-custom>
    <My_listbox ref="List" :pullDown="false" @getlist="loadData">
      <view class="head">
        <view class="name">
          <view class="left">
            <text class="status" :style="{ backgroundColor: detail.bgColor }">{{
              detail.status
            }}</text>
            {{ detail.devicename }}
          </view>
          <view class="sliding-block" v-if="detail.issupportbluetooth == 1">
            <view
              class="but"
              :class="mode == 0 ? 'action' : ''"
              style="left: 0"
              hover-class="navigator-hover"
              @click="changeMode(0)"
              >网络</view
            >
            <view
              class="but"
              hover-class="navigator-hover"
              style="right: 0"
              :class="mode == 1 ? 'action' : ''"
              @click="changeMode(1)"
              >蓝牙</view
            >
            <view
              class="sliding"
              :style="{
                transform: `translateX(${mode == 0 ? 0 : '34px'})`,
              }"
            />
          </view>
        </view>
        <view class="row"> 设备编号：{{ detail.serialnumber || " --" }} </view>
        <view class="row">
          最近上线时间：{{ detail.lastconnecttime || " --" }}
        </view>
      </view>
      <preview-image ref="轮播图" :attinfos="detail.attinfos" />
      <view class="ceiling" :style="{ top: tovw(CustomBar) }">
        <horizontal-direction ref="hd" />
      </view>
      <view class="ceiling" :style="{ top: tovw(CustomBar + tabsTop) }">
        <tabs :tabs="tabs" @changeTab="changeTab" />
      </view>
      <control
        ref="设备控制"
        :detail="detail"
        :mode="mode"
        @onUpdate="getDetail"
      />
      <daily-record
        ref="设备日志"
        :isfeedback="detail.isfeedback"
        :w_deviceid="w_deviceid"
      />
      <preview ref="详情信息" :detail="detail" />
      <alerts ref="告警记录" :w_deviceid="w_deviceid" />
      <view style="height: 30px" />
    </My_listbox>
  </view>
</template>

<script>
import horizontalDirection from "./modules/horizontalDirection.vue";
import tabs from "./modules/tabs.vue";
import preview from "./modules/preview.vue";
import dailyRecord from "./modules/dailyRecord.vue";
import control from "./modules/control.vue";
import previewImage from "./modules/previewImage.vue";
import alerts from "./modules/alerts.vue";

let page = {};
export default {
  components: {
    horizontalDirection,
    tabs,
    preview,
    dailyRecord,
    control,
    previewImage,
    alerts,
  },
  name: "facilityD",
  data() {
    return {
      CustomBar: 0,
      tabsTop: 0,
      w_deviceid: 0,
      detail: {},
      mode: 0, //0网络 1蓝牙
      showTab: "设备控制",
      tabs: [
        {
          name: "设备控制",
        },
        {
          name: "设备日志",
        },
        {
          name: "告警记录",
        },
        {
          name: "详情信息",
        },
      ],
    };
  },
  watch: {
    mode: function () {
      this.$refs.设备控制.getControl(true);
    },
  },
  onLoad(options) {
    this.w_deviceid = options.id;
  },
  mounted() {
    this.CustomBar = -10;
    this.$refs.List.setHeight();
  },
  onShow() {
    this.getDetail(true);
    try {
      this.$Http.openNetwork = this.$refs.轮播图.openNetwork;
      this.$Http.slideshowSetData = this.$refs.轮播图.setData;
    } catch (error) {
      setTimeout(() => {
        this.$Http.openNetwork = this.$refs.轮播图.openNetwork;
        this.$Http.slideshowSetData = this.$refs.轮播图.setData;
      }, 100);
    }
  },
  methods: {
    getDetail(init = false) {
      this.$Http
        .basic({
          id: 20230615103902,
          content: {
            nocache: true,
            w_deviceid: this.w_deviceid,
          },
        })
        .then((res) => {
          console.log("设备详情", res);
          if (this.cutoff(res.msg)) return;
          if (!res.data.miniapppath) {
            res.data.miniapppath = require("../../control/pages").getPageName(
              res.data.prodnum
            );
            if (!res.data.miniapppath) {
              //未匹配到设备控制页
              this.showTab = "设备日志";
              this.tabs.shift();
            }
          }
          console.log("res.data.miniapppath", res.data.miniapppath);
          switch (res.data.status) {
            case "在线":
              res.data.bgColor = "#007aff";
              break;
            case "禁用":
              res.data.bgColor = "#F56C6C";
              break;
            default:
              res.data.bgColor = "#F9AE3D";
              break;
          }
          this.detail = res.data;
          if (init) {
            let prodnum = res.data.prodnum;
            if (res.data.miniapppath)
              prodnum = res.data.miniapppath.split("-")[1];
            this.$refs.hd
              .getList(this.w_deviceid, prodnum)
              .then((num) => (this.tabsTop = num));
            setTimeout(() => {
              this.changeTab({ name: this.showTab }, true);
            }, 100);
          }
        });
    },
    changeTab({ name }, init = false) {
      this.showTab = name;
      page.show = false;
      page = this.$refs[name];
      this.loadData(init);
    },
    loadData(init) {
      // show t =加载 f=变化
      if ((page.uninitialized && !page.show) || init) {
        console.log("首次加载", this.showTab);
        page.show = true;
        page.initialize(true);
      } else if (page.show) {
        page.initialize();
      } else {
        page.show = true;
      }
    },
    changeMode(mode) {
      const that = this;
      if (this.mode == mode) return;
      switch (mode) {
        case 0:
          uni.showModal({
            content: "是否关闭蓝牙\n并切换至网络控制",
            success: function ({ confirm }) {
              if (confirm) {
                that.mode = mode;
                try {
                  if (that.$Http.Bluetooth)
                    uni.closeBLEConnection({
                      deviceId: that.$Http.Bluetooth.device.deviceId,
                    });
                  uni.closeBluetoothAdapter();
                  delete that.$Http.Bluetooth;
                } catch (error) {}
              }
            },
          });
          break;
        case 1:
          /*    uni.openBluetoothAdapter({
            mode: "peripheral",
          }); */
          uni.openBluetoothAdapter({
            success: (result) => {
              if (result.errno == 0) {
                uni.navigateTo({
                  url:
                    "/Bluetooth/index/index?services=" +
                    JSON.stringify([
                      that.detail.prodnum,
                      that.detail.w_productid,
                    ]),
                });
                this.$Http.setBluetooth = function (Bluetooth) {
                  this.mode = mode;
                  let curPages = getCurrentPages();
                  if (
                    curPages[curPages.length - 1].__route__ ==
                    "Bluetooth/index/index"
                  )
                    uni.navigateBack();
                  this.$Http.setDetailMode = function (mode1) {
                    this.mode = mode1;
                    delete this.$Http.setDetailMode;
                    uni.closeBluetoothAdapter();
                  }.bind(this);
                  this.$Http.Bluetooth = Bluetooth;
                  delete this.$Http.setBluetooth;
                }.bind(this);
              } else {
                uni.showModal({
                  title: result.errno,
                  content: result.Msg,
                  showCancel: false,
                  confirmText: "确定",
                });
              }
            },
            fail: (fail) => {
              console.log("蓝牙初始化fail:", fail);
              if (fail.errno == "103") {
                uni.showModal({
                  title: "提示",
                  content: "未获取使用蓝牙功能授权，请授权后使用",
                  showCancel: false,
                  confirmText: "前去授权",
                  success() {
                    uni.openSetting({
                      success({ authSetting }) {
                        if (authSetting["scope.bluetooth"])
                          that.changeMode(mode);
                      },
                    });
                  },
                });
              } else {
                const codes = {
                  0: "ok",
                  "-1": "已连接 ",
                  10000: "未初始化蓝牙适配器",
                  10001: "当前蓝牙适配器不可用",
                  10002: "没有找到指定设备",
                  10003: "连接失败",
                  10004: "没有找到指定服务",
                  10005: "没有找到指定特征值",
                  10006: "当前连接已断开",
                  10007: "当前特征值不支持此操作",
                  10008: "其余所有系统上报的异常",
                  10009: "系统版本低于 4.3 不支持 BLE",
                  10010: "已连接",
                  10011: "配对设备需要配对码",
                  10012: "连接超时",
                  10013: "连接 deviceId 为空或者是格式不正确",
                };
                uni.showModal({
                  content: codes[fail.errCode] || fail.errMsg,
                  showCancel: false,
                  confirmText: "确认",
                });
              }
            },
          });
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.ceiling {
  position: sticky;
  z-index: 9;
}

.head {
  width: 355px;
  background: #ffffff;
  border-radius: 4px;
  padding: 10px 15px;
  box-sizing: border-box;
  margin: 10px auto 0;

  .name {
    display: flex;
    line-height: 20px;
    font-size: 14px;
    font-family: PingFang SC-Medium, PingFang SC;
    font-weight: bold;
    color: #333333;
    margin-bottom: 10px;
    .left {
      flex: 1;
      .status {
        display: inline-block;
        padding: 2px 6px;
        border-radius: 4px;
        color: #ffffff;
        margin-right: 5px;
        font-weight: normal;
        font-size: 14px;
      }
    }

    .sliding-block {
      position: relative;
      flex-shrink: 0;
      width: 74px;
      height: 20px;
      border-radius: 12px;
      overflow: hidden;
      box-sizing: border-box;
      background: #f5f6fa;

      .but {
        position: absolute;
        font-size: 10px;
        width: 40px;
        text-align: center;
        line-height: 21px;
        z-index: 2;
        color: #bbbbbb;
        border-radius: 12px;
        transition: color 0.3s ease;
      }

      .action {
        color: #ffffff;
        z-index: 3;
      }

      .sliding {
        position: absolute;
        width: 40px;
        height: 20px;
        background: #3874f6;
        border-radius: 12px;
        z-index: 1;
        transition: transform 0.3s ease;
      }
    }
  }

  .row {
    line-height: 17px;
    font-size: 12px;
    color: #666666;
    margin-bottom: 5px;
  }
}
</style>
