<template>
  <el-row :gutter="20" style="margin-top: -10px;">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" @keyup.enter.native="queryList(true)">
      <el-form-item label="设备SN:" style="margin-left: 20px;width: 240px;">
        <el-input v-model="queryParams.deviceSn" placeholder="设备SN" width="90px" maxlength="11" show-word-limit
          size="small" clearable />
      </el-form-item>
      <el-form-item label="遥测站编码:" style="margin-left: 2px;width: 235px;">
        <el-input v-model="queryParams.stationCode" placeholder="遥测站编码" width="100px" maxlength="10" show-word-limit
          size="small" clearable />
      </el-form-item>

      <el-form-item label="日志来源:" style="margin-left: 2px;width: 180px;">
        <el-select v-model="queryParams.logFrom" class="filter-item" placeholder="日志来源" size="small" clearable>
          <el-option v-for="(key, value) in Dic.comLogFrom" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围:" style="margin-left:2px;">
        <el-config-provider :locale="locale">
          <el-date-picker v-model="state.defaultTime" type="datetimerange" start-placeholder="开始时间"
            style="width: 360px;" size="small" end-placeholder="结束时间" :default-time="state.defaultTime"
            value-format="YYYY-MM-DD HH:mm:ss" clearable />
        </el-config-provider>
      </el-form-item>

      <!-- <el-form-item label="手机号码:" style="margin-left: 2px;width: 235px;">
            <el-input v-model="queryParams.appLoginId" placeholder="手机号码" width="100px" maxlength="11" show-word-limit clearable/>
          </el-form-item> -->
      <el-form-item>
        <el-button type="primary" class="button" @click="queryList">查询日志</el-button>
      </el-form-item>
    </el-form>
    <el-col :span="12">
      <div>
        <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%;margin-top: -20px;"
          :height="tableHeight" highlight-current-row @current-change="handleCurrentRowChange" ref="my_table"
          @row-click="tableRowClick" :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
          <el-table-column fixed type="index" width="50" align="center" />
          <el-table-column fixed prop="deviceSn" label="设备SN" header-align="center" width="115" align="center" />
          <el-table-column prop="stationCode" label="遥测站编码" header-align="center" width="110" />
          <el-table-column prop="stationName" label="遥测站名称" header-align="center" width="110" show-overflow-tooltip />
          <!-- <el-table-column prop="appLoginId" label="手机号码" header-align="center" width="110" /> -->
          <!-- <el-table-column prop="memo" label="备注信息" header-align="center" min-width="200" align="center" /> -->

          <el-table-column prop="createTime" label="创建时间" header-align="center" width="138">
            <template #default="scope">
              {{ tool.dateFormatYMDHm(scope.row.createTime,"YYYYMMDDHHmmss",'YY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>

          <el-table-column prop="sampleTime" label="采样时间" header-align="center" width="138">
            <template #default="scope">
              {{ tool.dateFormatYMDHm(scope.row.sampleTime,"YYYYMMDDHHmmss",'YY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>

          <el-table-column label="日志来源" header-align="center" width="90">
            <template #default="scope">
              <span>{{ Dic.comLogFrom[scope.row.logFrom] }}</span>
            </template>
          </el-table-column>

          <el-table-column label="MCU日志等级" header-align="center" width="80">
            <template #default="scope">
              <span>{{ global.getLogUploadLevelLabel(scope.row.mcuLogLevel) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="AI日志等级" header-align="center" width="70">
            <template #default="scope">
              <span>{{ global.getLogUploadLevelLabel(scope.row.aiLogLevel) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="appUserName" label="操作人" header-align="center" width="80" />
          <!-- <el-table-column label="" align="left" width="120" fixed="right">
            <template #default="scope">
              <el-button type="text" @click="showText(scope.row)">日志原文</el-button>
              <el-button type="text" @click="submitDeleteForm(scope.row)">删除</el-button>
            </template>
          </el-table-column> -->
          <!-- <el-table-column fixed="right"></el-table-column> -->
        </el-table>
        <el-config-provider :locale="locale">
          <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
            :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
            :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
            style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-config-provider>
      </div>
    </el-col>
    <el-col :span="12">
      <div style="height: calc(100vh - 130px);margin-top: -18px;">
        <textarea v-model="formData.rawComLog"
          style="resize:none;height: calc(100vh - 180px);width: 100%;border: 1px solid #dbdbdb;" readonly></textarea>
        <!-- <el-input class="inputDeep" id="textarea" v-model="formData.rawComLog" :autosize="{ maxRows: 37 }"
          type="textarea" placeholder="报文数据" readonly>
        </el-input> -->
      </div>
      <!-- <el-form :inline="true" :model="formData">
        <el-input id="textarea" v-model="formData.rawComLog" :rows="38" type="textarea" placeholder="APP串口日志原文"
          readonly>
        </el-input>
      </el-form> -->
    </el-col>
  </el-row>

  <!-- 下面是预留弹出式的 -->
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" draggable center>
    <el-form ref="dataFormRef" :model="formData" label-width="0">
      <el-form-item>
        <el-input id="textarea" v-model="formData.rawComLog" :rows="25" width="950px" type="textarea" readonly>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import TAppComlogAction from "@/api/app/tappcomlog";
import { TAppComlogQueryParam, TAppComlogModel, Dialog, PageResult } from '@/types';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import elInput from "element-plus/lib/el-input";
import global from '@/until/global';
import tool from '@/until/tool';
import Dic from "@/dictionary/aicbqcfg";
import Moment from "moment";

let locale = ref(zhCn)
const my_table = ref();
const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const defaultDate = new Date();

const loading = ref(false)
let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;

const state = reactive({
  queryParams: { page: 1, rows: pageSize } as TAppComlogQueryParam,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  dialog: {} as Dialog,
  formData: {} as TAppComlogModel,
  tableData: [] as TAppComlogModel[],
  defaultTime: [Moment(defaultDate.getTime() - 1000 * 3600 * 24 * 15).format("YYYY-MM-DD 00:00:00"), Moment(defaultDate).format("YYYY-MM-DD 23:59:59"),],
});

const {
  queryParams,
  dialog,
  formData,
  tableData,
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 170);
const currentRow = ref()

const handleCurrentRowChange = (val: TAppComlogModel | undefined) => {
  currentRow.value = val
  if (val !== undefined) {
    getPackMessage(val.id);
  }
}

async function showText(row: any) {
  state.formData = row;
  let mytitle = '串口日志预览--SN:[' + state.formData.deviceSn + '][' + state.formData.createTime + ']';
  state.dialog = {
    title: mytitle,
    visible: true,
    disabled: false,
  };
}

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList(true);
  localStorage.setItem("PageSize", val.toString());
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList(true);
};

const queryList = (isTop: boolean) => {
  loading.value = true;

  if (state.queryParams.stationCode) {
    state.queryParams.stationCode = state.queryParams.stationCode.padStart(10, '0');     //不足10位前面自动补0
  }

  if (state.queryParams.deviceSn) {
    state.queryParams.deviceSn = state.queryParams.deviceSn.padStart(11, '0');     //不足10位前面自动补0
  }

  state.queryParams.startTime = state.defaultTime[0];
  state.queryParams.endTime = state.defaultTime[1];

  TAppComlogAction.QueryTAppComlogList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TAppComlogModel[]>;
        state.tableData = pageData.list;
        state.total = pageData.total;

        //把第一个赋给右侧的日志框(默认选中)
        if (state.tableData != null && state.tableData.length > 0) {
          getPackMessage(pageData.list[0].id);
        }

        if (isTop) {
          if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
        }
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
  loading.value = false;
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(
    ' 是否删除日志[' + row.deviceSn + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      TAppComlogAction.DeleteTAppComlog(row.id).then(result => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success('删除成功');
            queryList(false);
          } else {
            ElMessage.error(error);
          }
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除成功!',
      })
    })
};

const cancel = () => {
  dataFormRef.value.resetFields();
  state.formData = {} as TAppComlogModel;
  state.dialog.visible = false;
}

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 170
  }

  queryList(false);
})

const tableRowClick = (row: TAppComlogModel) => {
  state.formData = row;
  const textarea = document.getElementById('textarea');
  if (textarea != null) {
    textarea.scrollTop = 0;
  }
};


const getPackMessage = (id: number) => {
  TAppComlogAction.QueryTAppComlogById(id).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;

      if (flag === "1") {
        const pageData = res as TAppComlogModel;
        state.formData.rawComLog = pageData.rawComLog;
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
}
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}

::v-deep .el-table__body tr.current-row>td {
  color: #fff;
  background: #6db3fa !important;
}

::v-deep .el-textarea__inner {
  border: 0;
  resize: none;
  /* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
}
</style>