<template>
  <view class="container">
    <!-- 建议放在外层 -->
    <!--    <u-navbar
      title="历史数据"
      @leftClick="devicemenuShow"
      :safeAreaInsetTop="true"
    >
      <view class="u-nav-slot" slot="left">
        <u-icon name="list" size="20"> </u-icon>
      </view>
    </u-navbar> -->
    <!-- 侧边栏 -->
    <view v-show="menushow" class="menupage">
      <DeviceMenu @menuClick="menuClick"></DeviceMenu>
    </view>

    <!-- 历史数据列表页 -->
    <view v-if="!menushow" class="main">
      <view class="u-page">
        <div class="flcard">
          <div class="btns" style="margin-top: 10px">
            <u-button
              type="normal"
              class="u-button"
              :text="deviceName ? deviceName : '选择设备'"
              @click="deviceShow = true"
            ></u-button>
            <u-button
              type="normal"
              class="u-button"
              :text="lable ? lable : '间隔时间'"
              @click="show = true"
            ></u-button>
          </div>
          <div class="btns" style="margin-top: 10px">
            <uni-datetime-picker
              class="u-button"
              :show="dataShow"
              mode="datetime"
              @cancel="dataShow = false"
              @confirm="selectStartTime"
              v-model="StartTime"
            ></uni-datetime-picker>
            <uni-datetime-picker
              class="u-button"
              :show="dataShow1"
              mode="datetime"
              @cancel="dataShow1 = false"
              @confirm="selectEndTime"
              v-model="EndTime"
            ></uni-datetime-picker>
            <u-button
              type="primary"
              text="查询"
              @click="checkHistory"
              class="btn"
            ></u-button>
          </div>
          <u-picker
            :show="deviceShow"
            :columns="[devices]"
            @cancel="deviceShow = false"
            @confirm="selectDevice"
            keyName="strinstallpos"
          >
          </u-picker>
          <u-picker
            :show="deviceShow1"
            :columns="devices1"
            @cancel="deviceShow1 = false"
            @confirm="selectDevice1"
            keyName="label"
          ></u-picker>
          <u-picker
            :show="show"
            :columns="timeColumns"
            @cancel="show = false"
            keyName="label"
            @confirm="selectSkipTime"
          ></u-picker>
        </div>
        <u-list
          :class="{ emptyhistory: historyData.length === 0 }"
          class="historycontainer"
        >
          <template v-if="historyData.length > 0">
            <u-list-item
              class="itemback"
              v-for="(item, index) in historyData"
              :key="index"
            >
              <u-row gutter="5" customStyle="margin-bottom: 10px">
                <u-col span="24">
                  <u--text :text="item.ginstallpos || item.devicePos"></u--text>
                </u-col>
              </u-row>
              <u-row gutter="5" customStyle="margin-bottom: 10px">
                <u-col span="3" style="margin-right: 15rpx">
                  <div v-if="item.netStatus == 0" class="error-tag1">
                    <image
                      src="/static/model/connectFalse.svg"
                      alt=""
                      class="icon-style"
                    />
                    <span style="float: right">断开</span>
                  </div>
                  <div v-else class="success-tag">
                    <image
                      src="/static/model/connectTrue.svg"
                      alt=""
                      class="icon-style"
                    />
                    <span style="float: right">连接</span>
                  </div>
                </u-col>
                <u-col span="3"> </u-col>
                <u-col span="5">
                  <div class="time-bg">
                    <span class="timetext">{{ item.time || item.ttime }}</span>
                  </div>
                </u-col>
              </u-row>
              <view style="display: flex; flex-wrap: wrap">
                <view
                  class="datacard"
                  v-for="(showitem, index) in deviceShowList"
                  :key="index"
                  v-if="
                    showitem.appShow == 1 &&
                    showitem.monitorcode != 'strinstallpos' &&
                    showitem.monitorcode != 'gdevicename' &&
                    showitem.monitorcode != 'ginstallpos' &&
                    showitem.monitorcode != 'netStatus' &&
                    showitem.monitorcode != 'warnFlag' &&
                    showitem.monitorcode != 'gcreatetime' &&
                    showitem.monitorcode != 'ttime' &&
                    showitem.monitorcode != 'time'
                  "
                >
                  <view
                    :class="TabCur"
                    style="
                      padding-top: 10rpx;
                      padding-bottom: 10rpx;
                      display: flex;
                      flex-direction: column;
                      height: 100%;
                    "
                  >
                    <view
                      v-if="showitem.monitorcode == 'doorUse'"
                      class="demo-layout bg-purple-light"
                      style="
                        margin-top: 10rpx;
                        color: #3787fe;
                        font-size: 30rpx;
                        margin-top: 20rpx;
                        margin-left: 20rpx;
                        float: left;
                      "
                    >
                      {{
                        item[showitem.monitorcode] == "2"
                          ? "行人"
                          : item[showitem.monitorcode] == "1"
                          ? "行车"
                          : "-"
                      }}
                    </view>
                    <view
                      v-else
                      class="demo-layout bg-purple-light"
                      style="
                        color: #3787fe;
                        font-size: 30rpx;
                        margin-top: 20rpx;
                        margin-left: 20rpx;
                        float: left;
                      "
                    >
                      {{
                        item[showitem.monitorcode] == null ||
                        item[showitem.monitorcode] == ""
                          ? "-"
                          : item[showitem.monitorcode]
                      }}
                    </view>
                    <view
                      class="demo-layout bg-purple-light"
                      style="
                        margin-top: 20rpx;
                        color: #677799;
                        margin-top: 20rpx;
                        margin-left: 20rpx;
                        float: left;
                      "
                    >
                      {{ showitem.des }}
                    </view>
                  </view>
                </view>
              </view>
            </u-list-item>
          </template>
          <template v-else>
            <div class="empty-message">数据为空</div>
          </template>
        </u-list>
      </view>
    </view>
  </view>
</template>

<script>
import api from "@/api/api";
import dayjs from "dayjs";
import DeviceMenu from "../../pages/device/devicemenu/devicemenu";
import uniDatetimePicker from "../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue";
export default {
  data() {
    return {
      menushow: false,
      TabCur: "gate",
      curlist: [],
      colums: [],
      deviceList: {},
      startDate: null,
      endDate: null,
      show: false,
      deviceShow: false,
      deviceShow1: false,
      dataShow: false,
      dataShow1: false,
      StartTime: "", //起始时间
      EndTime: "", //结束时间
      devices: [], //设备类型数组
      devices1: [
        [
          {
            label: "1#风机",
            value: "fan1",
          },
          {
            label: "2#风机",
            value: "fan2",
          },
        ],
      ], //子设备类型数组
      deviceName: "", //设备名称
      labelName: "", //子设备名称
      timeS: "", //间隔时间
      lable: "", //间隔时间
      timeColumns: [
        [
          {
            label: "1秒",
            value: "1",
            value1: "1s",
          },
          {
            label: "5秒",
            value: "2",
            value1: "5s",
          },
          {
            label: "10秒",
            value: "3",
            value1: "10s",
          },
          {
            label: "30秒",
            value: "4",
            value1: "30s",
          },
          {
            label: "1分钟",
            value: "5",
            value1: "1m",
          },
          {
            label: "10分钟",
            value: "6",
            value1: "10m",
          },
          {
            label: "30分钟",
            value: "7",
            value1: "30m",
          },
          {
            label: "1小时",
            value: "8",
            value1: "1h",
          },
        ],
      ],
      deviceID: "", //设备ID
      deviceType1: "", //设备类型
      skip: 8, //时间间隔
      interval: "1h", //时间间隔
      dataTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      historyData: [], //历史数据
      deviceShowList: [],
      loading: false, // 是否正在加载数据
      hasMoreData: true, // 是否还有更多数据可以加载
      pageNo: 1, // 当前页码（用于请求数据时分页）
      stationType: "plc1", // 站点类型（用于请求数据时的参数）
      strType: "", //设备小类
      sysId: "",
    };
  },
  components: {
    DeviceMenu,
    uniDatetimePicker,
  },
  props: ["showColum", "deviceType"],
  watch: {
    deviceType: {
      async handler(data) {
        if (data) {
          this.TabCur = data;
          console.log(this.TabCur, "设备");
          this.curlist = this.deviceList[this.TabCur];
          if (this.curlist == null) {
            this.curlist = [];
          }
          // 选择设备分类，重新获取数据
          await this.loadData(this.TabCur);
          this.$emit("setMenushow", {
            menushow: false,
          });
        }
      },
      immediate: true,
    },
  },
  created() {
    this.colums = this.showColum;
    const startTime = new Date().getTime() - 3600 * 1000 * 24 * 30;
    const endTime = new Date();
    this.StartTime = dayjs(startTime).format("YYYY-MM-DD HH:mm:ss");
    this.EndTime = dayjs(endTime).format("YYYY-MM-DD HH:mm:ss");
  },
  mounted() {
    // this.TabCur = deviceType;
    if (this.TabCur.startsWith("sys_")) {
      this.loadNewData(this.TabCur);
    } else {
      this.loadData(this.TabCur);
    }
  },

  computed: {},
  methods: {
    loadData(type) {
      new Promise((resolve, reject) => {
        api
          .getDeviceMonitor({
            devicetype: type,
            pagetype: "normal",
            filterParams: {},
          })
          .then((response) => {
            if (response.data.code == 200) {
              this.deviceList[type] = response.data.result.msgTxt[0].datalist;
              this.curlist = this.deviceList[type];
              this.setData(this.curlist);
            } else {
              resolve(response);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    loadNewData(type) {
      return new Promise((resolve, reject) => {
        api
          .getSysList({
            strtype: type,
            pagetype: "normal",
          })
          .then((response) => {
            if (response.data.code == 200) {
              this.sysId = response.data.result.records[0].id;
              this.loadSysData({
                devicetype: "sys",
                systemID: this.sysId,
              });
            } else {
              resolve(response);
            }
          })
          .catch((error) => {
            // console.log("catch===>response", response);
            reject(error);
          });
      });
    },
    //加载场景类数据
    loadSysData(data) {
      new Promise((resolve, reject) => {
        api
          .getDeviceMonitor(data)
          .then((response) => {
            if (response.data.code == 200) {
              this.deviceList[this.TabCur] =
                response.data.result.msgTxt[0].datalist;
              this.curlist = this.deviceList[this.TabCur];
              this.setData(this.curlist);
            } else {
              resolve(response);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //选择设备选择器  保存对应的id
    setData(data) {
      this.devices = [];
      data.forEach((element) => {
        const deviceObj = {
          // id: element.deviceID,
          ID: element.deviceID,
          strinstallpos: element.strinstallpos,
          type: element.deviceType,
          stationtype: element.stationtype,
          strtype: element.strtype,
        };
        this.devices.push(deviceObj);
      });
    },
    //选择设备  点击确定按钮  保存id
    selectDevice(e) {
      // this.deviceId = e.value[0].id;
      this.deviceID = e.value[0].ID;
      this.stationType = e.value[0].stationtype;
      this.strType = e.value[0].type;
      this.deviceType1 = e.value[0].type;
      this.deviceName = e.value[0].strinstallpos;
      this.deviceShow = false;
      let original = this.TabCur;
      let newName = original.startsWith("sys_")
        ? original.substring(4)
        : original;
      const key = newName + "_history";
      const key1 = this.deviceType1 + "_history";
      console.log(key1, "key1");
      if (this.showColum?.[key1]?.length > 0) {
        this.deviceShowList = this.showColum[key1];
      } else {
        this.deviceShowList = this.showColum[key] ?? [];
      }
    },
    selectDevice1(e) {
      this.deviceNum = e.value[0].value;
      this.labelName = e.value[0].label;
      this.deviceShow1 = false;
    },
    //选择起始时间
    selectStartTime(e) {
      const startTime = e.value;
      const formattedTime = dayjs(startTime).format("YYYY-MM-DD HH:mm:ss");
      this.StartTime = formattedTime;
      this.dataShow = false;
    },
    //选择结束时间
    selectEndTime(e) {
      const endTime = e.value;
      const formattedTime = dayjs(endTime).format("YYYY-MM-DD HH:mm:ss");
      this.EndTime = formattedTime;
      this.dataShow1 = false;
    },
    //选择间隔时间
    selectSkipTime(e) {
      this.skip = e.value[0].value;
      this.interval = e.value[0].value1;
      this.lable = e.value[0].label;
      this.show = false;
    },
    //查询历史数据 getDeviceHistory
    checkHistory() {
      this.historyData = []; // 清空历史数据
      if (this.stationType !== "redis") {
        this.getHistoryData();
      } else {
        this.getHistoryData2();
      }
    },
    // 查询历史数据
    getHistoryData() {
      const params = {
        ttime_begin: this.StartTime,
        ttime_end: this.EndTime,
        gdeviceid: this.deviceID,
        skip: this.skip,
        pageNo: this.pageNo,
        pageSize: 10,
        strtype: this.strType,
      };
      new Promise((resolve, reject) => {
        api
          .getDeviceHistory(params)
          .then((response) => {
            if (response.data.code == 200) {
              const infolist = response.data.result;
              const result = infolist.datalist.records;
              result.forEach((item) => {
                const newData = { ...item, ...item.readData };
                this.historyData.push(newData);
              });
              this.pageNo = response.data.result.datalist.current;
            } else {
              resolve(response);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    getHistoryData2() {
      const params = {
        startTime: this.StartTime,
        endTime: this.EndTime,
        deviceId: this.deviceID,
        interval: this.interval,
        isEmployee: this.TabCur.startsWith("vehicle") ? false : true,
        pageNum: 1,
        pageSize: 10,
        strtype:
          (this.TabCur.startsWith("sys_")
            ? this.TabCur.substring(4)
            : this.TabCur) + "*",
      };
      if (this.TabCur.startsWith("sys")) {
        params.sysId = this.sysId;
      }
      new Promise((resolve, reject) => {
        api
          .getDeviceHistory2(params)
          .then((response) => {
            if (response.data.code === 200) {
              const result1 = response.data.result;
              if (result1.records.length != 0) {
                this.historyData = result1.records;
              }
              // this.pageNo = response1.data.result.datalist.current;
            } else {
              resolve(response);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async loadMoreData() {
      if (this.loading || !this.hasMoreData) return;
      this.loading = true;
      try {
        // 如果新数据为空，则表示没有更多数据了
        if (this.historyData.length === 0) {
          this.hasMoreData = false;
        } else {
          // 将新数据追加到数据列表中
          this.historyData = [...this.historyData, ...newData];
          // 更新页码以便下次加载下一页数据
          this.pageNo += 1;
        }
      } catch (error) {
        // 处理请求错误
        console.error("加载数据失败:", error);
      } finally {
        // 无论请求成功还是失败，都要将加载状态设置为false
        this.loading = false;
      }
    },
    devicemenuShow(e) {
      this.menushow = !this.menushow;
    },
    menuClick(id) {
      this.TabCur = id;
      console.log(this.TabCur);
      // 显示该分类的数据
      this.curlist = this.deviceList[this.TabCur];
      if (this.curlist == null) {
        this.curlist = [];
      }
      // 选择设备分类，重新获取数据
      this.loadData(this.TabCur);
      this.menushow = false;
    },
  },
  destroyed() {
    // 停止定时器
  },
  onReachBottom() {
    // uni-app提供的页面滚动到底部钩子函数
    console.log("上拉加载更多数据");
    // this.loadMoreData();
  },
};
</script>

<style lang="scss" scoped>
.btn {
  width: 80px;
  background: linear-gradient(to right, #338afe, #07b4ff, #338afe) !important;
  border-radius: 5px;
}
.u-button {
  border-radius: 5px;
  border: 1px solid #2299fe;
  font-weight: bold;
}
.time-bg {
  background-color: #cce6fb;
  border-radius: 5px;
  height: 26px;
  line-height: 25px;
  text-align: center;
  float: right;
}
.timetext {
  text-align: center;
  color: #2591eb;
}
.emptyhistory {
  background: url("/static/empty.png") no-repeat;
  background-size: 100% 50%;
}
.empty-message {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  line-height: 80vh;
  color: #333;
}
.content {
  width: 100%;
  display: flex;
  flex-direction: column;
}
.main {
  /* margin-top: 100rpx; */
  display: flex;
  flex-direction: column;
}
.menupage {
  position: absolute;
  z-index: 2;
  top: 40rpx;
  height: calc(100% - 40rpx);
  width: 100%;
}
.btns {
  display: flex;
}
.btns > * {
  margin-right: 10px; /* 根据需要调整间距大小 */
}

/* 去除最后一个按钮的右边距 */
.btns > *:last-child {
  margin-right: 0;
}

.flcard {
  padding: 20rpx;
  background-color: #ffffff;
  margin-bottom: 5rpx;
}
.itemback {
  padding: 20rpx;
  background-color: #ffffff;
  margin-bottom: 5rpx;
}
.datacard {
  width: 47%;
  margin: 1%;
  float: left;
  height: 75px;
  background: url("/static/dataBg.png");
  background-size: 40% 100%;
  background-position: right;
  background-repeat: no-repeat;
}
.datacard .window {
  background: linear-gradient(
    to right,
    rgba(55, 135, 254, 0.08),
    rgba(4, 184, 255, 0.08),
    rgba(60, 161, 237, 0.08)
  );
}
.error-tag {
  border-radius: 10%;
  display: inline-block;
  color: #e90000;
  line-height: 50rpx;
  font-size: 14px;
  text-align: center;
  width: 120rpx;
  height: 50rpx;
  background-color: rgba(233, 0, 0, 0.2);
}
.error-tag1 {
  border-radius: 10%;
  display: inline-block;
  color: #696969;
  line-height: 50rpx;
  font-size: 14px;
  text-align: center;
  width: 120rpx;
  height: 50rpx;
  background-color: rgba(105, 105, 105, 0.2);
}
.success-tag {
  border-radius: 10%;
  color: #5acc1f;
  line-height: 50rpx;
  font-size: 14px;
  width: 120rpx;
  height: 50rpx;
  display: inline-block;
  background-color: rgba(226, 250, 214, 0.5);
}
.icon-style {
  margin: 15rpx;
  width: 14px;
  height: 14px;
}
</style>