<template>
  <el-row :gutter="20">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" @keyup.enter.native="queryClick">
      <el-form-item label="遥测站编码:" style="margin-left: 15px;width: 220px;">
        <el-input v-model="queryParams.stationCode" placeholder="遥测站编码" clearable width="100px" maxlength="10"
          size="small" />
      </el-form-item>
      <!-- <el-form-item label="报文组ID:" style="margin-left: 2px;width: 220px;">
            <el-input v-model="queryParams.packGid" placeholder="报文组ID" width="100px" clearable maxlength="40" />
          </el-form-item> -->
      <el-form-item label="上下行:" style="margin-left: 2px;width: 160px;">
        <el-select v-model="queryParams.upordown" class="filter-item" size="small" style="max-width: 100px;" clearable
          placeholder="上下行">
          <el-option v-for="item in upOrDownMap" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="报文类型:" style="margin-left: 2px;width: 230px;">
        <el-select v-model="queryParams.funCode" class="filter-item" size="small" style="max-width: 160px;" clearable
          placeholder="报文类型">
          <el-option v-for="item in funTypeMap" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="解析状态:" style="margin-left: 2px;width: 220px;">
        <el-select v-model="queryParams.flag" class="filter-item" size="small" style="max-width: 150px;" clearable
          placeholder="解析状态">
          <el-option v-for="(key, value) in dealFlagMap" :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>
        <el-button type="primary" class="button" @click="queryClick" :disabled="state.disabled">
          查询报文</el-button>
      </el-form-item>
    </el-form>
    <el-col :span="14">
      <div>
        <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%;margin-top: -15px;"
          :height="tableHeight" ref="my_table" highlight-current-row @current-change="handleCurrentRowChange"
          @row-click="tableRowClick" :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
          <el-table-column fixed type="index" width="50" align="center" />
          <el-table-column prop="stationCode" label="遥测站编码" header-align="center" width="110" />
          <!-- <el-table-column prop="packGid" label="报文组ID" header-align="center" width="150" /> -->
          <el-table-column prop="packCount" label="总包" header-align="center" width="55" align="center" />
          <el-table-column prop="packIndex" label="实收" header-align="center" width="55" align="center" />
          <el-table-column prop="upordown" label="上下行" header-align="center" width="70" align="center">
            <template #default="scope">
              <span v-if="scope.row.upordown === '0'">上行</span>
              <span v-if="scope.row.upordown === '8'">下行</span>
              <span v-if="scope.row.upordown !== '0'&&scope.row.upordown !== '8'">未知</span>
            </template>
          </el-table-column>
          <el-table-column prop="funName" label="类型" header-align="center" width="80" align="center" />
          <el-table-column prop="rptLen" label="长度" header-align="center" width="60" align="center" />
          <el-table-column prop="datatime" label="数据时间" header-align="center" width="138">
            <template #default="scope">
              {{ tool.dateFormat(scope.row.datatime, "YYYY-MM-DD HH:mm:ss",'YY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>

          <el-table-column prop="rptTime" label="发报时间" header-align="center" width="138">
            <template #default="scope">
              {{ tool.dateFormat(scope.row.rptTime, "YYYY-MM-DD HH:mm:ss",'YY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>

          <el-table-column prop="revTime" label="接收时间" header-align="center" width="138">
            <template #default="scope">
              {{ tool.dateFormat(scope.row.revTime, "YYYY-MM-DD HH:mm:ss",'YY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>

          <!-- <el-table-column prop="datatime" label="数据时间" header-align="center" width="100" align="center" />
          <el-table-column prop="rptTime" label="发报时间" header-align="center" width="100" align="center" />
          <el-table-column prop="revTime" label="接收时间" header-align="center" width="100" align="center" /> -->
          <el-table-column prop="flag" label="解析状态" header-align="center" width="100" align="center">
            <template #default="scope">
              <span>{{ dealFlagMap[scope.row.flag] }}</span>
            </template>
          </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="10" height="20px">
      <div style="height: calc(100vh - 125px);margin-top: -15px;">
        <textarea v-model="formData.originmessage"
          style="resize:none;height: calc(100vh - 195px);width: 100%;border: 1px solid #dbdbdb;" readonly></textarea>
      </div>
      <!-- <div style="border: 1px solid #dbdbdb; height: calc(100vh - 125px);">
        <el-input class="inputDeep" id="textarea" v-model="formData.originmessage" :autosize="{ maxRows: 32 }"
          type="textarea" placeholder="报文数据" readonly>
        </el-input>
      </div> -->
      <!-- <el-form :inline="true" :model="formData" :height="20" >      
        <el-input class="inputDeep" id="textarea" v-model="formData.originmessage" autosize type="textarea" placeholder="报文数据" readonly>
        </el-input>
      </el-form> -->
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from "vue";
import { ElForm, ElMessage } from 'element-plus';
import TPackLogAction from "@/api/tpacklog";
import { TPackLogQueryParam, TPackLogModel, Dialog, PageResult } from '@/types';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import elInput from "element-plus/lib/el-input";
import tool from "@/until/tool";
import Moment from "moment";

let locale = ref(zhCn)

const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;
const loading = ref(false)
const my_table = ref();
const defaultDate = new Date();

const state = reactive({
  queryParams: { page: 1, rows: pageSize, stationCode: '' } as TPackLogQueryParam,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  dialog: {} as Dialog,
  formData: {} as TPackLogModel,
  tableData: [] as TPackLogModel[],
  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 - 190);
const currentRow = ref()

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

//报文类型
const funTypeMap = [
  { value: 'FF', label: '全部' },
  { value: '32', label: '定时报' },
  { value: '36', label: '大图报' },
  { value: '52', label: '补发报' },
  { value: '54', label: '回执报文' },
  { value: 'e0', label: '远程配置' },
  { value: 'e1', label: '配置回执' },
  { value: 'e2', label: 'CNN数据' },
  { value: 'e4', label: '审核下发' },
  { value: 'e5', label: '审核回执' },
  { value: 'e6', label: '运行日志' },
  { value: 'ef', label: '召测任务' },
];

//上下行
const upOrDownMap = [
  { value: '0', label: '上行' },
  { value: '8', label: '下行' },
];

type mapStatee = Record<string, string>;
const dealFlagMap: mapStatee = {
  FF: '全部',
  0: "未解析",
  1: "已解析",
  10: "未解析[大]",
  11: "已解析[大]",
  20: "未解析[中]",
  21: "已解析[中]",
  44: "错误"
};

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

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

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

const queryList = () => {
  loading.value = true;
  state.disabled = true;

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

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

  TPackLogAction.QueryTPackLogListByQueryParam(queryParams.value).then(result => {
    state.disabled = false;
    if (result.status === 200) {
      const { res, flag, error } = result.data;

      if (flag === "1") {
        const pageData = res as PageResult<TPackLogModel[]>;
        state.tableData = pageData.list;
        state.total = pageData.total;

        //把第一个赋给右侧的日志框(默认选中)
        if (state.tableData != null && state.tableData.length > 0) {
          getPackMessage(state.tableData[0].id);
        }else{
          state.formData={} as TPackLogModel;
        }
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
  loading.value = false;
};

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

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

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

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

  queryList();
})

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

const queryClick = () => {
  state.queryParams.page = 1;
  queryList();

  if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
}
</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>