<template>
  <Dialog v-model="dialogVisible" :title="title" width="545px" style="padding: 0">
    <el-form :model="formData" label-width="auto" ref="formRef" :rules="formRules">
      <el-form-item label="车辆类型" prop="robotModelId" required>
        <el-select
          v-model="formData.robotModelId"
          placeholder="请选择车辆类型"
          required
          :disabled="formData.id"
        >
          <el-option
            :label="item.robotModelNumber"
            :value="item.id"
            v-for="item in carModelList"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item required label="车辆编号" prop="robotNo">
        <el-input
          v-model="formData.robotNo"
          :disabled="false"
          placeholder="请输入车辆编号"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>
      <el-form-item required label="车辆状态" v-if="formData.id">
        <el-select v-model="formData.robotTaskModel" placeholder="请选择车辆类型" required>
          <el-option :label="'锁定'" :value="0" />
          <el-option :label="'正常'" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item required label="自动充电电量" prop="autoCharge">
        <el-input-number
          style="width: 100px"
          v-model="formData.autoCharge"
          :disabled="false"
          :controls="false"
          :precision="0"
          :step="1"
          type="number"
          :min="0"
          :max="99"
          placeholder="请输入自动充电电量"
        >
          <template #append>%</template>
        </el-input-number>
        <span style="margin-left: 5px">%</span>
        <span style="margin-left: 4px; color: #c60606; font-size: 12px"
          >建议自动充电电量大于30%</span
        >
      </el-form-item>
      <el-form-item required label="Mac地址" prop="macAddress">
        <el-input
          v-model="formData.macAddress"
          :disabled="false"
          placeholder="请输入Mac地址"
          maxlength="25"
          show-word-limit
        />
      </el-form-item>
      <el-form-item required label="选择范围" placeholder="请选择范围">
        <el-cascader
          :options="floorAreaList"
          :props="props"
          clearable
          :collapse-tags="false"
          v-model="floorAreaJsonData"
          @change="floorAreaChange"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="padding: 0 10px 10px 0">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
import * as MapTaskAPi from '@/api/map/mapTask'
import * as CarApi from '@/api/car/index'
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const title = ref('新建') // form表单
const formData = ref({
  robotModelId: undefined, //车辆类型id
  robotNo: undefined, //AGV编号
  macAddress: undefined, //mac地址
  floorAreaJson: [],
  autoCharge: undefined
})
const carModelList = ref([])
const floorAreaList = ref([])
const props = { multiple: true }
const floorAreaJsonData = ref([])

const getCarModelList = async () => {
  const res = await CarApi.robotGetAllModel()
  carModelList.value = res
}

const getFloorArea = async () => {
  const res = await CarApi.robotPositionGetMapAllNew()
  let data = []
  let floor = []
  data = res
  for (let key in res) {
    let obj = {
      value: key,
      label: key + '层',
      children: res[key].map((item) => {
        return { label: item.area, value: item.id, ...item, children: [] }
      })
    }
    floor.push(obj)
  }
  console.log(floor)
  floorAreaList.value = floor
}

const floorAreaChange = (value) => {
  console.log(value)
  formData.value.floorAreaJson = []
  value.forEach((item) => {
    formData.value.floorAreaJson.push(item[1])
  })
  console.log(formData.value.floorAreaJson)
}

const formRules = reactive({
  robotModelId: [{ required: true, message: '车辆类型不能为空', trigger: 'change' }],
  robotNo: [{ required: true, message: 'AGV编号不能为空', trigger: 'change' }],
  macAddress: [{ required: true, message: 'Mac地址不能为空', trigger: 'change' }],
  autoCharge: [{ required: true, message: '自动充电电量不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type, id) => {
  floorAreaJsonData.value = []
  getCarModelList()
  getFloorArea()
  dialogVisible.value = true
  resetForm()
  if (id) {
    title.value = '编辑'
    const data = await CarApi.getRobotInformation({ id })
    formData.value = data
    if (data.positionMapList.length) {
      data.positionMapList.forEach((item) => {
        floorAreaJsonData.value.push([item.floor, item.id])
      })
    }
    console.log(data)
  } else {
    title.value = '新建'
  }
  // getCanUseRobotList()
  // getTaskNo()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (!formData.value.floorAreaJson.length) {
    message.warning('请选择范围')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.id) {
      await CarApi.robotInformationUpdate(formData.value)
      message.success(t('common.updateSuccess'))
      dialogVisible.value = false
      emit('success')
    } else {
      await CarApi.robotInformationCreate(formData.value)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      emit('success')
    }
  } finally {
    formLoading.value = false
  }
}

//前往任务管理页面
const { push } = useRouter()
const taskManagement = () => {
  push({ name: 'taskManagementCreateTask' })
}

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

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

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    robotModelId: undefined, //车辆类型id
    robotNo: undefined, //AGV编号
    macAddress: undefined, //mac地址
    floorAreaJson: [],
    autoCharge: undefined
  }
  floorAreaJsonData.value = []
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  padding: 0 !important;
}
::v-deep .el-dialog__header {
  border-bottom: 1px solid #e8e8e8 !important;
}

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

.el-select-dropdown__loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  font-size: 20px;
}

.circular {
  display: inline;
  height: 30px;
  width: 30px;
  animation: loading-rotate 2s linear infinite;
}
.path {
  animation: loading-dash 1.5s ease-in-out infinite;
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: var(--el-color-primary);
  stroke-linecap: round;
}

@keyframes loading-rotate {
  to {
    transform: rotate(360deg);
  }
}
@keyframes loading-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -40px;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -120px;
  }
}
@keyframes custom-spin-move {
  to {
    opacity: 1;
  }
}
</style>
