<template>
  <view class="container">
    <u-navbar title="设备日志"
              @rightClick="rightClick" titleStyle="color:#fff;fontSize:36rpx;"   bgColor="#2C6FF3"
              :autoBack="true" leftIconColor="#fff" :placeholder="true">
    </u-navbar>

    <view class="content">

      <view class="topbar flex flex-wrap justify-between">
        <view class="data_total flex align-center">
          共 {{data.total}} 条记录
        </view>
        <view class="search flex" style="margin-left: 20rpx;">
          <u-button size="mini" @click="openPicLogMenu">捞日志</u-button>
        </view>
        <view class="search flex" style="margin-left: 20rpx;">
          <u-button size="mini" @click="getList">刷新</u-button>
        </view>
        <view class="search flex" @tap="openSearchMenu" style="margin-left: 20rpx;">
          筛选<u-icon name="arrow-right" style="margin-left: 6rpx;" size="14"></u-icon>
        </view>
      </view>

      <scroll-view  class="scrollview" :scroll-with-animation="true" scroll-y lower-threshold="100"
                    @scrolltolower="scrolltolower" :style="{height:data.fullHeight}">
        <view v-if="data.dataList.length>0">
          <view class="eq-item"
                v-for="(item1,index1) in data.dataList" :key="item1.deviceId">
            <view class="eq-content">
              <view class="eq-wrap">
                <view class="eq-name flex justify-between">
                  <view class="eq-title" v-if="item1.deviceName">{{item1.deviceId}}<text style="color: #666;">({{item1.deviceId}})</text></view>
                  <view class="eq-title" v-else>{{item1.deviceId}}</view>
                  <view class="eq-status-box flex align-center">
<!--                    <view class="eq-status" :class="[item1.netState==1?'online':'']"><text></text>{{item1.netState=='1'?'在线':'离线'}}-->
<!--                    </view>-->
                  </view>
                </view>
                <view class="eqeq-type">
                  <view>
                    日志类型：
                  </view>
                  <view>
                    {{proxy.$getDictByValue(dicts.device_log_type,item1.type).label}}
                  </view>
                </view>
                <view class="eqeq-type">
                  <view>
                    日志文件：
                  </view>
                  <view class="logfile" @tap="showLog(item1.logName)">
                    {{item1.logName}}
                  </view>
                </view>
                <view class="eqeq-type">
                  <view>
                    开始时间：
                  </view>
                  <view>
                    {{item1.logBeginTime}}
                  </view>
                </view>
                <view class="eqeq-type">
                  <view>
                    结束时间：
                  </view>
                  <view>
                    {{item1.logEndTime}}
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="load-more" style="padding:24rpx;">
            <u-loadmore v-if="data.dataList.length>0" :status="data.loadmoreStatus" />
          </view>
        </view>
        <view v-else class='empty'>
          <u-empty mode="data" text="数据为空"></u-empty>
        </view>
      </scroll-view>
    </view>

    <u-popup :show="searchMenu.showPopMenu"  duration="0" :customStyle="searchMenu.style" :round="10" mode="right" :duration="300" :overlay="false"  >
      <view class="searchMenu popMenu flex" :style="searchMenu.searchMenu_body_style">
        <scroll-view scroll-y class="searchMenu_body flex-wrap justify-between">
          <view>
            <view class="label">
              设备编号
            </view>
            <view>
              <u--input
                  placeholder="请输入设备编号"
                  border="surround"
                  v-model="searchMenu.params.deviceId"
              ></u--input>
            </view>
          </view>
          <view>
            <view class="label">
              类型
            </view>
            <view class="flex flex-wrap justify-between">
              <view>
                <view class="tab-list flex flex-wrap justify-between">
                  <block v-for="(item,index) in dicts.device_log_type" :key="item.value">
                    <view :class="[searchMenu.params.type==item.value?'tab-item tab-show':'tab-item']" @click="searchMenu.params.type = item.value">
                      {{item.label}}
                    </view>
                  </block>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="searchMenu_bottom ">
          <view class="flex flex-wrap justify-between">
            <view>
              <u-button size="normal" :plain="true" text="关闭" @click="doSearch(0)"></u-button>
            </view>

            <view class="flex">
              <view>
                <u-button size="normal"  type="primary" :plain="true" text="重置" @click="resetSearchMenu"></u-button>
              </view>
              <view style="margin-left: 20rpx">
                <u-button size="normal"  type="primary"  text="查找" @click="doSearch(1)"></u-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
    <u-popup :show="picLogMenu.showPopMenu"  duration="0" :customStyle="picLogMenu.style" :round="10" mode="right" :duration="300" :overlay="false"  >
      <view class="searchMenu popMenu flex" :style="searchMenu.searchMenu_body_style">
        <scroll-view scroll-y class="searchMenu_body flex-wrap justify-between">
          <view>
            <view class="label">
              设备编号
            </view>
            <view>
              <u--input
                  placeholder="请输入设备编号"
                  border="surround"
                  v-model="picLogMenu.params.deviceId"
              ></u--input>
            </view>
          </view>
          <view>
            <view class="label">
              类型
            </view>
            <view class="flex flex-wrap justify-between">
              <view>
                <view class="tab-list flex flex-wrap justify-between">
                  <block v-for="(item,index) in dicts.device_log_type" :key="item.value">
                    <view v-show="item.label!='全部'" :class="[picLogMenu.params.logType==item.value?'tab-item tab-show':'tab-item']" @click="picLogMenu.params.logType = item.value">
                      {{item.label}}
                    </view>
                  </block>
                </view>
              </view>
            </view>
          </view>
          <view>
            <view class="label">
              开始时间
            </view>
            <view class="flex flex-wrap justify-between">
              <view class="flex">
                <u--input
                    placeholder=""
                    border="surround"
                    v-model="picLogMenu.params.startTime"
                ></u--input>
              </view>
              <view>
                <u-button @click="showTimePicker(0)">选择</u-button>
              </view>
            </view>
          </view>
          <view>
            <view class="label">
              结束时间
            </view>
            <view class="flex flex-wrap justify-between">
              <view class="flex">
                <u--input
                    placeholder=""
                    border="surround"
                    v-model="picLogMenu.params.endTime"
                ></u--input>
              </view>
              <view>
                <u-button @click="showTimePicker(1)">选择</u-button>
              </view>
            </view>
          </view>
          <!--              v-if="picLogMenu.showTimePicker"-->
          <u-datetime-picker
              ref="datetimePicker"
              :show="picLogMenu.showTimePicker"
              v-model="picLogMenu.selTime"
              mode="datetime"
              @confirm="onSelectTime"
              @cancel="onCancelSelectTime"
          ></u-datetime-picker>
        </scroll-view>
        <view class="searchMenu_bottom ">
          <view class="flex flex-wrap justify-between">
            <view>
              <u-button size="normal" :plain="true" text="关闭" @click="picLogMenu.showPopMenu=false"></u-button>
            </view>

            <view class="flex">
              <u-button size="normal"  type="primary"  text="捞日志" @click="sendCommand(1)"></u-button>
            </view>
          </view>
        </view>
      </view>
    </u-popup>

  </view>
</template>

<script setup>

import {getCurrentInstance, onMounted, reactive, ref,reject} from "vue";
import {getDictByCode} from "../../../plugins/dict";
const { proxy } = getCurrentInstance();
const instance = getCurrentInstance();
const {
  device_log_type,device_type,mqtt_cmd_templet_task
} = proxy.$useDict('device_log_type','device_type', 'mqtt_cmd_templet_task',);
const dicts = reactive({
  device_type:[],
  device_log_type:[],
  mqtt_cmd_templet_task:[],
})

const searchMenu = reactive({
  showPopMenu:false,
  selStatus:0,
  style:{
    marginTop :'174rpx'
  },
  searchMenu_body_style:{
    height:'600rpx'
  },
  params:{
    deviceId:undefined,
    type:undefined,
    beginLogBeginTime:undefined,
    endLogBeginTime:undefined,
  }
});

function openSearchMenu(){
  searchMenu.showPopMenu = true;
  getTreeData();
}
function resetSearchMenu(){
  searchMenu.params.deviceId = undefined;
  searchMenu.params.type = undefined;
}
function selectCode(){
  proxy.$refs.treePicker._show();
}
function doSearch(o){
  if(o==0)resetSearchMenu();

  setTimeout(function(){
    searchMenu.showPopMenu = false;
    data.curPage = 1;
    getList()
  }, 500);
}

function formatDate(time) {
  return  time.getFullYear()+"-"+((time.getMonth()+1)<10?"0":"")+(time.getMonth()+1)+"-"+((time.getDate())<10?"0":"")+time.getDate()
      +" "+(time.getHours()<10?"0":"")+time.getHours()+":"+(time.getMinutes()<10?"0":"")+time.getMinutes()+":"+(time.getSeconds()<10?"0":"")+time.getSeconds();
}

const picLogMenu = reactive({
  showPopMenu:false,
  showTimePicker:false,
  selTimeIdx:0,
  selTime:Number(new Date()),
  style:{
    marginTop :'174rpx'
  },
  searchMenu_body_style:{
    height:'600rpx'
  },
  params:{
    deviceId:undefined,
    logType:undefined,
    startTime:undefined,
    endTime:undefined,
  },
  reqUrls:{
    sendCommand: "/device/mqtt/senCommand",
  }
});
function showTimePicker(idx){
  picLogMenu.selTimeIdx = idx;
  if(0==idx){
    picLogMenu.selTime =Number(new Date(picLogMenu.params.startTime));
    console.log('--------',picLogMenu.params.startTime,new Date(picLogMenu.params.startTime))
  }
  else{
    picLogMenu.selTime =Number(new Date(picLogMenu.params.endTime));
  }
  picLogMenu.showTimePicker = true;
}
function onSelectTime(o){
  var time = new Date(o.value);
  if(0==picLogMenu.selTimeIdx){
    picLogMenu.params.startTime = formatDate(time);
  }
  else {
    picLogMenu.params.endTime = formatDate(time);
  }
  console.log("----------",o,picLogMenu.selTime.toLocaleString(),time);
  picLogMenu.showTimePicker = false;
}
function onCancelSelectTime(){
  picLogMenu.showTimePicker = false;
}
function formatter(type, value) {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}

function openPicLogMenu(){
  picLogMenu.showPopMenu = true;
}
function sendCommand () {
  if(!picLogMenu.params.deviceId||picLogMenu.params.deviceId.length == 0){
    proxy.$modal.msg('请填写机器编号~')
    return
  }

  if(!picLogMenu.params.logType||picLogMenu.params.logType.length == 0){
    proxy.$modal.msg('请选择指令类型~')
    return
  }

  var templet = undefined;

  //templet = eval("(" +proxy.$getDictByCode(dicts.mqtt_cmd_templet_task,'log')+ ")");
  console.log(dicts.mqtt_cmd_templet_task);
  templet = JSON.parse(proxy.$getDictByCode(dicts.mqtt_cmd_templet_task,'log').value)
  templet.data.logType=picLogMenu.params.logType;
  templet.data.startTime=picLogMenu.params.startTime;
  templet.data.endTime=picLogMenu.params.endTime;


  var params = [{
    deviceId: picLogMenu.params.deviceId,
    templet: templet
  }];

  console.log("------------",JSON.stringify(params));
  proxy.$request({
    url: picLogMenu.reqUrls.sendCommand,
    data: params,
    method:'post'
  }).then(res => {
    console.log('***',res);
    proxy.$modal.msg('指令已下发~')
    resolve(res)
  }).catch(err => {
    console.log('***',err);
    //reject(err)
  })
}

const data = reactive({
  reqUrls:{
    list: '/device/device-log/page',

  },
  curPage:1,
  loadmoreStatus:'nomore',
  params:{
    readState: 1,
    priority: 1,
    page: {
      current: 1,
      size: 10,
      orders: [
        {
          asc: false,
          column: 'create_time'
        }]
    },
  },
  fullHeight:0,
  screenHeight:1920,
  // screenWidht:1080,
  dataList:[],
  total:0,
})


onMounted(() => {
  dicts.device_log_type = ([{value:null,label:'全部'}].concat(device_log_type.value));
  dicts.mqtt_cmd_templet_task = ([{value:null,label:'全部'}].concat(mqtt_cmd_templet_task.value));

  data.screenHeight = uni.getSystemInfoSync().windowHeight;//-uni.upx2px(100);
  searchMenu.searchMenu_body_style.height = (data.screenHeight-90)+"px";

  var time = new Date();
  picLogMenu.params.startTime = formatDate(time)
  time.setTime(time.getTime()+30*60*1000);
  picLogMenu.params.endTime = formatDate(time);

  proxy.$refs.datetimePicker.setFormatter(formatter)

  getList();

  const query = uni.createSelectorQuery().in(instance);
  query.select(".scrollview").boundingClientRect((r) => {
    uni.getSystemInfo({
      success(res) {
        // 针对iPhone X等机型底部安全距离做适配
        const model = res.model;
        const modelInclude = [
          "iPhone X",
          'iPhone XR',
          "iPhone XS",
          "iPhone XS MAX",
          "iPhone 12/13 mini",
          "iPhone 12/13 (Pro)",
          "iPhone 12/13 Pro Max",
          "iPhone 14 Pro Max"
        ];
        let safeDistance = modelInclude.includes(model)
        //动态设置商品区域高度
        console.log(res.windowHeight, r.top)
        // data.screenWidht = data1.right;

        let h = 0;
        if (safeDistance) {

          h = res.windowHeight - r.top;
        } else {
          h = res.windowHeight - r.top;
        }
        data.fullHeight+=h+"px";


        //console.log("--------",searchMenu.searchMenu_body_style);
      },
    });
  }).exec();

});
function scrolltolower(){
  if (data.loadmoreStatus == 'nomore') return
  data.curPage++
  getList()
}
function getList () {
  return new Promise((resolve, reject) => {
    data.params.page.current = data.curPage;
    data.params.deviceId = searchMenu.params.deviceId;
    data.params.type = searchMenu.params.type;
    if(data.curPage == 1){
      data.dataList = [];
    }
    proxy.$request({
      url: data.reqUrls.list,
      data: data.params,
      method:'post'
    }).then(res => {
      console.log('***',res);

      if (res.records) {
        data.dataList = data.dataList.concat(res.records)
      }
      data.total = res.total;
      if (res.records.length < 10) {
        data.loadmoreStatus = "nomore"
      } else {
        data.loadmoreStatus = "loadmore"
      }

      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

function showLog(file){
  proxy.$tab.navigateTo(`/pages/xy_system/logs/logFile?file=${file}`)
}

function rightClick () {
  console.log('点击了右侧')
}
</script>

<style lang="scss" scoped>
.container {
  .content {
    font-size: 28rpx;
    font-weight: 500;
    text-align: center;
    //margin-top: 135rpx;
  }

  .empty {
    margin-top: 50%;
  }
  .search{
    margin: 20rpx 10rpx;
  }
  .popMenu{
    background-color: white;
    padding: 20rpx 20rpx 20rpx 20rpx;
  }
  .searchMenu{
    width: 600rpx;
    font-size: 28rpx;
    flex-direction: column;
    position: relative;
    .searchMenu_body{
      overflow-y: scroll;
      margin-bottom: 100rpx;
    }
    .label{
      text-align: left;
      margin: 20rpx 10rpx 10rpx 10rpx;
      width: 600rpx;
    }
    .searchMenu_bottom{
      width: 100%;
      padding: 20rpx;
      position: absolute;
      bottom:0rpx;
      left:0;
    }
  }
  .topbar{
    background-color: white;
    padding: 0rpx 20rpx 0rpx 20rpx;
  }
  .data_total{
    padding-left: 20rpx;
    background-color: white;
    text-align: center;
    font-size: 28rpx;
  }
  .tab-list {
    width: 100%;
    background-color: #fff;
    padding: 0 26rpx;
    .tab-item{
      padding:0 20rpx;
      //width: 200rpx;
      height: 62rpx;
      background: #F7F7F7;
      border-radius: 10rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: #777777;
      line-height: 62rpx;
      margin-bottom: 14rpx;
      text-align:center;
      &.tab-show{
        background: #F4F8FF;
        color:#2C6FF3;
      }
    }
  }

  .scrollview{
    padding: 16rpx 16rpx 16rpx 16rpx;
    padding-bottom:calc(20rpx + env(safe-area-inset-bottom) / 2);

    .xy-card {
      margin-bottom: 24rpx;
    }

    .eq-item {
      position: relative;

      &+.eq-item {
        padding-top: 12rpx;
      }

      .eq-content {

        .eq-wrap {
          border-radius: 8rpx;
          background-color: white;//rgb(245, 248, 251);
          box-sizing: border-box;
          padding: 24rpx 12rpx;
          font-size: 26rpx;

          .eq-name {
            text-align: left;
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 12rpx;
            position: relative;

            >.eq-title{
              width: 420rpx;
              >text{
                font-size: 30rpx;
                color: #666;
                font-weight: normal;
              }
            }

            .eq-status-box{
              float: right;
              position: absolute;
              right:0;
              top:0;
            }

            .eq-status {
              font-size: 28rpx;
              color: #666;
              font-weight: normal;
              margin-left: 12rpx;

              >text {
                display: inline-block;
                background-color: #666;
                width: 16rpx;
                height: 16rpx;
                border-radius: 16rpx;
                margin-right: 12rpx;

              }

              &.online {
                color: #f56c6c;

                >text {
                  background-color: green;
                }
              }
            }
          }
        }

        .eqeq-type {
          display: flex;
          flex-direction: row;
          align-items: center;
          font-size: 28rpx;

          >view:nth-child(1) {
            text-align: left;
            color: #000;
            width: 220rpx;
          }

          >view:nth-child(2) {
            color: #666;
            padding-left: 6rpx;
            word-break: break-word;
            white-space: pre-line;
          }

          .logfile{
            color: #2C6FF3;
            font-style: italic;
          }
        }

        .eqeq-type+.eqeq-type{
          margin-top: 8rpx;
        }
        .message{
          min-height: 100rpx;
          border-style: solid;
          border-width: 2rpx;
          border-color: #cccccc;
          border-radius: 10rpx;
          margin: 20rpx 10rpx;
          padding: 10rpx 10rpx;
          background-color:#FFF0F5;
          text-align: left;
        }
        .status {
          width: 130rpx;
          height: 120rpx;
          box-sizing: border-box;
          border-radius: 120rpx;
          // border: 6rpx solid #2C6FF3;
          text-align: center;
          display: flex;
          flex-flow: column;
          justify-content: space-around;
          align-items: center;
          position: absolute;
          right: 12rpx;
          bottom: 24rpx;

          .s-name {
            font-size: 28rpx;
            padding-top: 20rpx;
            font-weight: bold;
          }

          .s-num {
            font-size: 32rpx;
            padding-bottom: 20rpx;
          }
        }
      }
    }
  }

}
</style>
