<template>
  <div class="water">
    <!-- 表格数据 -->
    <!-- 表头 -->
    <div class="theadDiv">
      <n-table
        :bordered="props.dataStyle.tableBordered"
        :single-column="props.dataStyle.tableSigleColumn"
        :single-line="props.dataStyle.tableSingleLine"
        :size="props.dataStyle.tableSize"
      >
        <thead v-if="props.dataStyle.tableHeaderShow">
          <tr
            :style="{
              backgroud: props.dataStyle.tableHeaderBackgroud,
            }"
          >
            <th
              class="th"
              v-if="props.dataStyle.tableOrderBumberShow"
              :style="{
                width: headWidths[0] + 'px',
              }"
            >
            </th>
            <th
              class="th"
              v-for="(item, index) in props.header"
              :key="index"
              :style="{
                width: headWidths[props.dataStyle.tableOrderBumberShow ? index + 1 : index] + 'px',
              }"
            >
              {{ item.title }}
            </th>
            <th
              class="th"
              v-if="props.dataStyle.tableButtonDivShow"
              :style="{
                width: headWidths[headWidths.length - 1] + 'px',
              }"
            >
              操作
            </th>
          </tr>
        </thead>
      </n-table>
    </div>
    <!-- 表格数据 -->
    <div class="tbodyDiv">
      <n-table
        :bordered="props.dataStyle.tableBordered"
        :single-column="props.dataStyle.tableSigleColumn"
        :single-line="props.dataStyle.tableSingleLine"
        :size="props.dataStyle.tableSize"
      >
        <tbody>
          <tr
            v-for="(dataItem, dataIndex) in filterData"
            :key="dataIndex"
            :class="dataIndex % 2 == 0 ? 'td_image1' : 'td_image2'"
          >
            <!-- 序号 -->
            <td
              id="dataTd_order"
              v-if="props.dataStyle.tableOrderBumberShow"
              :style="{
                width: props.dataStyle.tableOrderDivWidth + 'px',
              }"
            >
              {{ dataIndex + 1 }}
            </td>
            <!-- 数据 -->
            <td
              :id="'dataTd_' + headerIndex"
              v-for="(headerItem, headerIndex) in props.header"
              :key="headerIndex"
              :style="{
                width: headerItem.width + 'px',
              }"
            >
              <span>
                {{ dataItem[headerItem.key] ? convertData(headerItem, dataItem) : '--' }}
              </span>
            </td>
            <!-- 操作 -->
            <td
              id="dataTd_button"
              v-if="props.dataStyle.tableButtonDivShow"
              :style="{
                width: props.dataStyle.tableButtonDivWidth + 'px',
              }"
            >
              <div class="buttonDiv">
                <n-button size="small" quaternary @click="moveLocation(dataItem)">
                  <Button1 :dataStyle="props.dataStyle" />
                </n-button>
                <span class="buttonDivspan"> | </span>
                <n-button size="small" quaternary @click="roamLocation(dataItem)">
                  <Button2 :dataStyle="props.dataStyle" />
                </n-button>
              </div>
            </td>
          </tr>
        </tbody>
      </n-table>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, PropType, toRefs, watch, reactive, ref } from 'vue';
  import dayjs from 'dayjs';
  import { cloneDeep } from 'lodash-es';
  import Button1 from './button1.vue';
  import Button2 from './button2.vue';

  const props = defineProps(['dataset', 'dataStyle', 'header', 'h', 'filterDivHeight']);
  const emit = defineEmits(['moveLocation', 'roamLocation']);

  function moveLocation(dataItem) {
    emit('moveLocation', [dataItem.lng, dataItem.lat]);
  }
  function roamLocation(dataItem) {
    emit('roamLocation', [dataItem.lng, dataItem.lat]);
  }

  // 表头高度
  const headHeight: any = computed(() => {
    if (props.dataStyle.tableHeaderShow) {
      return document.querySelector('.theadDiv')?.offsetHeight + 10;
    } else {
      return 0;
    }
  });
  // 数据表实际宽度
  const headWidths = computed(() => {
    let widths: any = [];
    if (props.dataStyle.tableHeaderShow) {
      setTimeout(() => {
        if (props.dataStyle.tableOrderBumberShow) {
          widths.push(document.getElementById('dataTd_order')?.offsetWidth);
        }
        props.header.forEach((item, index) => {
          let td = document.getElementById('dataTd_' + index);
          widths.push(td?.offsetWidth);
        });
        if (props.dataStyle.tableButtonDivShow) {
          widths.push(document.getElementById('dataTd_button')?.offsetWidth);
        }
      }, 500);
    }
    return widths;
  });

  // 筛选后的数据
  const filterData = computed(() => {
    let data = props.dataset.filter((item) => item.type == 0);
    switch (props.dataStyle.distanceradio) {
      case '1':
        data = data.filter((d) => parseFloat(d.distance) <= 1);
        break;
      case '2':
        data = data.filter((d) => parseFloat(d.distance) <= 5);
        break;
      case '3':
        data = data.filter((d) => parseFloat(d.distance) <= 10);
        break;
      case '4':
        data = data.filter((d) => parseFloat(d.distance) <= 20);
        break;
      case '5':
        data = data;
        break;
    }
    return data;
  });

  // 数据转换
  function convertData(header, data) {
    let prefix = header.prefix ? header.prefix : '';
    let suffix = header.suffix ? header.suffix : '';
    let convertData = data[header.key];

    // 小数点保留后两位
    if (convertData && header.convert == '0' && isValidNumber(convertData)) {
      convertData =
        typeof convertData === 'string'
          ? String(parseFloat(convertData).toFixed(2))
          : String(convertData.toFixed(2));
    }
    // 转换时间格式（例：0小时0分钟0秒）
    if (convertData && header.convert == '1' && isValidTime(convertData)) {
      convertData =
        dayjs(convertData, 'HH:mm:ss').hour() +
        '小时' +
        dayjs(convertData, 'HH:mm:ss').minute() +
        '分钟' +
        dayjs(convertData, 'HH:mm:ss').second() +
        '秒';
    }
    // 转换日期格式（例：YYYY-MM-DD HH:mm:ss）
    let format = 'YYYY-MM-DD HH:mm:ss';
    if (header.convert == '2') {
      format = 'YYYY-MM-DD';
    }
    if (header.convert == '3') {
      format = 'YYYY/MM/DD';
    }
    if (
      convertData &&
      ['2', '3', '4'].includes(header.convert) &&
      isValidDate(convertData, format)
    ) {
      convertData = dayjs(convertData).format(format);
    }
    return prefix + convertData + suffix;
  }

  // 检查字符串可否转成数字
  function isValidNumber(str) {
    const regex = /^-?\d+(\.\d+)?$/;
    return regex.test(String(str).trim());
  }
  // 检查字符串可否转成时间
  function isValidTime(str) {
    const parsedDate = dayjs(str, 'HH:mm:ss');
    if (parsedDate.isValid()) {
      return true;
    } else {
      return false;
    }
  }
  // 检查字符串可否转成日期
  function isValidDate(str, format) {
    const parsedDate = dayjs(str, format);
    if (parsedDate.isValid()) {
      return true;
    } else {
      return false;
    }
  }
</script>

<style lang="scss" scoped>
  // 表头
  .theadDiv {
    margin-top: v-bind('`${props.dataStyle.tableMarginTop}px`');
    padding-left: v-bind('`${props.dataStyle.tableMarginLeft}px`');
    padding-right: v-bind('`${props.dataStyle.tableMarginLeft}px`');
  }
  // 表格部分
  .tbodyDiv {
    overflow-y: auto;
    height: v-bind(
      '`${props.h -props.filterDivHeight - props.dataStyle.filterMarginTop  - props.dataStyle.tableMarginTop}px`'
    );
    padding-left: v-bind('`${props.dataStyle.tableMarginLeft}px`');
    padding-right: v-bind('`${props.dataStyle.tableMarginLeft}px`');
  }
  .tbodyDiv::-webkit-scrollbar {
    display: none;
  }
  .tbodyDiv {
    scrollbar-width: none;
    -ms-overflow-style: none;
  }

  .th {
    background: v-bind('`${props.dataStyle.tableHeaderBackgroud}`');
    text-align: v-bind('`${props.dataStyle.tableAlign}`');
    color: v-bind('`${props.dataStyle.tableHeaderFontColor}`');
    font-size: v-bind('`${props.dataStyle.tableHeaderFontSize}px`');
  }
  td {
    text-align: v-bind('`${props.dataStyle.tableAlign}`');
    background: #ffffff00;
    color: v-bind('`${props.dataStyle.tableDataFontColor}`');
    font-size: v-bind('`${props.dataStyle.tableDataFontSize}px`');
    border-bottom: 0px;
  }
  .td_image1 {
    background-image: url('@/assets/images/chart/zhichu/component/ModalTable_td1.png');
    background-size: 100% 100%;
  }
  .td_image2 {
    background-image: url('@/assets/images/chart/zhichu/component/ModalTable_td2.png');
    background-size: 100% 100%;
  }

  .buttonDiv {
    display: flex;
    align-items: v-bind('`${props.dataStyle.tableAlign}`');
    justify-content: center;
  }

  .buttonDivspan {
    color: #00611a;
  }
</style>
