<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="searchQueryFormRef" :model="searchQueryFormEntity" :label-position="labelPosition"
                   label-width="158px" style="max-width: 100%" status-icon>
            <div style="display: flex;justify-content: space-between;">
              <el-row>
                <el-form-item label="任务状态">
                  <el-select v-model="searchQueryFormEntity.wcsTaskStatus" placeholder="请选择任务状态" clearable>
                    <el-option v-for="item in taskStatusOptions" :key="item.value" :label="item.label"
                             :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="箱号">
                  <el-input v-model="searchQueryFormEntity.vehicleId" @keyup.enter="search()" clearable />
                </el-form-item>
                <el-form-item label="起点">
                  <el-input v-model="searchQueryFormEntity.origin" @keyup.enter="search()" clearable />
                </el-form-item>
                <el-form-item label="终点">
                  <el-input v-model="searchQueryFormEntity.destination" @keyup.enter="search()" clearable />
                </el-form-item>
              </el-row>
              <div style="align-content: center;">
                <el-row>
                  <el-button type="primary" class="btn-search" @click="search()">查询</el-button>
                  <el-button type="warning" class="btn-search" @click="clearQuery()">清除输入</el-button>
                </el-row>
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="tableData" stripe border v-loading="tableLoading" class="table-class"
                    :max-height="maxHeight" highlight-current-row
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                    @sort-change="handleSortChange">
            <el-table-column prop="wcsTaskId" label="任务号" fixed="left" min-width="180px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="vehicleId" label="箱号" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="wcsTaskStatus" label="任务状态" min-width="100px" sortable="custom"
                             show-overflow-tooltip>
              <template #default="scope">
                {{ getTaskStatusLabel(scope.row.wcsTaskStatus) }}
              </template>
            </el-table-column>
            <el-table-column prop="wcsTaskType" label="任务类型" min-width="100px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="taskPriority" label="优先级" min-width="80px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="origin" label="起点" min-width="120px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="destination" label="终点" min-width="120px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" min-width="160px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="sendTime" label="下发时间" min-width="160px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="finishTime" label="完成时间" min-width="160px" sortable="custom"
                             show-overflow-tooltip />
            <el-table-column prop="remark" label="备注" min-width="120px" sortable="custom"
                             show-overflow-tooltip />
          </el-table>
          <br />
          <el-pagination v-model:current-page="baseTableQuery.pageNo"
                         v-model:page-size="baseTableQuery.pageSize" :page-sizes="[10, 25, 50]" :small="false"
                         :disabled="false" :background="false" :default-page-size="10" @size-change="search"
                         @current-change="search" layout="total, sizes, prev, pager, next, jumper"
                         :total="baseTableQuery.total" />
        </div>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { queryWcsTaskInfoByPage } from '@/api/wcsTask.js'
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { labelPosition } from '@/constant/form.js'

/**
 * 常量定义
 */
const taskStatusOptions = [
  { value: 0, label: '任务初始化' },
  { value: 1, label: '任务排队中' },
  { value: 2, label: '任务开始执行' },
  { value: 3, label: '任务已经离开初始位置' },
  { value: 4, label: '任务到达中间点' },
  { value: 5, label: '任务到达目的地' },
  { value: 100, label: '任务完成' },
  { value: 998, label: '任务取消' },
  { value: 999, label: '任务异常' }
]

/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let tableData = ref([])
let baseTableQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  sortBy: [{
    column: 'wcs_task_id',
    asc: true
  }]
})
let searchQueryFormEntity = reactive({
  wcsTaskStatus: '',
  vehicleId: '',
  origin: '',
  destination: ''
})
let searchQueryFormRef = ref()

/**
 * 系统方法
 */
onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', resizeHeight)
    search()
  })
})

onBeforeUnmount(() => {
  nextTick(() => {
    window.removeEventListener('resize', resizeHeight)
  })
})

const resizeHeight = () => {
  maxHeight.value = window.innerHeight * 0.55
}

/**
 * 自定义方法
 */
// 查询
const search = () => {
  tableLoading.value = true
  let request = {
    ...baseTableQuery,
    wcsTaskStatus: searchQueryFormEntity.wcsTaskStatus,
    vehicleId: searchQueryFormEntity.vehicleId.trim(),
    origin: searchQueryFormEntity.origin.trim(),
    destination: searchQueryFormEntity.destination.trim()
  }

  queryWcsTaskInfoByPage(request).then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        tableData.value = data.lists
        baseTableQuery.total = data.total
      } else {
        tableData.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询数据异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}

const clearQuery = () => {
  searchQueryFormEntity.wcsTaskStatus = ''
  searchQueryFormEntity.vehicleId = ''
  searchQueryFormEntity.origin = ''
  searchQueryFormEntity.destination = ''
}

const handleSortChange = (data) => {
  // 将驼峰命名转换为下划线命名
  const columnMap = {
    'wcsTaskId': 'wcs_task_id',
    'wcsTaskStatus': 'wcs_task_status',
    'wcsTaskType': 'wcs_task_type',
    'taskPriority': 'task_priority',
    'vehicleId': 'vehicle_id',
    'createTime': 'create_time',
    'sendTime': 'send_time',
    'finishTime': 'finish_time'
  }

  baseTableQuery.sortBy = [{
    column: columnMap[data.prop] || data.prop,
    asc: data.order.toLowerCase() === 'ascending'
  }]
  search()
}

const getTaskStatusLabel = (status) => {
  const option = taskStatusOptions.find(opt => opt.value === status)
  return option ? option.label : '未知'
}
</script>

<style scoped>
.content {
  display: flex;
  width: 100%;
}

.work-area {
  width: 100%;
}

.search-area {
  margin: auto;
  min-height: fit-content;
  max-height: 40%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.table-area {
  margin: auto;
  min-height: fit-content;
  max-height: 60%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.el-form-item {
  margin: 5px 5px 5px 5px;
}

.el-form-item .el-input {
  width: 196px;
}

.el-form-item .el-select {
  width: 196px;
}

.table-class {
  margin: 5px 5px 5px 5px;
  width: inherit;
}

.el-pagination {
  padding-left: 5px;
}

.btn-search {
  height: 30px;
  width: 80px;
  margin: auto 5px 5px auto;
  color: black;
}
</style>