<template>
  <el-dialog v-model="visible" title="历史记录" width="1200px" :before-close="handleClose">
    <!-- <el-tabs v-model="activeTab"> -->
    <!-- 船舶靠泊历史记录 tab -->
    <!-- <el-tab-pane label="船舶靠泊历史记录" name="shipBerthing"> -->
    <!-- 搜索和筛选区域 -->
    <div class="filter-container">
      <el-form :model="berthingQueryParams" label-width="80px" inline>
        <el-form-item label="类型">
          <el-select v-model="berthingQueryParams.type" style="width: 120px" placeholder="请选择类型">
            <el-option v-for="item in FACILITY_TYPE" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="关键字">
              <el-input v-model="berthingQueryParams.keyword" placeholder="请输入关键字搜索" clearable
                @keyup.enter="handleBerthingSearch" />
            </el-form-item> -->
        <el-form-item label="时间范围">
          <el-date-picker v-model="berthingDateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="handleBerthingDateChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleShorePowerConnectionSearch">搜索</el-button>
          <el-button @click="resetBerthingQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="berthingTableData" border stripe style="width: 100%" v-loading="berthingLoading">
      <el-table-column v-for="column in berthingColumns" :key="column.prop" :prop="column.prop" :label="column.label"
        :width="column.width" :formatter="column.formatter" />
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="berthingQueryParams.pageNo" v-model:page-size="berthingQueryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="berthingTotal" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleBerthingSizeChange" @current-change="handleBerthingCurrentChange" />
    </div>
    <!-- </el-tab-pane> -->


    <!-- <el-tab-pane label="船舶连接岸电箱历史记录" name="shorePowerConnection">

        <div class="filter-container">
          <el-form :model="shorePowerConnectionQueryParams" label-width="80px" inline>
            <el-form-item label="关键字">
              <el-input v-model="shorePowerConnectionQueryParams.keyword" placeholder="请输入关键字搜索" clearable
                @keyup.enter="handleShorePowerConnectionSearch" />
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker v-model="shorePowerConnectionDateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                @change="handleShorePowerConnectionDateChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleShorePowerConnectionSearch">搜索</el-button>
              <el-button @click="resetShorePowerConnectionQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>


        <el-table :data="shorePowerConnectionTableData" border stripe style="width: 100%"
          v-loading="shorePowerConnectionLoading">
          <el-table-column v-for="column in shorePowerConnectionColumns" :key="column.prop" :prop="column.prop"
            :label="column.label" :width="column.width" :formatter="column.formatter" />
        </el-table>


        <div class="pagination-container">
          <el-pagination v-model:current-page="shorePowerConnectionQueryParams.pageNo"
            v-model:page-size="shorePowerConnectionQueryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="shorePowerConnectionTotal" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleShorePowerConnectionSizeChange"
            @current-change="handleShorePowerConnectionCurrentChange" />
        </div> -->
    <!-- </el-tab-pane> -->
    <!-- </el-tabs> -->

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { MapApi } from "@/api/shorepower/map";
import {
  ElDialog,
  ElTabs,
  ElTabPane,
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination
} from 'element-plus'
import { CARGO_CATEGORY, FACILITY_TYPE, HARBOR_DISTRICT, getOperationTypeLabel, OPERATION_TYPE } from './dictionaryTable';
import { formatDuration, formatTimestamp, showStatus } from './utils';
import { RealtimeDeviceData } from '@/types/shorepower';

// 定义组件属性
interface Props {
  modelValue: boolean
  berthingData?: any[]
  shipParam?: { type: number, ids: number[] | null, shipId: number | null }
  shorePowerConnectionData?: any[]
  realtimeDeviceData: RealtimeDeviceData[];
}

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'berthing-search', params: any): void
  (e: 'shore-power-connection-search', params: any): void
}>()

// 属性定义
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  shipId: 0,
  berthingData: () => [],
  shorePowerConnectionData: () => []
})

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 船舶靠泊历史记录相关数据
const berthingQueryParams = ref({
  // keyword: '',
  startTime: '',
  endTime: '',
  ids: null as number[] | null,
  shipId: null as number | null,
  type: 1 as number | null,
  pageNo: 1,
  pageSize: 10
})

const berthingDateRange = ref<[string, string]>(['', ''])
const berthingLoading = ref(false)
const berthingTotal = ref(0)

// 船舶靠泊历史记录表格数据
const berthingTableData = ref<any[]>([])

// 船舶靠泊历史记录表格列
const berthingColumns = ref([
  {
    prop: 'shipBasicInfo',
    label: '船舶名称-英文名称',
    width: 200,
    formatter: (row) => {
      const name = row.shipBasicInfo?.name || '';
      const nameEn = row.shipBasicInfo?.nameEn || '';
      return `${name}${name && nameEn ? '-' : ''}${nameEn}`;
    }
  },
  { prop: 'shipBasicInfo.length', label: '船长', width: 200 },
  { prop: 'shipBasicInfo.width', label: '船宽', width: 150 },
  { prop: 'shipBasicInfo.tonnage', label: '最大载重', width: 150 },
  { prop: 'shipBasicInfo.voyage', label: '航线', width: 150 },
  { prop: 'applyInfo.departureHarborDistrict', label: '起运港', width: 150 },
  { prop: 'arrivalHarborDistrict', label: '到达港', width: 150 },
  { prop: 'applyInfo.operationType', label: '靠泊类型', width: 150, formatter: (_row, _column, cellValue) => getOperationTypeLabel(cellValue, OPERATION_TYPE) },
  { prop: '', label: '作业内容', width: 180 },
  /* {
    prop: 'applyInfo.loadingCargoCategory', label: '货物类型', width: 180,
    formatter: (row) => {
      if (row.applyInfo.operationType === 1) {
        return getOperationTypeLabel(row.applyInfo.loadingCargoCategory, CARGO_CATEGORY);
      } else if (row.applyInfo.operationType === 2) {
        return row.applyInfo.unloadingCargoCategory;
      } else if (row.applyInfo.operationType === 3) {
        return '装' + row.applyInfo.loadingCargoCategory + '-卸' + row.applyInfo.unloadingCargoCategory
      }
      return '';
    }
  }, */

  {
    prop: 'applyInfo.loadingCargoCategory', label: '货物名称', width: 180,
    formatter: (row) => {
      if (row.applyInfo.operationType === 1) {
        const label = getOperationTypeLabel(row.applyInfo.loadingCargoCategory, CARGO_CATEGORY);
        return label;
      } else if (row.applyInfo.operationType === 2) {
        const label = getOperationTypeLabel(row.applyInfo.unloadingCargoCategory, CARGO_CATEGORY);
        return label;
      } else if (row.applyInfo.operationType === 3) {
        return '装' + getOperationTypeLabel(row.applyInfo.loadingCargoCategory, CARGO_CATEGORY) + '-卸' + getOperationTypeLabel(row.applyInfo.unloadingCargoCategory, CARGO_CATEGORY)
      }
      return '';
    }
  },
  {
    prop: 'applyInfo.loadingCargoCategory', label: '货物吨数', width: 180,
    formatter: (row) => {
      if (row.applyInfo.operationType === 1) {
        return row.applyInfo.loadingCargoTonnage;
      } else if (row.applyInfo.operationType === 2) {
        return row.applyInfo.unloadingCargoTonnage;
      } else if (row.applyInfo.operationType === 3) {
        return '装' + row.applyInfo.loadingCargoTonnage + '-卸' + row.applyInfo.unloadingCargoTonnage
      }
      return '';
    }
  },
  { prop: 'usageRecordInfo.actualBerthTime', label: '靠泊时间', width: 180, formatter: (row) => formatTimestamp(row.usageRecordInfo.actualBerthTime) },
  { prop: 'usageRecordInfo.actualDepartureTime', label: '离泊时间', width: 180, formatter: (row) => formatTimestamp(row.usageRecordInfo.actualDepartureTime) },
  {
    prop: 'useStatus.status', label: '岸电使用情况', width: 180,
    formatter: (row) => {
      const status = showStatus(row, props.realtimeDeviceData);
      return status?.status || '';
    }
  },

])

const shorePowerConnectionTotal = ref(0)

// 处理日期变化
const handleBerthingDateChange = (val: [string, string]) => {
  if (val && val.length === 2) {
    berthingQueryParams.value.startTime = val[0] + ' 00:00:00'
    berthingQueryParams.value.endTime = val[1] + ' 23:59:59'
  } else {
    berthingQueryParams.value.startTime = ''
    berthingQueryParams.value.endTime = ''
  }
  handleShorePowerConnectionSearch()
}

// 处理关闭
const handleClose = () => {
  berthingQueryParams.value.ids = null
  berthingQueryParams.value.shipId = null
  berthingQueryParams.value.type = 1
  visible.value = false
}

// 船舶靠泊历史记录相关方法
const handleBerthingSearch = () => {
  // 发送搜索事件给父组件
  emit('berthing-search', { ...berthingQueryParams.value })
}

const resetBerthingQuery = () => {
  // berthingQueryParams.value.keyword = ''
  berthingQueryParams.value.startTime = ''
  berthingQueryParams.value.endTime = ''
  berthingDateRange.value = ['', '']
  berthingQueryParams.value.pageNo = 1
  handleShorePowerConnectionSearch()
}


const handleBerthingSizeChange = (val: number) => {
  berthingQueryParams.value.pageSize = val
  berthingQueryParams.value.pageNo = 1
  handleShorePowerConnectionSearch()
}

const handleBerthingCurrentChange = (val: number) => {
  berthingQueryParams.value.pageNo = val
  handleShorePowerConnectionSearch()
}

// 船舶连接岸电箱历史记录相关方法
const handleShorePowerConnectionSearch = () => {
  // const 
  const params = {
    // shipId: berthingQueryParams.value.shipId,
    // ids: berthingQueryParams.value.ids,
    ...(berthingQueryParams.value.ids ? { ids: berthingQueryParams.value.ids } : {}),
    ...(berthingQueryParams.value.shipId ? { shipId: berthingQueryParams.value.shipId } : {}),
    type: berthingQueryParams.value.type,
    pageNo: 1,
    pageSize: 9999 // 请求足够多的数据，以便在前端进行筛选和分页
  }
  handleGetShipHistortyList(params)
  // 发送搜索事件给父组件
  // emit('shore-power-connection-search', { ...shorePowerConnectionQueryParams.value })
}

// 监听数据变化并更新总数
watch(
  () => props.berthingData,
  (newData) => {
    berthingTotal.value = newData?.length || 0
  },
  { immediate: true }
)

watch(
  () => props.shorePowerConnectionData,
  (newData) => {
    shorePowerConnectionTotal.value = newData?.length || 0
  },
  { immediate: true }
)

watch(
  () => props.shipParam,
  (newShipParam) => {
    if (newShipParam) {
      // 当船舶ID变化时，触发搜索
      berthingTableData.value = []
      if (newShipParam.shipId) {
        berthingQueryParams.value.shipId = newShipParam.shipId
      } else {
        berthingQueryParams.value.shipId = null
      }
      if (newShipParam.ids && newShipParam.ids.length > 0) {
        berthingQueryParams.value.ids = newShipParam.ids
      } else {
        berthingQueryParams.value.ids = null
      }
      berthingQueryParams.value.type = newShipParam.type
      // handleGetShipHistortyList()
      handleShorePowerConnectionSearch()
    }
  }
)
const handleGetShipHistortyList = async (param) => {
  console.log('handleGetShipHistortyList', param)
  if (!param) return;
  // try {
  const res = await MapApi.getShipHistoryPage({
    /* shipId: param.id, // 将字符串转换为数字
    pageNo: 1,
    pageSize: 10,
    type: param.type, */
    // ids: [parseInt(id, 10)]
    ...param
  })
  console.log(res);

  // 本地日期筛选逻辑
  let filteredList = [...res.list];
  if (berthingQueryParams.value.startTime || berthingQueryParams.value.endTime) {
    filteredList = filteredList.filter(item => {
      const berthTime = item.usageRecordInfo?.actualBerthTime;
      if (!berthTime) return false;

      const berthTimestamp = new Date(berthTime).getTime();
      const startTime = berthingQueryParams.value.startTime ? new Date(berthingQueryParams.value.startTime).getTime() : 0;
      const endTime = berthingQueryParams.value.endTime ? new Date(berthingQueryParams.value.endTime).getTime() : Infinity;

      // 检查靠泊时间是否在筛选范围内
      if (berthTimestamp >= startTime && berthTimestamp <= endTime) {
        return true;
      }

      // 如果有离泊时间，也检查离泊时间是否在筛选范围内
      if (item.usageRecordInfo?.actualDepartureTime) {
        const departureTimestamp = new Date(item.usageRecordInfo.actualDepartureTime).getTime();
        if (departureTimestamp >= startTime && departureTimestamp <= endTime) {
          return true;
        }
      }

      // 检查筛选范围是否与靠泊-离泊时间段有重叠
      if (item.usageRecordInfo?.actualDepartureTime) {
        const departureTimestamp = new Date(item.usageRecordInfo.actualDepartureTime).getTime();
        if (berthTimestamp <= endTime && departureTimestamp >= startTime) {
          return true;
        }
      }

      return false;
    });
  }

  // 前端分页逻辑
  const totalFiltered = filteredList.length;
  const pageNo = berthingQueryParams.value.pageNo;
  const pageSize = berthingQueryParams.value.pageSize;
  const startIndex = (pageNo - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedList = filteredList.slice(startIndex, endIndex);
  const harborDistructList = await HARBOR_DISTRICT()
  const buildData = await Promise.all(paginatedList.map(async item => ({
    ...item,
    arrivalHarborDistrict: getOperationTypeLabel(item.applyInfo.arrivalHarborDistrict, harborDistructList),
  })))
  berthingTableData.value = buildData
  berthingTotal.value = totalFiltered
}

onMounted(() => {
  console.log('页面加载了！')
  // console.log('props.shipId', props.shipId)
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>