<template>
  <div class="page">
    <ContentWrap>
      <div class="top-header">
        <span class="title">发起任务</span>
        <div>
          <el-button :icon="RefreshRight" @click="resetFormData">重置</el-button>
          <el-button type="primary" :icon="Position" @click="submitForm" :disabled="formLoading"
            >确认</el-button
          >
        </div>
      </div>
    </ContentWrap>

    <el-form :model="formData" label-width="94" ref="taskFormRef">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span class="line"></span>
            <span>任务基本信息</span>
          </div>
        </template>
        <div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item required label="任务号" prop="taskNo" label-width="146">
                <el-input v-model="formData.taskNo" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item required label="是否拼接任务" prop="montageTask" label-width="146">
                  <el-select
                    v-model="formData.montageTask"
                    placeholder="请选择"
                    @change="montageTaskChange"
                  >
                    <el-option label="不拼接" :value="0" />
                    <el-option label="拼接" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.montageTask === 1">
                <el-form-item required label="任务拼接数量" prop="montageNumber" label-width="146">
                  <el-input-number
                    :disabled="montageNumberDisable"
                    class="!w-220px"
                    v-model="formData.montageNumber"
                    :min="1"
                    :max="100"
                    @change="montageNumberChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <div>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="搬空所选线库/区域"
                    prop="doMoveAll"
                    label-width="146"
                  >
                    <el-switch
                      v-model="formData.doMoveAll"
                      :active-value="1"
                      :inactive-value="0"
                      :before-change="doMoveAllChange.bind()"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item required label="任务循环" prop="doCycle" label-width="146">
                    <el-switch
                      v-model="formData.doCycle"
                      :active-value="1"
                      :inactive-value="0"
                      :before-change="doCycleChange.bind()"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="formData.doCycle === 1">
                  <el-form-item required label="循环次数" prop="cycleNumber" label-width="146">
                    <el-input-number class="!w-220px" v-model="formData.cycleNumber" :min="0" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="物料信息" prop="skuInfo" label-width="146">
                    <el-input
                      v-model="formData.skuInfo"
                      placeholder="请输入物料信息"
                      maxlength="100"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="优先级" prop="priority" label-width="146">
                    <el-input-number
                      placeholder="优先级范围为1-100"
                      v-model="formData.priority"
                      :min="1"
                      :max="100"
                      class="!w-220px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="其他信息" prop="otherMsg" label-width="146">
                    <el-input
                      v-model="formData.otherMsg"
                      placeholder="请输入其他信息"
                      maxlength="100"
                      show-word-limit
                      type="textarea"
                      rows="3"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-card>

      <el-card shadow="never" class="mt-4">
        <template #header>
          <div class="card-header">
            <span class="line"></span>
            <span>任务详情</span>
          </div>
        </template>
        <div class="task-list">
          <div
            v-for="(detailItem, index) in formData.taskDetailList"
            :key="index"
            class="task-item"
          >
            <div class="index-logo">{{ index + 1 }}</div>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item
                  required
                  label="任务类型"
                  :prop="`taskDetailList[${index}].taskType`"
                  :rules="{ required: true, message: '任务类型不能为空', trigger: 'change' }"
                >
                  <el-select
                    v-model="detailItem.taskType"
                    placeholder="请选择"
                    @change="taskTypeChange(detailItem, index)"
                  >
                    <!--
                   暂时去除所有发起任务的校验
                   <el-option
                      v-for="item in detailItem.taskTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    /> -->

                    <el-option
                      v-for="item in allTaskTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 取放货 -->
            <div v-if="detailItem.taskType === 1">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="取货类型"
                    :prop="`taskDetailList[${index}].takeType`"
                    :rules="{ required: true, message: '取货类型不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.takeType"
                      placeholder="请选择取货类型"
                      @change="takeTypeChange(detailItem)"
                    >
                      <el-option label="库位" :value="1" />
                      <el-option label="线库" :value="2" />
                      <el-option label="区域" :value="3" />
                      <el-option label="取放货点" :value="4" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="取货位置"
                    :prop="`taskDetailList[${index}].takeId`"
                    :rules="{ required: true, message: '取货位置不能为空', trigger: 'change' }"
                  >
                    <div style="width: 100%; display: flex; align-items: center">
                      <el-select
                        :disabled="!detailItem.takeType"
                        v-model="detailItem.takeId"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入取货位置"
                        :remote-method="
                          (query) => {
                            takeRemoteMethod(query, detailItem)
                          }
                        "
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in detailItem.takeList"
                          :key="item.id"
                          :label="detailItem.takeType == 4 ? item.pointName : item.locationNo"
                          :value="item.id"
                        />
                      </el-select>
                      <el-icon
                        class="ml-2"
                        size="20"
                        color="#00329F"
                        @click="chooseLocation('take', detailItem, index)"
                        ><Location />
                      </el-icon>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="放货类型"
                    :prop="`taskDetailList[${index}].releaseType`"
                    :rules="{ required: true, message: '放货类型不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.releaseType"
                      placeholder="请选择放货类型"
                      @change="releaseTypeChange(detailItem)"
                    >
                      <el-option label="库位" :value="1" />
                      <el-option label="线库" :value="2" />
                      <el-option label="区域" :value="3" />
                      <el-option label="取放货点" :value="4" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="放货位置"
                    :prop="`taskDetailList[${index}].releaseId`"
                    :rules="{ required: true, message: '放货位置不能为空', trigger: 'change' }"
                  >
                    <div style="width: 100%; display: flex; align-items: center">
                      <el-select
                        :disabled="!detailItem.releaseType"
                        v-model="detailItem.releaseId"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入放货位置"
                        :remote-method="
                          (query) => {
                            releaseRemoteMethod(query, detailItem)
                          }
                        "
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in detailItem.releaseList"
                          :key="item.id"
                          :label="detailItem.releaseType == 4 ? item.pointName : item.locationNo"
                          :value="item.id"
                        />
                      </el-select>
                      <el-icon
                        class="ml-2"
                        size="20"
                        color="#00329F"
                        @click="chooseLocation('release', detailItem, index)"
                        ><Location />
                      </el-icon>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="指定车辆">
                    <el-select
                      clearable
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="chooseCarErrorMsg"
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotNo"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 停车 -->
            <div v-if="detailItem.taskType === 2">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="车辆编号"
                    :prop="`taskDetailList[${index}].robotNo`"
                    :rules="{ required: true, message: '车辆不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="chooseCarErrorMsg"
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotList"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="停车后锁定"
                    :prop="`taskDetailList[${index}].needLock`"
                    :rules="{ required: true, message: '请选择停车后是否锁定', trigger: 'change' }"
                  >
                    <el-select v-model="detailItem.needLock" placeholder="停车后锁定">
                      <el-option label="是" :value="0" />
                      <el-option label="否" :value="1" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 充电 -->
            <div v-if="detailItem.taskType === 3">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="车辆编号"
                    :prop="`taskDetailList[${index}].robotNo`"
                    :rules="{ required: true, message: '车辆不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="
                        (e) => {
                          robotNoChange(e, detailItem)
                        }
                      "
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotList"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所选车辆电量" label-width="96">
                    <el-input v-model="detailItem.electricity" :disabled="true" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 移动 -->
            <div v-if="detailItem.taskType === 4">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="车辆编号"
                    :prop="`taskDetailList[${index}].robotNo`"
                    :rules="{ required: true, message: '车辆不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="chooseCarErrorMsg"
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotList"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="终点库位"
                    :prop="`taskDetailList[${index}].releaseId`"
                    :rules="{ required: true, message: '终点库位不能为空', trigger: 'change' }"
                  >
                    <el-select
                      :disabled="!detailItem.takeType"
                      v-model="detailItem.releaseId"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入终点库位"
                      :remote-method="
                        (query) => {
                          releaseRemoteMethod(query, detailItem)
                        }
                      "
                      :loading="loading"
                    >
                      <el-option
                        v-for="item in detailItem.releaseList"
                        :key="item.id"
                        :label="detailItem.releaseType == 4 ? item.pointName : item.locationNo"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 仅取货 -->
            <div v-if="detailItem.taskType === 5">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="取货类型"
                    :prop="`taskDetailList[${index}].takeType`"
                    :rules="{ required: true, message: '取货类型不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.takeType"
                      placeholder="请选择取货类型"
                      @change="takeTypeChange(detailItem)"
                    >
                      <el-option label="库位" :value="1" />
                      <el-option label="线库" :value="2" />
                      <el-option label="区域" :value="3" />
                      <el-option label="取放货点" :value="4" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="取货位置"
                    :prop="`taskDetailList[${index}].takeId`"
                    :rules="{ required: true, message: '取货位置不能为空', trigger: 'change' }"
                  >
                    <div style="width: 100%; display: flex; align-items: center">
                      <el-select
                        :disabled="!detailItem.takeType"
                        v-model="detailItem.takeId"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入取货位置"
                        :remote-method="
                          (query) => {
                            takeRemoteMethod(query, detailItem)
                          }
                        "
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in detailItem.takeList"
                          :key="item.id"
                          :label="detailItem.takeType == 4 ? item.pointName : item.locationNo"
                          :value="item.id"
                        />
                      </el-select>
                      <el-icon
                        class="ml-2"
                        size="20"
                        color="#00329F"
                        @click="chooseLocation('take', detailItem, index)"
                        ><Location />
                      </el-icon>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="车辆编号"
                    :prop="`taskDetailList[${index}].robotNo`"
                    :rules="{ required: true, message: '车辆不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="chooseCarErrorMsg"
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotList"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 仅放货 -->
            <div v-if="detailItem.taskType === 6">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="放货类型"
                    :prop="`taskDetailList[${index}].releaseType`"
                    :rules="{ required: true, message: '放货类型不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.releaseType"
                      placeholder="请选择放货类型"
                      @change="releaseTypeChange(detailItem)"
                    >
                      <el-option label="库位" :value="1" />
                      <el-option label="线库" :value="2" />
                      <el-option label="区域" :value="3" />
                      <el-option label="取放货点" :value="4" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="放货位置"
                    :prop="`taskDetailList[${index}].releaseId`"
                    :rules="{ required: true, message: '放货位置不能为空', trigger: 'change' }"
                  >
                    <div style="width: 100%; display: flex; align-items: center">
                      <el-select
                        :disabled="!detailItem.releaseType"
                        v-model="detailItem.releaseId"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入放货位置"
                        :remote-method="
                          (query) => {
                            releaseRemoteMethod(query, detailItem)
                          }
                        "
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in detailItem.releaseList"
                          :key="item.id"
                          :label="detailItem.releaseType == 4 ? item.pointName : item.locationNo"
                          :value="item.id"
                        />
                      </el-select>
                      <el-icon
                        class="ml-2"
                        size="20"
                        color="#00329F"
                        @click="chooseLocation('release', detailItem, index)"
                        ><Location />
                      </el-icon>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item required label="指定车辆" prop="montageTask">
                    <el-select
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="chooseCarErrorMsg"
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotList"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 移动到点位 -->
            <div v-if="detailItem.taskType === 9">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item
                    required
                    label="车辆编号"
                    :prop="`taskDetailList[${index}].robotNo`"
                    :rules="{ required: true, message: '车辆不能为空', trigger: 'change' }"
                  >
                    <el-select
                      v-model="detailItem.robotNo"
                      placeholder="请选择车辆"
                      @change="chooseCarErrorMsg"
                    >
                      <el-option
                        v-for="car in robotList"
                        :key="car.id"
                        :label="car.robotList"
                        :value="car.robotNo"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    required
                    label="终点点位"
                    :prop="`taskDetailList[${index}].releaseId`"
                    :rules="{ required: true, message: '终点点位不能为空', trigger: 'change' }"
                  >
                    <el-select
                      :disabled="!detailItem.takeType"
                      v-model="detailItem.releaseId"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入终点点位"
                      :remote-method="
                        (query) => {
                          endPointMethod(query, detailItem)
                        }
                      "
                      :loading="loading"
                    >
                      <el-option
                        v-for="item in detailItem.endPointList"
                        :key="item.id"
                        :label="item.locationNo"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-card>
    </el-form>

    <locationSelectionDialog
      ref="locationSelectionDialogRef"
      @location-selection-dialog-success="locationSelectionDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { RefreshRight, Position } from '@element-plus/icons-vue'
import * as MapTaskAPi from '@/api/map/mapTask'
import * as DeviceApi from '@/api/device/index'
import locationSelectionDialog from '../components/locationSelectionDialog.vue'

defineOptions({ name: 'TaskManagementCreateTask' })

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

const { push } = useRouter()

const allTaskTypeList = ref([
  { label: '取放货', value: 1 },
  { label: '停车', value: 2 },
  { label: '充电', value: 3 },
  { label: '移动', value: 4 },
  { label: '仅取货', value: 5 },
  { label: '仅放货', value: 6 },
  { label: '移动到点位', value: 9 }
])

const formData = ref({
  montageTask: 1, //是否拼接任务（0：不拼接、1：拼接）
  montageNumber: 1, //	拼接任务数量
  taskDetailList: [
    {
      taskType: 1, //任务类型（1：取放货、2：停车、 3：充电、4：移动、5：仅取货、6：仅放货、7：扫描码、8：检测托盘类型）
      releaseType: 1, //放货类型 1：库位、2：线库、 3：区域
      takeType: 1, //取货类型（1：库位、2：线库、 3：区域 4.取放货点）
      releaseId: undefined, //放货位置的id
      releaseList: [], //放货的名称的列表
      takeId: undefined, //取货位置的id
      takeList: [], //取货位置的名称列表
      robotNo: undefined, //车辆编号
      needLock: 0, //停车后锁定(0:否、1:是)
      electricity: undefined, //所选车辆电量(充电模式)
      taskTypeList: [
        { label: '取放货', value: 1 },
        { label: '停车', value: 2 },
        { label: '充电', value: 3 },
        { label: '移动', value: 4 },
        { label: '仅取货', value: 5 },
        { label: '仅放货', value: 6 },
        { label: '移动到点位', value: 9 }
      ]
    }
  ], //任务列表
  skuInfo: undefined, //物料信息
  skuBatch: undefined, //	物料批次号
  skuNumber: undefined, // 物料数量
  priority: 50, //	优先级
  otherMsg: undefined, //	其他信息
  doCycle: 0, //循环(0:不循环、1：循环)
  doMoveAll: 0, //是否搬空所选线库/区域(0:不搬空、1：搬空)
  cycleNumber: 0, //	循环次数
  remainingCycleNumber: 1, //剩余循环次数，默认1
  taskNo: undefined, //	任务号
  taskStatus: 0, //任务状态(0:未开始、1：执行中、2：已完成、3：已取消)
  taskStage: 0, //任务阶段(0:待执行、1：前往取货、2：取货中、3：运输中、4：放货中、5：结束)
  startTime: 0, //开始时间
  endTime: 0 //结束时间
})

//重置
const resetFormData = () => {
  formData.value = {
    montageTask: 1, //是否拼接任务（0：不拼接、1：拼接）
    montageNumber: 1, //	拼接任务数量
    taskDetailList: [
      {
        taskType: 1, //任务类型（1：取放货、2：停车、 3：充电、4：移动、5：仅取货、6：仅放货、7：扫描码、8：检测托盘类型）
        releaseType: 1, //放货类型 1：库位、2：线库、 3：区域 4：点位
        takeType: 1, //取货类型（1：库位、2：线库、 3：区域 4.取放货点）
        releaseId: undefined, //放货位置的id
        releaseList: [], //放货的名称的列表
        takeId: undefined, //取货位置的id
        takeList: [], //取货位置的名称列表
        robotNo: undefined, //车辆编号
        needLock: 0, //停车后锁定(0:否、1:是)
        electricity: undefined, //所选车辆电量(充电模式)
        taskTypeList: [
          { label: '取放货', value: 1 },
          { label: '停车', value: 2 },
          { label: '充电', value: 3 },
          { label: '移动', value: 4 },
          { label: '仅取货', value: 5 },
          { label: '仅放货', value: 6 },
          { label: '移动到点位', value: 9 }
        ]
      }
    ], //任务列表
    skuInfo: undefined, //物料信息
    skuBatch: undefined, //	物料批次号
    skuNumber: undefined, // 物料数量
    priority: 50, //	优先级
    otherMsg: undefined, //	其他信息
    doCycle: 0, //循环(0:不循环、1：循环)
    doMoveAll: 0, //是否搬空所选线库/区域(0:不搬空、1：搬空)
    cycleNumber: 0, //	循环次数
    remainingCycleNumber: 1, //剩余循环次数，默认1
    taskStatus: 0, //任务状态(0:未开始、1：执行中、2：已完成、3：已取消)
    taskStage: 0, //任务阶段(0:待执行、1：前往取货、2：取货中、3：运输中、4：放货中、5：结束)
    startTime: 0, //开始时间
    endTime: 0, //结束时间
    taskNo: undefined //	任务号
  }
  getTaskNo()
  taskFormRef.value?.resetFields()
}

//获取任务号
const getTaskNo = async () => {
  formData.value.taskNo = await MapTaskAPi.getTaskNo()
}

//获取取货位置可选的列表
const getLocationList = async (type, locationNo) => {
  if (type == 4) {
    return await DeviceApi.getWareHouseTakePointList({ pointType: 1 })
  } else {
    return await MapTaskAPi.getLocationByName({
      type, //	放货类型（1：库位、2：线库、 3：区域）
      locationNo
    })
  }
}
//放货的选择列表
const loading = ref(false)
const releaseRemoteMethod = async (query, item) => {
  if (query) {
    item.releaseList = await getLocationList(item.releaseType, query)
  } else {
    item.releaseList = []
  }
}
//取货的选择列表
const takeRemoteMethod = async (query, item) => {
  if (query) {
    item.takeList = await getLocationList(item.takeType, query)
  } else {
    item.takeList = []
  }
}
//终点点位
const endPointMethod = async (query, item) => {
  if (query) {
    item.endPointList = await getLocationList(4, query)
  } else {
    item.endPointList = []
  }
}

//查询能用的车辆
const robotList = ref([])
const getCanUseRobotList = async () => {
  robotList.value = await MapTaskAPi.getCanUseRobot()
}

//车辆切换
const robotNoChange = (e, detailItem) => {
  let car = robotList.value.find((item) => {
    return item.robotNo == e
  })
  detailItem.electricity = car.electricity

  if (car?.errorMsg) {
    message.warning(car.errorMsg)
  }
}

//任务类型切换
const montageNumberDisable = computed(() =>
  formData.value.taskDetailList.some((item) => {
    return item.taskType == 2 || item.taskType == 3
  })
)
const taskTypeChange = (item, index) => {
  item.releaseType = 1
  item.takeType = 1
  item.needLock = 0
  item.releaseId = undefined
  item.takeId = undefined
  item.robotNo = undefined
  item.electricity = undefined
  item.otherMsg = undefined
  item.releaseList = []
  item.takeList = []

  let nextItem = formData.value.taskDetailList[index + 1]
  if (!nextItem) return

  //搬空线库
  if (formData.value.doMoveAll === 1) {
    nextItem.taskTypeList = [{ label: '取放货', value: 1 }]
  } else {
    //开启了任务循环
    if (formData.value.doCycle === 1) {
      nextItem.taskTypeList = [
        { label: '取放货', value: 1 },
        { label: '移动', value: 4 },
        { label: '移动到点位', value: 9 }
      ]
    } else {
      if (item.taskType === 1) {
        nextItem.taskTypeList = [
          { label: '取放货', value: 1 },
          { label: '移动', value: 4 },
          { label: '仅取货', value: 5 },
          { label: '移动到点位', value: 9 }
        ]
      } else if (item.taskType === 2) {
        formData.value.taskDetailList = formData.value.taskDetailList.slice(0, index + 1)
        formData.value.montageNumber = formData.value.taskDetailList.length
      } else if (item.taskType === 3) {
        formData.value.taskDetailList = formData.value.taskDetailList.slice(0, index + 1)
        formData.value.montageNumber = formData.value.taskDetailList.length
      } else if (item.taskType === 4) {
        nextItem.taskTypeList = [
          { label: '取放货', value: 1 },
          { label: '移动', value: 4 },
          { label: '仅取货', value: 5 },
          { label: '移动到点位', value: 9 }
        ]
      } else if (item.taskType === 5) {
        nextItem.taskTypeList = [
          { label: '移动', value: 4 },
          { label: '仅放货', value: 6 },
          { label: '移动到点位', value: 9 }
        ]
      } else if (item.taskType === 6) {
        nextItem.taskTypeList = [
          { label: '取放货', value: 1 },
          { label: '移动', value: 4 },
          { label: '仅取货', value: 5 },
          { label: '移动到点位', value: 9 }
        ]
      }
    }
  }
}

//拼接的任务数量改变
const montageNumberChange = (currentValue: number, oldValue: number) => {
  if (currentValue > oldValue) {
    //增加
    let oldItem = formData.value.taskDetailList[oldValue - 1]
    let addLength = currentValue - formData.value.taskDetailList.length
    let taskTypeList

    //搬空线库
    if (formData.value.doMoveAll === 1) {
      taskTypeList = [{ label: '取放货', value: 1 }]
    } else {
      //开启了任务循环
      if (formData.value.doCycle === 1) {
        taskTypeList = [
          { label: '取放货', value: 1 },
          { label: '移动', value: 4 },
          { label: '移动到点位', value: 9 }
        ]
      } else {
        if (oldItem) {
          if (oldItem.taskType === 1) {
            taskTypeList = [
              { label: '取放货', value: 1 },
              { label: '移动', value: 4 },
              { label: '仅取货', value: 5 },
              { label: '移动到点位', value: 9 }
            ]
          } else if (oldItem.taskType === 4) {
            taskTypeList = [
              { label: '取放货', value: 1 },
              { label: '移动', value: 4 },
              { label: '仅取货', value: 5 },
              { label: '移动到点位', value: 9 }
            ]
          } else if (oldItem.taskType === 5) {
            taskTypeList = [
              { label: '移动', value: 4 },
              { label: '仅放货', value: 6 },
              { label: '移动到点位', value: 9 }
            ]
          } else if (oldItem.taskType === 6) {
            taskTypeList = [
              { label: '取放货', value: 1 },
              { label: '移动', value: 4 },
              { label: '仅取货', value: 5 },
              { label: '移动到点位', value: 9 }
            ]
          }
        } else {
          taskTypeList = [
            { label: '取放货', value: 1 },
            { label: '停车', value: 2 },
            { label: '充电', value: 3 },
            { label: '移动', value: 4 },
            { label: '仅取货', value: 5 },
            { label: '仅放货', value: 6 },
            { label: '移动到点位', value: 9 }
          ]
        }
      }
    }

    for (let index = 0; index < addLength; index++) {
      formData.value.taskDetailList.push({
        taskType: undefined, //任务类型（1：取放货、2：停车、 3：充电、4：移动、5：仅取货、6：仅放货、7：扫描码、8：检测托盘类型）
        releaseType: 1, //放货类型 1：库位、2：线库、 3：区域
        takeType: 1, //取货类型（1：库位、2：线库、 3：区域）
        releaseId: undefined, //放货位置的id
        releaseList: [], //放货的名称的列表
        takeId: undefined, //取货位置的id
        takeList: [], //取货位置的名称列表
        robotNo: undefined, //车辆编号
        needLock: 0, //停车后锁定(0:否、1:是)
        electricity: undefined, //所选车辆电量(充电模式)
        taskTypeList: index === 0 ? taskTypeList : []
      })
    }
  } else {
    //减少
    formData.value.taskDetailList = formData.value.taskDetailList.slice(0, currentValue)
  }
}

//是否拼接切换
const montageTaskChange = (e) => {
  if (e === 0) {
    formData.value.montageNumber = 1
    formData.value.taskDetailList = formData.value.taskDetailList.slice(0, 1)
  }
}

//搬空区域改变
const doMoveAllChange = (e) => {
  return new Promise((resolve, reject) => {
    resolve(true)
    // 暂时去除所有发起任务的校验
    // if (formData.value.doMoveAll === 1) {
    //   if (formData.value.doCycle === 1) {
    //     formData.value.taskDetailList.forEach((item, index) => {
    //       item.taskTypeList = [
    //         { label: '取放货', value: 1 },
    //         { label: '移动', value: 4 },
    //         { label: '移动到点位', value: 9 }
    //       ]
    //     })
    //   } else {
    //     formData.value.taskDetailList.forEach((item, index) => {
    //       item.taskType = undefined
    //       if (index === 0) {
    //         item.taskTypeList = [
    //           { label: '取放货', value: 1 },
    //           { label: '停车', value: 2 },
    //           { label: '充电', value: 3 },
    //           { label: '移动', value: 4 },
    //           { label: '仅取货', value: 5 },
    //           { label: '仅放货', value: 6 },
    //           { label: '移动到点位', value: 9 }
    //         ]
    //       } else {
    //         item.taskTypeList = []
    //       }
    //     })
    //   }
    //   resolve(true)
    // } else {
    //   try {
    //     ElMessageBox.confirm('开启搬空所选线库/区域，任务类型只能选择取放货，是否切换?', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     })
    //       .then(async () => {
    //         resolve(true)
    //         formData.value.taskDetailList.forEach((item) => {
    //           item.taskType = undefined
    //           item.taskTypeList = [{ label: '取放货', value: 1 }]
    //         })
    //       })
    //       .catch(() => {
    //         ElMessage({
    //           type: 'info',
    //           message: '取消成功'
    //         })
    //         reject(false)
    //       })
    //   } catch (err) {
    //     reject(false)
    //   }
    // }
  })
}

//任务循环切换
const doCycleChange = () => {
  return new Promise((resolve, reject) => {
    resolve(true)
    // 暂时去除所有发起任务的校验
    // if (formData.value.doCycle === 1) {
    //   formData.value.cycleNumber = 0 //循环次数
    //   formData.value.taskDetailList.forEach((item, index) => {
    //     item.taskType = undefined
    //     if (index === 0) {
    //       item.taskTypeList = [
    //         { label: '取放货', value: 1 },
    //         { label: '停车', value: 2 },
    //         { label: '充电', value: 3 },
    //         { label: '移动', value: 4 },
    //         { label: '仅取货', value: 5 },
    //         { label: '仅放货', value: 6 },
    //         { label: '移动到点位', value: 9 }
    //       ]
    //     } else {
    //       item.taskTypeList = []
    //     }
    //   })
    //   resolve(true)
    // } else {
    //   try {
    //     ElMessageBox.confirm('开启循环任务，任务类型只能选择取放货和移动，是否切换?', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     })
    //       .then(async () => {
    //         resolve(true)
    //         formData.value.cycleNumber = 1 //循环次数
    //         formData.value.taskDetailList.forEach((item) => {
    //           item.taskType = undefined
    //           if (formData.value.doMoveAll === 1) {
    //             item.taskTypeList = [{ label: '取放货', value: 1 }]
    //           } else {
    //             item.taskTypeList = [
    //               { label: '取放货', value: 1 },
    //               { label: '移动', value: 4 },
    //               { label: '移动到点位', value: 9 }
    //             ]
    //           }
    //         })
    //       })
    //       .catch(() => {
    //         ElMessage({
    //           type: 'info',
    //           message: '取消成功'
    //         })
    //         reject(false)
    //       })
    //   } catch (err) {
    //     reject(false)
    //   }
    // }
  })
}

//取货类型切换
const takeTypeChange = (item) => {
  item.takeId = undefined
}

//放货类型切换
const releaseTypeChange = (item) => {
  item.releaseId = undefined
}

//选择车辆
const chooseCarErrorMsg = (e) => {
  let carItem = robotList.value.find((item) => item.robotNo === e)

  if (carItem?.errorMsg) {
    message.warning(carItem.errorMsg)
  }
}

//提交表单
const taskFormRef = ref()
const formLoading = ref(false)

const submitForm = async () => {
  let valid = await taskFormRef.value.validate()
  if (valid) {
    formLoading.value = true
    try {
      formData.value.taskDetailList.forEach((item) => {
        delete item.releaseList
        delete item.takeList
        delete item.endPointList
      })
      await MapTaskAPi.createTask(formData.value)
      message.success(t('common.createSuccess'))
      push({ name: 'taskManagementTaskList' })
      resetFormData()
    } finally {
      formLoading.value = false
    }
  } else {
    message.warning('请补充完整表单信息！')
  }
}

//打卡地图选择放货和取货位置
//选择库位
const locationSelectionDialogRef = ref()
const chooseLocationType = ref('') //放货还是取货
const locationTypeNumber = ref(1) //1库位 2线库 3区域
const currentItemIndex = ref(0) // 选择的是哪一项
const chooseLocation = (type, item, index) => {
  chooseLocationType.value = type
  currentItemIndex.value = index
  if (type == 'take') {
    //取货
    locationTypeNumber.value = item.takeType
  } else {
    //放货
    locationTypeNumber.value = item.releaseType
  }
  locationSelectionDialogRef.value.open(locationTypeNumber.value, type)
}
//成功选择库位
const locationSelectionDialogSuccess = (item) => {
  if (chooseLocationType.value == 'take') {
    //取货
    if (locationTypeNumber.value == 1 || locationTypeNumber.value == 4) {
      // 1库位
      takeRemoteMethod(item.locationNo, formData.value.taskDetailList[currentItemIndex.value])
      formData.value.taskDetailList[currentItemIndex.value].takeId = item.id
    } else if (locationTypeNumber.value == 2) {
      // 2线库
      takeRemoteMethod(item.laneName, formData.value.taskDetailList[currentItemIndex.value])
      formData.value.taskDetailList[currentItemIndex.value].takeId = item.laneId
    } else if (locationTypeNumber.value == 3) {
      // 3区域
      takeRemoteMethod(item.areaName, formData.value.taskDetailList[currentItemIndex.value])
      formData.value.taskDetailList[currentItemIndex.value].takeId = item.areaId
    }
  } else if (chooseLocationType.value == 'release') {
    //放货
    if (locationTypeNumber.value == 1 || locationTypeNumber.value == 4) {
      // 1库位
      releaseRemoteMethod(item.locationNo, formData.value.taskDetailList[currentItemIndex.value])
      formData.value.taskDetailList[currentItemIndex.value].releaseId = item.id
    } else if (locationTypeNumber.value == 2) {
      // 2线库
      releaseRemoteMethod(item.laneName, formData.value.taskDetailList[currentItemIndex.value])
      formData.value.taskDetailList[currentItemIndex.value].releaseId = item.laneId
    } else if (locationTypeNumber.value == 3) {
      // 3区域
      releaseRemoteMethod(item.areaName, formData.value.taskDetailList[currentItemIndex.value])
      formData.value.taskDetailList[currentItemIndex.value].releaseId = item.areaId
    }
  }
}

/** 初始化 **/
onMounted(() => {
  getTaskNo()
  getCanUseRobotList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;

  .line {
    display: block;
    width: 4px;
    height: 14px;
    background: #0147eb;
    margin-right: 8px;
  }
}

.page {
  .top-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      font-family:
        PingFangSC,
        PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: #0d162a;
      line-height: 25px;
      text-align: center;
      font-style: normal;
    }
  }

  .task-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 6px 0 0 0;

    .task-item {
      border: 1px solid #e2e7f5;
      box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
      width: 48%;
      padding: 20px 20px 10px 20px;
      border-radius: 4px;
      margin: 0 11px 24px 11px;
      box-sizing: border-box;
      position: relative;

      .index-logo {
        width: 18px;
        height: 18px;
        line-height: 18px;
        background: #1989fa;
        font-size: 13px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        position: absolute;
        top: 10px;
        left: 10px;
      }
    }
  }
}
</style>
