<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务号" prop="taskNo">
        <el-input
          v-model="queryParams.taskNo"
          placeholder="请输入任务ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="车辆编号" prop="robotNo">
        <el-select v-model="queryParams.robotNo" class="!w-240px" @change="handleQuery()">
          <el-option
            v-for="car in robotList"
            :key="car.id"
            :label="car.robotNo"
            :value="car.robotNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          class="!w-240px"
          clearable
          placeholder="请选择任务状态"
          @change="handleQuery()"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ROBOT_TASK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务阶段" prop="taskStage">
        <el-select
          v-model="queryParams.taskStage"
          class="!w-240px"
          clearable
          placeholder="请选择任务阶段"
          @change="handleQuery()"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ROBOT_QUEST_PHASES)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      :data="list"
      style="width: 100%"
      row-class-name="table-row-class"
      :header-cell-style="{ backgroundColor: '#EBF1FF', color: '#0D162A', padding: '13px 0' }"
      v-loading="loading"
    >
      <el-table-column align="center" label="序号" type="expand" width="60">
        <template #default="props">
          <div class="family-table">
            <el-table
              :data="props.row.details"
              border
              :span-method="(param) => objectSpanMethod(param, props.row.details)"
            >
              <el-table-column align="center" label="指令" prop="taskType">
                <template #default="scope">
                  <el-text class="mx-1" v-if="scope.row.taskType == 1">取放货</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 2">停车</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 3">充电</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 4">充电</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 5">仅取货</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 6">仅放货</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 7">扫描码</el-text>
                  <el-text class="mx-1" v-if="scope.row.taskType == 8">检测托盘类型</el-text>
                </template>
              </el-table-column>
              <el-table-column align="center" label="车辆编号" prop="robotNo" />
              <el-table-column align="center" label="取货点" prop="fromLocationNo" />
              <el-table-column align="center" label="放货点" prop="toLocationNo" />
              <el-table-column align="center" label="阶段" prop="taskStage">
                <template #default="scope">
                  <div class="task-stage" v-if="scope.row.taskStage == 0">
                    <div
                      class="icon-dot"
                      style="background-color: #e6b500; border: 0.0625rem solid #e6b500"
                    ></div>
                    <el-text class="mx-1">待执行</el-text>
                  </div>
                  <div class="task-stage" v-else-if="scope.row.taskStage == 1">
                    <div class="icon-dot"> </div>
                    <el-text class="mx-1">前往取货</el-text>
                  </div>
                  <div class="task-stage" v-else-if="scope.row.taskStage == 2">
                    <div class="icon-dot"> </div>
                    <el-text class="mx-1">取货中</el-text>
                  </div>
                  <div class="task-stage" v-else-if="scope.row.taskStage == 3">
                    <div class="icon-dot"> </div>
                    <el-text class="mx-1">运输中</el-text>
                  </div>
                  <div class="task-stage" v-else-if="scope.row.taskStage == 4">
                    <div class="icon-dot"> </div>
                    <el-text class="mx-1">放货中</el-text>
                  </div>
                  <div class="task-stage" v-else>
                    <div
                      class="icon-dot"
                      style="background-color: #4dc606; border: 0.0625rem solid #4dc606"
                    >
                    </div>
                    <el-text class="mx-1">已完成</el-text>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="270">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.taskStage !== 5"
                    type="warning"
                    @click="cancelTask(props.row, scope.row)"
                    >取消任务</el-button
                  >
                  <el-popover
                    placement="right"
                    :width="300"
                    trigger="click"
                    v-if="scope.row.taskStage === 0"
                  >
                    <template #reference>
                      <el-button type="primary" @click="modifyPriority(props.row, scope.row)"
                        >修改优先级</el-button
                      >
                    </template>
                    <div>
                      <span>修改优先级：</span>
                      <el-input
                        v-model="priorityNum"
                        style="width: 180px"
                        placeholder="优先级范围为1-100"
                        @blur="priorityNumChange(props.row, scope.row)"
                      />
                    </div>
                  </el-popover>

                  <el-button
                    type="primary"
                    @click="finishTask(props.row, scope.row)"
                    v-if="scope.row.taskStage !== 0 && scope.row.taskStage !== 5"
                    >人工完成</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务号" prop="taskNo" align="center" />
      <el-table-column label="优先级" prop="priority" align="center" />
      <el-table-column label="物料信息" prop="skuInfo" align="center" show-overflow-tooltip />
      <el-table-column
        label="开始时间"
        prop="startTime"
        :formatter="dateFormatter"
        align="center"
      />
      <el-table-column label="结束时间" prop="endTime" :formatter="dateFormatter" align="center" />
      <el-table-column label="任务状态" prop="taskStatus" align="center">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ROBOT_TASK_STATUS" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="其他信息" prop="otherMsg" align="center" show-overflow-tooltip />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { UserFilled, Close } from '@element-plus/icons-vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { TabsPaneContext } from 'element-plus'
import * as MapTaskAPi from '@/api/map/mapTask'

defineOptions({ name: 'taskManagementTaskList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { push } = useRouter()
const route = useRoute()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  taskNo: null,
  robotNo: null,
  taskStatus: null,
  taskStage: null
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MapTaskAPi.getTaskPageList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
//合并单元格
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }, list) => {
  if (columnIndex === 5) {
    if (rowIndex > 0 && list[rowIndex].taskStage === list[rowIndex - 1].taskStage) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    return {
      rowspan: getRowspan('taskStage', rowIndex, list),
      colspan: 1
    }
  }
}
// 获取行合并数
const getRowspan = (key, rowIndex, list) => {
  let rowspan = 1 //默认合并1行
  let curVal = list[rowIndex][key] //存储了当前值
  for (let i = rowIndex + 1; i < list.length; i++) {
    if (list[i][key] === curVal) {
      rowspan++
    } else {
      break
    }
  }
  return rowspan
}

//取消任务
const cancelTask = async (mainItem, item) => {
  try {
    await message.delConfirm('请确认是否取消所有任务？')
    await MapTaskAPi.updateTask({
      id: mainItem.id,
      priority: mainItem.priority,
      montageTask: mainItem.montageTask,
      montageNumber: mainItem.montageNumber,
      taskStatus: 3
    })
    message.success('已取消')
    await getList()
  } catch {}
}

//人工完成
const finishTask = async (mainItem, item) => {
  try {
    await message.delConfirm('请确认是否取消所有任务？')
    await MapTaskAPi.updateTask({
      id: mainItem.id,
      priority: mainItem.priority,
      montageTask: mainItem.montageTask,
      montageNumber: mainItem.montageNumber,
      taskStatus: 5
    })
    message.success('已取消')
    await getList()
  } catch {}
}

//修改优先级
const priorityNum = ref()
const modifyPriority = (mainItem, item) => {
  priorityNum.value = mainItem.priority
}
const priorityNumChange = async (mainItem, item) => {
  try {
    await MapTaskAPi.updateRobotTask({
      id: mainItem.id,
      priority: priorityNum.value,
      montageTask: mainItem.montageTask,
      montageNumber: mainItem.montageNumber
    })
    message.success('已修改')
    await getList()
  } catch {}
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

//查询能用的车辆
const robotList = ref([])
const getCanUseRobotList = async () => {
  robotList.value = await MapTaskAPi.getCanUseRobot()
}
// 匹配对应的值
const findPropertyValue = (arr, targetValue, compareProp, returnProp) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][compareProp] === targetValue) {
      return arr[i][returnProp]
    }
  }
  return undefined
}
/** 初始化 **/
onMounted(() => {
  if (route.query.type) {
    let data = getIntDictOptions(DICT_TYPE.ROBOT_TASK_STATUS)
    queryParams.taskStatus = findPropertyValue(data, route.query.type, 'label', 'value')
  }
  getList()
  getCanUseRobotList()
})
</script>

<style lang="scss" scoped>
.family-table {
  margin: 10px 20px 10px 50px;

  .task-stage {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .icon-dot {
    display: inline-block;
    width: 1.125rem;
    height: 1.125rem;
    padding: 0.1875rem;
    border-radius: 50%;
    background-clip: content-box;
    margin-right: 0.25rem;
    background-color: #409eff;
    border: 0.0625rem solid #409eff;
  }
}

::v-deep .table-row-class {
  background-color: #f9f9f9e5;
}
::v-deep .el-table__body .cell {
  font-weight: 400;
  font-size: 14px;
  color: #536387;
  padding: 4px 12px;
}
</style>
