<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.taskType" placeholder="任务类型"
                                :options="addAllOptionOfOptions(taskTypeOptions)"
                                @change="search()"></el-select-v2>
                </el-form-item>
                <el-form-item label="任务状态">
                  <el-select-v2 style="width: 196px" v-model="searchQueryFormEntity.taskStatus" placeholder="任务状态"
                                :options="addAllOptionOfOptions(wmsTaskStatusOptions)"
                                @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.goodsId" @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 @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.taskId" v-model="taskId">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="taskId" label="任务号" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="taskType" label="任务类型" fixed="left" :formatter="taskTypeFormat" min-width="120px"
                             sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="taskStatus" label="任务状态" :formatter="taskStatusFormat" fixed="right"
                             min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="taskPriority" label="优先级" min-width="120px" 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="goodsId" label="料号" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="goodsDesc" label="物料描述"
                             min-width="120px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="opNum" label="操作数量" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="stockNum" label="库存数量" min-width="120px"
                             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="wcsTaskId" label="wcs任务号" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="createTime" label="创建时间" :formatter="timeFormat" min-width="120px"
                             sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="finishTime" label="完成时间" :formatter="timeFormat" min-width="120px"
                             sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="opUser" label="操作用户" min-width="120px"
                             sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="callStand" label="呼叫站台" min-width="120px"
                             sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="remark" label="备注" 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="editCurrentRowTask(scope.row)">编辑
                  </el-button>
                  <el-button type="danger"
                             @click="deleteCurrentRowTask(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>
        <el-dialog v-model="rowEditFlag" title="任务详情" width="40%" draggable :show-close="false">
          <el-form ref="rowEditFormRef" :model="rowEditFormEntity" :label-position="labelPosition"
                   label-width="100px" style="max-width: 100%" status-icon>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="任务号">
                  <el-input v-model="rowEditFormEntity.taskId" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务类型">
                  <el-select-v2 style="width: 196px" v-model="rowEditFormEntity.taskType" placeholder="请选择任务类型"
                                :options="taskTypeOptions" disabled></el-select-v2>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="任务状态">
                  <el-select-v2 style="width: 196px" v-model="rowEditFormEntity.taskStatus" placeholder="请选择任务状态"
                                :options="wmsTaskStatusOptions"></el-select-v2>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优先级">
                  <el-input-number v-model.number="rowEditFormEntity.taskPriority" controls-position="right"
                                   :min="0" :max="9"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="箱号">
                  <el-input v-model="rowEditFormEntity.vehicleId" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="料号">
                  <el-input v-model="rowEditFormEntity.goodsId" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="描述">
                  <el-input v-model="rowEditFormEntity.goodsDesc" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="wcs任务号">
                  <el-input v-model="rowEditFormEntity.wcsTaskId" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="操作数量">
                  <el-input-number v-model.number="rowEditFormEntity.opNum" controls-position="right"
                                   :min="0" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="库存数量">
                  <el-input-number v-model.number="rowEditFormEntity.stockNum" controls-position="right" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="起点">
                  <el-input v-model="rowEditFormEntity.origin" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="终点">
                  <el-input v-model="rowEditFormEntity.destination" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="创建时间">
                  <el-input type="text" v-model="rowEditFormEntity.createTime" :formatter="timeFormatter" disabled>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成时间">
                  <el-input type="text" v-model="rowEditFormEntity.finishTime" :formatter="timeFormatter" disabled>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="操作用户">
                  <el-input v-model="rowEditFormEntity.opUser" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="呼叫站台">
                  <el-input v-model="rowEditFormEntity.callStand" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="备注">
                  <el-input type="textarea" style="width: 196px" v-model="rowEditFormEntity.remark" maxlength="1024"
                            :autosize="{minRows: 1, maxRows: 4}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button type="primary" @click="rowEditFlag = false">取消</el-button>
              <el-button type="success" @click="submitUpdateRow(rowEditFormEntity)">
                确定
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import store from '@/store'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {queryTasksByPage} from '@/api/taskQuery.js'
import {deleteWmsTask, updateWmsTask} from '@/api/taskOperation'
import {timeFormatter, wmsTaskTypeFormatter, wmsTaskStatusFormatter} from '@/utils/formatter.js'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {genTableRequest} from '@/utils/generator.js'
import {labelPosition} from '@/constant/form.js'
import {taskTypeOptions, wmsTaskStatusOptions} from '@/constant/options.js'
import {addAllOptionOfOptions} from '@/utils/generator.js'
import {loading} from '@/utils/loading'

/**
 * 常量定义
 */
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([['createTime', true]]),// 按照成品号顺序排序
  standId: STAND_ID,
  userName: USER_NAME
})
let searchQueryFormEntity = reactive({
  vehicleId: '',
  goodsId: '',
  taskType: -99,
  taskStatus: -99
})
let searchQueryFormRef = ref()
let rowEditFlag = ref(false)
let taskId = ''
let rowEditFormRef = ref()
let rowEditFormEntity = reactive({
  taskId: '',
  taskType: null,
  taskStatus: null,
  taskPriority: null,
  vehicleId: '',
  origin: '',
  destination: '',
  wcsTaskId: '',
  createTime: null,
  finishTime: null,
  goodsId: '',
  opNum: null,
  stockNum: null,
  opUser: '',
  remark: '',
  callStand: '',
  goodsDesc: ''
})
/**
 * 系统方法
 */
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 = genTableRequest(baseTableQuery)
  // 设定查询参数
  request.vehicleId = searchQueryFormEntity.vehicleId.trim()
  request.goodsId = searchQueryFormEntity.goodsId.trim()
  request.taskType = searchQueryFormEntity.taskType === -99 ? null : searchQueryFormEntity.taskType
  request.taskStatus = searchQueryFormEntity.taskStatus === -99 ? null : searchQueryFormEntity.taskStatus
  queryTasksByPage(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.goodsId = ''
}
const handleSortChange = (data) => {
  if (baseTableQuery.sortBy.has(data.prop)) {
    baseTableQuery.sortBy.delete(data.prop)
  }
  baseTableQuery.sortBy.set(data.prop, data.order.toLowerCase() === 'ascending')
  search()
}
const getCurrentRow = (row) => {
  taskId = row.taskId
}
const timeFormat = (row, column, cellValue, index) => {
  return timeFormatter(cellValue)
}
const taskTypeFormat = (row, column, cellValue, index) => {
  return wmsTaskTypeFormatter(cellValue)
}
const taskStatusFormat = (row, column, cellValue, index) => {
  return wmsTaskStatusFormatter(cellValue)
}
// 编辑弹框
const editCurrentRowTask = (row) => {
  // 设置form值
  rowEditFormEntity.taskId = row.taskId
  rowEditFormEntity.taskType = row.taskType
  rowEditFormEntity.taskStatus = row.taskStatus
  rowEditFormEntity.taskPriority = row.taskPriority
  rowEditFormEntity.vehicleId = row.vehicleId
  rowEditFormEntity.origin = row.origin
  rowEditFormEntity.destination = row.destination
  rowEditFormEntity.wcsTaskId = row.wcsTaskId
  rowEditFormEntity.createTime = row.createTime
  rowEditFormEntity.finishTime = row.finishTime
  rowEditFormEntity.goodsId = row.goodsId
  rowEditFormEntity.opNum = row.opNum
  rowEditFormEntity.stockNum = row.stockNum
  rowEditFormEntity.opUser = row.opUser
  rowEditFormEntity.remark = row.remark
  rowEditFormEntity.callStand = row.callStand
  rowEditFormEntity.goodsDesc = row.goodsDesc
  // 弹出框
  rowEditFlag.value = true
}
// 删除当前任务行
const deleteCurrentRowTask = (row) => {
  ElMessageBox.confirm(
      '当前操作仅涉及删除当前任务行。\n是否确认',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    const request = {
      taskId: row.taskId,
      userName: USER_NAME,
      standId: STAND_ID
    }
    loading.open('删除中...')
    deleteWmsTask(request).then(res => {
      const response = res.data
      if (response.code === 0) {
        ElMessage.success(response.message)
      } else {
        ElMessage.error(response.message)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error('删除异常')
    }).finally(() => {
      search()
      loading.close()
    })
  }).catch(() => {
    ElMessage.info('操作取消')
  })
}
// 更新当前行数据
const submitUpdateRow = (rowFormEntity) => {
  const request = {
    taskId: rowFormEntity.taskId,
    taskStatus: rowFormEntity.taskStatus,
    taskPriority: rowFormEntity.taskPriority,
    opNum: rowFormEntity.opNum,
    destination: rowFormEntity.destination,
    remark: rowFormEntity.remark,
    standId: STAND_ID,
    userName: USER_NAME
  }
  loading.open('更新中...')
  updateWmsTask(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()
  })
}
</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;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>