<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-v2 style="width: 196px" v-model="searchQueryFormEntity.isEmpty" placeholder="任务类型"
                                        :options="addAllOptionOfOptions(yesOrNoOptions)"
                                        @change="search()"></el-select-v2>
                                </el-form-item>
                                <el-form-item label="锁定">
                                    <el-select-v2 style="width: 196px" v-model="searchQueryFormEntity.isLock" placeholder="任务状态"
                                        :options="addAllOptionOfOptions(yesOrNoOptions)"
                                        @change="search()"></el-select-v2>
                                </el-form-item>
                                <el-form-item label="状态">
                                    <el-select-v2 style="width: 196px" v-model="searchQueryFormEntity.vehicleStatus" placeholder="任务状态"
                                        :options="addAllOptionOfOptions(vehicleStatusOptions)"
                                        @change="search()"></el-select-v2>
                                </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.locationId" @keyup.enter="search()"
                                        clearable />
                                </el-form-item>
                            </el-row>
                            <div style="align-content: center;">
                                <el-row>
                                    <el-button type="danger" class="btn-search" @click="openEmptyBoxDialog()">出空箱</el-button>
                                    <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 @row-click="getCurrentRow"
                        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                        @sort-change="handleSortChange">
                        <el-table-column width="65px" fixed="left">
                            <template v-slot="scope">
                                <el-radio :label="scope.row.vehicleId" v-model="vehicleId">&nbsp;</el-radio>
                            </template>
                        </el-table-column>
                        <el-table-column prop="vehicleId" label="箱号" fixed="left" min-width="120px" sortable="custom"
                            show-overflow-tooltip />
                        <el-table-column prop="vehicleStatus" label="状态" :formatter="vehicleStatusFormat" fixed="right"
                            min-width="120px" sortable="custom" show-overflow-tooltip />
                        <el-table-column prop="isEmpty" label="空箱" :formatter="yesOrNoFormat" min-width="120px"
                            sortable="custom" show-overflow-tooltip />
                        <!-- <el-table-column prop="vehicleType" label="料箱类型" min-width="120px" sortable="custom"
                            show-overflow-tooltip /> -->
                        <el-table-column prop="isLock" label="锁定" :formatter="yesOrNoFormat" min-width="120px"
                            sortable="custom" show-overflow-tooltip />
                        <el-table-column prop="locationId" label="库位" :formatter="locationFormat" min-width="120px"
                            sortable="custom" show-overflow-tooltip />
                        <el-table-column prop="lastInTime" label="上次入库时间" :formatter="timeFormat" min-width="120px"
                            sortable="custom" show-overflow-tooltip />
                        <!-- <el-table-column fixed="right" label="操作" width="170px">
                            <template v-slot="scope">
                                <div style="display: inline-block; align-content: center;">
                                    <el-button type="primary"
                                        @click="editCurrentRowFormEntity(scope.row)">编辑</el-button>
                                </div>
                            </template>
                        </el-table-column> -->
                    </el-table>
                    <br />
                    <el-pagination v-model:current-page="baseTableQuery.currentPage"
                        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>
  <el-dialog v-model="emptyBoxDialogVisible" title="出空箱" width="30%" draggable :show-close="false">
    <el-form ref="emptyBoxFormRef" :model="emptyBoxFormEntity" label-width="100px" status-icon>
      <el-form-item label="箱号" prop="vehicleId">
        <el-input
            v-model="emptyBoxFormEntity.vehicleId"
            placeholder="请输入箱号"
            clearable
            @input="handleVehicleIdInput"
        />
      </el-form-item>
      <el-form-item
          label="出空箱数量"
          prop="quantity"
          :rules="[{ required: true, message: '请输入数量', trigger: 'blur' }]">
        <el-input-number
            v-model="emptyBoxFormEntity.quantity"
            controls-position="right"
            :min="1"
            :max="9999"
            :disabled="!!(emptyBoxFormEntity.vehicleId && emptyBoxFormEntity.vehicleId.trim() !== '')"
            style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="cancelEmptyBox()">取消</el-button>
      <el-button type="primary" @click="submitEmptyBox()">确定</el-button>
    </span>
    </template>
  </el-dialog>

</template>

<script setup>
import store from '@/store'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { queryVehicleInfoByPage } from '@/api/vehicle.js'
import { timeFormatter, locationFormatter, yesOrNoFormatter, vehicleStatusFormatter } from '@/utils/formatter.js'
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { genTableRequest } from '@/utils/generator.js'
import { labelPosition } from '@/constant/form.js'
import { yesOrNoOptions, vehicleStatusOptions } from '@/constant/options.js'
import { addAllOptionOfOptions } from '@/utils/generator.js'
import { loading } from '@/utils/loading'
import {requireStockOutEmpty} from "@/api/task";
import {errorBox} from "@/utils/myMessageBox";
// 修改导入语句，添加正确的API函数

/**
 * 常量定义
 */
// 添加出空箱相关的响应式数据
const emptyBoxDialogVisible = ref(false)
const emptyBoxFormRef = ref()
const emptyBoxFormEntity = reactive({
  quantity: 1,
  vehicleId: '' // 新增箱号字段
})
const STAND_ID = store.getters.getStandId
const USER_NAME = store.getters.getUserName
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let tableData = ref([])
let baseTableQuery = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    sortBy: new Map([['lastInTime', true]]),// 按照成品号顺序排序
    standId: STAND_ID,
    userName: USER_NAME
})
let searchQueryFormEntity = reactive({
    vehicleId: '',
    locationId: '',
    vehicleStatus: -99,
    isLock: -99,
    isEmpty: -99
})
let searchQueryFormRef = ref()
let rowEditFlag = ref(false)
let vehicleId = ''
let rowEditFormRef = ref()
let rowFormEntity = reactive({})
/**
 * 系统方法
 */
onMounted(() => {
    nextTick(() => {
        window.addEventListener('resize', resizeHeight)
        search()
    })
})
onBeforeUnmount(() => {
    nextTick(() => {
        window.removeEventListener('resize', resizeHeight)
    })
})
const resizeHeight = () => {
    maxHeight.value = window.innerHeight * 0.55
}

/**
 * 自定义方法
 */
const handleVehicleIdInput = (value) => {
  // 如果输入了箱号，则限制数量为1
  if (value && value.trim() !== '') {
    emptyBoxFormEntity.quantity = 1
  }
}

// 查询
const search = () => {
    tableLoading.value = true
    let request = genTableRequest(baseTableQuery)
    // 设定查询参数
    request.vehicleId = searchQueryFormEntity.vehicleId.trim()
    request.locationId = searchQueryFormEntity.locationId.trim()
    request.vehicleStatus = searchQueryFormEntity.vehicleStatus == -99 ? null : searchQueryFormEntity.vehicleStatus
    request.isLock = searchQueryFormEntity.isLock == -99 ? null : searchQueryFormEntity.isLock
    request.isEmpty = searchQueryFormEntity.isEmpty == -99 ? null : searchQueryFormEntity.isEmpty
    queryVehicleInfoByPage(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.vehicleId = ''
    searchQueryFormEntity.locationId = ''
}
const handleSortChange = (data) => {
    if (baseTableQuery.sortBy.has(data.prop)) {
        baseTableQuery.sortBy.delete(data.prop)
    }
    baseTableQuery.sortBy.set(data.prop, data.order == 'ascending')
    search()
}
const getCurrentRow = (row) => {
    vehicleId = row.vehicleId
}
const timeFormat = (row, column, cellValue, index) => {
    return timeFormatter(cellValue)
}
const yesOrNoFormat = (row, column, cellValue, index) => {
    return yesOrNoFormatter(cellValue)
}
const locationFormat = (row, column, cellValue, index) => {
    return locationFormatter(cellValue)
}
const vehicleStatusFormat = (row, column, cellValue, index) => {
    return vehicleStatusFormatter(cellValue)
}
// 编辑弹框
const editCurrentRowFormEntity = (row) => {
    // 设置form值
    rowFormEntity.workIndex = row.workIndex
    rowFormEntity.workOrder = row.workOrder
    rowFormEntity.productId = row.productId
    rowFormEntity.singleProductId = row.singleProductId
    rowFormEntity.boxNo = row.boxNo
    rowFormEntity.goodsId = row.goodsId
    rowFormEntity.needNum = row.needNum
    rowFormEntity.distributeNum = row.distributeNum
    rowFormEntity.finishNum = row.finishNum
    rowFormEntity.workStatus = row.workStatus
    rowFormEntity.lackStatus = row.lackStatus
    // 弹出框
    rowEditFlag.value = true
}
// 关闭当前缺料工作
const closeLackWork = (row) => {
    const request = {
        workIndex: row.workIndex,
        standId: STAND_ID,
        userName: USER_NAME
    }
    loading.open('关闭中...')
    closeCurrentWorks(request).then(res => {
        const response = res.data
        if (response.code == 0) {
            ElMessage.success(response.message)
            search()
        } else {
            ElMessage.error(response.message)
        }
    }).catch(err => {
        console.log(err)
        ElMessage.error('请求异常。')
    }).finally(() => {
        loading.close()
    })
}
// 更新当前行数据
const submitUpdateRow = (rowFormEntity) => {
    const request = {
        workIndex: rowFormEntity.workIndex,
        distributeNum: rowFormEntity.distributeNum,
        finishNum: rowFormEntity.finishNum,
        workStatus: rowFormEntity.workStatus,
        lackStatus: rowFormEntity.lackStatus,
        standId: STAND_ID,
        userName: USER_NAME
    }
    loading.open('更新中...')
    updateKateWorks(request).then(res => {
        if (res.data.code == 0) {
            ElMessage.success('更新数据成功。')
            rowEditFlag.value = false
            search()
        } else {
            ElMessage.error('更新数据失败。')
        }
    }).catch(err => {
        console.log(err)
        ElMessage.error('更新数据异常。')
    }).finally(() => {
        loading.close()
    })
}
/**
 * 出空箱功能相关方法
 */
const openEmptyBoxDialog = () => {
  emptyBoxDialogVisible.value = true
}

const cancelEmptyBox = () => {
  emptyBoxDialogVisible.value = false
  emptyBoxFormEntity.quantity = 1
}

const submitEmptyBox = async () => {
  try {
    // 验证表单
    if (!emptyBoxFormRef.value) return

    await emptyBoxFormRef.value.validate()

    // 构造请求参数
    const request = {
      outType: 1,
      needNum: emptyBoxFormEntity.quantity,
      vehicleId: emptyBoxFormEntity.vehicleId,
      standId: STAND_ID,
      userName: USER_NAME,
      destination: STAND_ID
    }

    // 显示加载状态
    loading.open('提交中...')
    requireStockOutEmpty(request).then(res => {
      const response = res.data
      if (response.code === 0) {
        // 成功
        ElMessage.success(response.message)
      } else {
        errorBox(response.message)
      }
    }).catch(err => {
      console.log(err)
      errorBox('请求错误。')
    }).finally(() => {
      loading.close()
    })

  } catch (error) {
    loading.close()
    console.error('提交出空箱数量失败:', error)
    ElMessage.error('提交出空箱数量失败')
  }
}

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

.work-area {
    width: 100%;
    /* padding: 5px; */
}

.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-input-number {
    width: 196px;
}

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

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

.my-autocomplete li {
    width: 196px;
    line-height: normal;
    padding: 7px;
}

.my-autocomplete li .name {
    text-overflow: ellipsis;
    overflow: hidden;
}

.my-autocomplete li .addr {
    font-size: 12px;
    color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
    color: #ddd;
}

.my-autocomplete li .goods_id {
    color: brown;
}

.my-autocomplete li .goods_name {
    color: cornflowerblue;
}

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