<template>
  <Dialog v-model="dialogVisible" :title="title" width="545" style="padding: 0">
    <el-form :model="formData" label-width="auto" ref="formRef" :rules="formRules">
      <el-form-item label="设备类型" prop="deviceType">
        <el-select
          v-model="formData.deviceType"
          clearable
          placeholder="请选择设备类型"
          @change="deviceTypeChange"
        >
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.DEVICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="Number(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceNo">
        <el-input
          v-model="formData.deviceNo"
          :disabled="false"
          placeholder="请输入设备编号(25字以内)"
          maxlength="25"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="摄像头编号" prop="cameraCode" v-if="formData.deviceType == 9">
        <el-input
          v-model="formData.cameraCode"
          :disabled="false"
          placeholder="请输入摄像头编号(50字以内)"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="Mac地址" prop="macAddress" v-if="formData.deviceType !== 9">
        <el-input
          v-model="formData.macAddress"
          :disabled="false"
          placeholder="请输入Mac地址"
          maxlength="25"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="设备IP" v-if="formData.deviceType !== 9">
        <el-input
          v-model="formData.deviceIp"
          :disabled="false"
          show-word-limit
          placeholder="请输入设备ip"
          maxlength="20"
          @input="formData.deviceIp = formData.deviceIp.replace(/[^\d.]/g, '')"
        />
      </el-form-item>
      <el-form-item label="端口" v-if="formData.deviceType !== 9">
        <el-input
          v-model="formData.devicePort"
          :disabled="false"
          show-word-limit
          placeholder="请输入端口"
          maxlength="10"
          @input="formData.devicePort = formData.devicePort.replace(/[\u4E00-\u9FA5]/g, '')"
        />
      </el-form-item>
      <el-form-item label="充电桩类型" prop="deviceAttribute" v-if="formData.deviceType == 1">
        <el-select v-model="formData.deviceAttribute" clearable placeholder="请选择设备类型">
          <el-option :label="'自动充电'" :value="1" />
          <el-option :label="'手动充电'" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="摄像头类型" prop="cameraType" v-if="formData.deviceType == 9">
        <el-select v-model="formData.cameraType" clearable placeholder="请选择摄像头类型">
          <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-form-item label="设备位置" v-if="formData.deviceType == 9">
        <el-input
          v-model="formData.deviceLocation"
          :disabled="false"
          placeholder="请输入设备位置"
          maxlength="25"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="deviceEnable">
        <el-select v-model="formData.deviceEnable" clearable placeholder="请选择是否启用">
          <el-option :label="'禁用'" :value="0" />
          <el-option :label="'启用'" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备取放货点位" v-if="formData.deviceType == 10" required>
        <el-select v-model="formData.takePointId" filterable placeholder="请输入取放货点位">
          <el-option
            v-for="item in takePointList"
            :key="item.id"
            :label="item.pointName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检测区点位" v-if="formData.deviceType == 10" required>
        <el-select
          v-model="formData.checkPointIds"
          multiple
          filterable
          placeholder="请选择检测区点位"
        >
          <el-option
            v-for="item in checkPointList"
            :key="item.id"
            :label="item.pointName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备图标">
        <UploadImg v-model="formData.mapImageUrl" :limit="1" />
      </el-form-item>
      <el-form-item label="设备图配置" prop="pictureConfig">
        <el-radio-group v-model="formData.pictureConfig">
          <el-radio :label="1">默认图片</el-radio>
          <el-radio :label="2">上传图片</el-radio>
          <el-radio :label="3">不显示图片</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="设备图片" prop="mapImageUrl" v-if="formData.pictureConfig === 2">
        <UploadImg v-model="formData.url" :limit="1" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="padding: 0 10px 10px 0">
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
import * as DeviceApi from '@/api/device/index'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const title = ref('新建') // form表单
const formData = ref({
  deviceType: undefined, //设备类型
  deviceNo: undefined, //车辆编号
  macAddress: undefined, //mac地址
  mapImageUrl: undefined, //设备在地图上图标
  pictureConfig: undefined, //	图片设置（1：默认图片、2：上传图片、 3：不显示图片）
  url: undefined, //上传图片附件
  deviceAttribute: undefined,
  deviceEnable: undefined, //设备启用禁用 设备启用禁用（0：禁用、1：启用）
  devicePort: undefined, //端口
  deviceIp: undefined, //设备IP
  cameraType: undefined, //摄像头类型
  deviceLocation: undefined, //设备位置
  cameraCode: undefined, //摄像头编号
  takePointId: undefined, //取放货点位
  checkPointIds: [] //检测区点位
})

// 取放货点位列表
const takePointList = ref([])
// 检测区点位列表
const checkPointList = ref([])

// 获取取放货点位列表
const getTakePointList = async () => {
  try {
    takePointList.value = await DeviceApi.getWareHouseTakePointList({ pointType: 1 })
  } catch (error) {
    console.error('获取取放货点位失败:', error)
    takePointList.value = []
  }
}

// 获取检测区点位列表
const getCheckPointList = async () => {
  try {
    checkPointList.value = await DeviceApi.getWareHouseTakePointList({ pointType: 0 })
  } catch (error) {
    console.error('获取检测区点位失败:', error)
    checkPointList.value = []
  }
}

const formRules = reactive({
  deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'blur' }],
  deviceNo: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  macAddress: [{ required: true, message: 'Mac地址不能为空', trigger: 'blur' }],
  mapImageUrl: [{ required: true, message: '设备图标不能为空', trigger: 'blur' }],
  pictureConfig: [{ required: true, message: '设备图配置不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '设备图片不能为空', trigger: 'blur' }],
  deviceAttribute: [{ required: true, message: '充电类型不能为空', trigger: 'blur' }],
  deviceEnable: [{ required: true, message: '是否启用不能为空', trigger: 'blur' }],
  cameraType: [{ required: true, message: '摄像头类型不能为空', trigger: 'blur' }],
  cameraCode: [{ required: true, message: '摄像头编号不能为空', trigger: 'blur' }],
  takePointId: [{ required: true, message: '取放货点位不能为空', trigger: 'blur' }],
  checkPointIds: [{ required: true, message: '检测点不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type, id) => {
  dialogVisible.value = true
  resetForm()
  if (id) {
    title.value = '编辑'
    await loadDeviceDetail(id)
  } else {
    title.value = '新建'
  }
}

/** 加载设备详情 */
const loadDeviceDetail = async (id) => {
  const data = await DeviceApi.deviceInformationGet({ id })
  formData.value = data

  if (!formData.value.mapImageUrl) {
    DeviceApi.getMapDeviceImageUrl({
      deviceType: formData.value.deviceType
    }).then((res) => {
      formData.value.mapImageUrl = res ? res : undefined
    })
  }

  // 根据设备类型设置 cameraType
  if (formData.value.deviceType !== 9) {
    formData.value.cameraType = undefined
  }

  // 如果是翻转机，获取点位列表
  if (formData.value.deviceType === 10) {
    await getTakePointList()
    await getCheckPointList()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.id) {
      await DeviceApi.deviceInformationUpdate(formData.value)
      message.success(t('common.updateSuccess'))
      dialogVisible.value = false
      emit('success')
    } else {
      await DeviceApi.deviceInformationCreate(formData.value)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      emit('success')
    }
  } finally {
    formLoading.value = false
  }
}
// 设备类型切换
const deviceTypeChange = async (e) => {
  DeviceApi.getMapDeviceImageUrl({
    deviceType: e
  }).then((res) => {
    formData.value.mapImageUrl = res ? res : undefined
  })
  if (e === 9) {
    formData.value.cameraType = '1'
  } else {
    formData.value.cameraType = undefined
  }

  // 当设备类型为翻转机(10)时，获取点位列表
  if (e === 10) {
    await getTakePointList()
    await getCheckPointList()
    // 重置点位选择
    formData.value.takePointId = undefined
    formData.value.checkPointIds = []
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    deviceType: undefined, //设备类型
    deviceNo: undefined, //车辆编号
    macAddress: undefined, //mac地址
    mapImageUrl: undefined, //设备在地图上图标
    pictureConfig: undefined, //	图片设置（1：默认图片、2：上传图片、 3：不显示图片）
    url: undefined, //上传图片附件
    deviceAttribute: undefined,
    deviceEnable: undefined, //设备启用禁用 设备启用禁用（0：禁用、1：启用）
    devicePort: undefined, //端口
    deviceIp: undefined, //设备IP
    cameraType: undefined, //摄像头类型
    deviceLocation: undefined, //设备位置
    cameraCode: undefined, //摄像头编号
    takePointId: undefined, //取放货点位
    checkPointIds: [] //检测区点位
  }

  formRef.value?.resetFields()
}
</script>

<style 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;
  width: 30px;
  height: 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>
