<template>
  <el-dialog v-model="visible" title="岸电箱历史记录" width="1200px" :before-close="handleClose">
    <el-tabs v-model="activeTab">
      <!-- 岸电箱历史记录 tab -->
      <el-tab-pane label="岸电箱历史记录" name="shorePower">
        <!-- 搜索和筛选区域 -->
        <div class="filter-container">
          <el-form :model="queryParams" label-width="80px" inline>
            <el-form-item label="关键字">
              <el-input v-model="queryParams.keyword" placeholder="请输入关键字搜索" clearable @keyup.enter="handleSearch" />
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="handleDateChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 数据表格 -->
        <el-table :data="shorePowerTableData" border stripe style="width: 100%" v-loading="loading">
          <el-table-column v-for="column in tableColumns" :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="queryParams.pageNo" v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-tab-pane>

      <!-- 岸电箱连接船舶记录 tab -->
      <el-tab-pane label="岸电箱连接船舶记录" name="shipConnection">
        <!-- 搜索和筛选区域 -->
        <div class="filter-container">
          <el-form :model="shipConnectionQueryParams" label-width="80px" inline>
            <el-form-item label="关键字">
              <el-input v-model="shipConnectionQueryParams.keyword" placeholder="请输入关键字搜索" clearable
                @keyup.enter="handleShipConnectionSearch" />
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker v-model="shipConnectionDateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                @change="handleShipConnectionDateChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleShipConnectionSearch">搜索</el-button>
              <el-button @click="resetShipConnectionQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 数据表格 -->
        <el-table :data="shipConnectionTableData" border stripe style="width: 100%" v-loading="shipConnectionLoading">
          <el-table-column v-for="column in shipConnectionColumns" :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="shipConnectionQueryParams.pageNo"
            v-model:page-size="shipConnectionQueryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="shipConnectionTotal" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleShipConnectionSizeChange" @current-change="handleShipConnectionCurrentChange" />
        </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 {
  ElDialog,
  ElTabs,
  ElTabPane,
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination
} from 'element-plus'
import { MapApi } from "@/api/shorepower/map";

// 定义组件属性
interface Props {
  modelValue: boolean
  data?: any[]
  shipConnectionData?: any[]
  shorePowerId: number
}

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

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

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

const shorePowerTableData = ref<any[]>([])
const activeTab = ref('shorePower')

// 岸电箱历史记录相关数据
const queryParams = ref({
  keyword: '',
  startTime: '',
  endTime: '',
  pageNo: 1,
  pageSize: 10
})

const dateRange = ref<[string, string]>(['', ''])
const loading = ref(false)
const total = ref(0)

// 表格数据计算属性
const tableData = computed(() => {
  // 在实际应用中，这里应该是从服务器获取的数据
  // 当前为了演示，我们使用传入的模拟数据
  return props.data?.slice(
    (queryParams.value.pageNo - 1) * queryParams.value.pageSize,
    queryParams.value.pageNo * queryParams.value.pageSize
  ) || []
})

// 表格列
const tableColumns = ref([
  { prop: 'id', label: '记录ID', width: 80 },
  { prop: 'time', label: '时间', width: 180 },
  { prop: 'operation', label: '操作类型' },
  { prop: 'voltage', label: '电压(V)' },
  { prop: 'current', label: '电流(A)' },
  { prop: 'power', label: '功率(kW)' },
  { prop: 'energy', label: '用电量(kWh)' }
])

// 岸电箱连接船舶记录相关数据
const shipConnectionQueryParams = ref({
  keyword: '',
  startTime: '',
  endTime: '',
  pageNo: 1,
  pageSize: 10
})

const shipConnectionDateRange = ref<[string, string]>(['', ''])
const shipConnectionLoading = ref(false)
const shipConnectionTotal = ref(0)

// 岸电箱连接船舶记录表格数据
const shipConnectionTableData = computed(() => {
  // 在实际应用中，这里应该是从服务器获取的数据
  // 当前为了演示，我们使用传入的模拟数据
  return props.shipConnectionData?.slice(
    (shipConnectionQueryParams.value.pageNo - 1) * shipConnectionQueryParams.value.pageSize,
    shipConnectionQueryParams.value.pageNo * shipConnectionQueryParams.value.pageSize
  ) || []
})

// 岸电箱连接船舶记录表格列
const shipConnectionColumns = ref([
  { prop: 'id', label: '记录ID', width: 80 },
  { prop: 'shipName', label: '船舶名称', width: 150 },
  { prop: 'time', label: '连接时间', width: 180 },
  { prop: 'duration', label: '连接时长(小时)', width: 120 },
  { prop: 'powerConsumption', label: '用电量(kWh)', width: 120 },
  { prop: 'status', label: '状态', width: 100 }
])

// 处理关闭
const handleClose = () => {
  visible.value = false
}

// 岸电箱历史记录相关方法
const handleSearch = () => {
  // 发送搜索事件给父组件
  emit('search', { ...queryParams.value })
}

const resetQuery = () => {
  queryParams.value.keyword = ''
  queryParams.value.startTime = ''
  queryParams.value.endTime = ''
  dateRange.value = ['', '']
  queryParams.value.pageNo = 1
  handleSearch()
}

const handleDateChange = (val: [string, string] | null) => {
  if (val && val[0] && val[1]) {
    queryParams.value.startTime = val[0]
    queryParams.value.endTime = val[1]
  } else {
    queryParams.value.startTime = ''
    queryParams.value.endTime = ''
  }
}

const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  queryParams.value.pageNo = 1
  handleSearch()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNo = val
  handleSearch()
}

// 岸电箱连接船舶记录相关方法
const handleShipConnectionSearch = () => {
  // 发送搜索事件给父组件
  emit('ship-connection-search', { ...shipConnectionQueryParams.value })
}

const resetShipConnectionQuery = () => {
  shipConnectionQueryParams.value.keyword = ''
  shipConnectionQueryParams.value.startTime = ''
  shipConnectionQueryParams.value.endTime = ''
  shipConnectionDateRange.value = ['', '']
  shipConnectionQueryParams.value.pageNo = 1
  handleShipConnectionSearch()
}

const handleShipConnectionDateChange = (val: [string, string] | null) => {
  if (val && val[0] && val[1]) {
    shipConnectionQueryParams.value.startTime = val[0]
    shipConnectionQueryParams.value.endTime = val[1]
  } else {
    shipConnectionQueryParams.value.startTime = ''
    shipConnectionQueryParams.value.endTime = ''
  }
}

const handleShipConnectionSizeChange = (val: number) => {
  shipConnectionQueryParams.value.pageSize = val
  shipConnectionQueryParams.value.pageNo = 1
  handleShipConnectionSearch()
}

const handleShipConnectionCurrentChange = (val: number) => {
  shipConnectionQueryParams.value.pageNo = val
  handleShipConnectionSearch()
}

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

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

watch(
  () => props.shorePowerId,
  (newShorePowerId) => {
    if (newShorePowerId) {
      // 当岸电箱ID变化时，触发搜索
      shorePowerTableData.value = []
      handleGetShorePowerHistoryList(newShorePowerId)
    }
  }
)

const handleGetShorePowerHistoryList = async (id) => {
  console.log('handleGetShorePowerHistoryList', id)
  if (!id) return;
  // try {
  const res = await MapApi.getShipHistoryPage({
    shipId: parseInt(id, 10), // 将字符串转换为数字
    pageNo: 1,
    pageSize: 10,
    type: 5,
    // ids: [parseInt(id, 10)]
  })
  console.log(res);
  const buildData = await Promise.all(res.list.map(async item => ({
    ...item,
  })))
  shorePowerTableData.value = buildData
}

onMounted(() => {
  console.log('页面加载了！')
  console.log('props.shipId', props.shorePowerId)
})
</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>