<template>
  <el-dialog :title="'处理预警'" v-model="dialogVisible" width="500px" append-to-body>
    <el-form ref="handleFormRef" :model="handleForm" :rules="rules" label-width="80px">
      <el-form-item label="处理结果" prop="handleResult">
        <el-input
          v-model="handleForm.handleResult"
          type="textarea"
          placeholder="请输入处理结果"
          rows="4"
        />
      </el-form-item>
      <el-form-item label="处理时间" prop="handleTime">
        <el-date-picker
          v-model="handleForm.handleTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择处理时间"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="HandleAlert">
import { ref, reactive, toRefs, onMounted, watch } from 'vue'
import { updateWmsAlertRecord } from "@/api/ware/wmsAlertRecord"
import useUserStore from "@/store/modules/user"

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  recordInfo: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'handle-success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const { proxy } = getCurrentInstance()

const handleFormRef = ref(null)

const userStore = useUserStore()

const data = reactive({
  handleForm: {
    recordId: null,
    handlerId: userStore.id,
    handleResult: '',
    handleTime: '',
    alertStatus: '1'
  },
  rules: {
    handleResult: [
      { required: true, message: '处理结果不能为空', trigger: 'blur' }
    ],
    handleTime: [
      { required: true, message: '处理时间不能为空', trigger: 'change' }
    ]
  }
})

const { handleForm, rules } = toRefs(data)

onMounted(() => {
  if (props.recordInfo) {
    handleForm.value.recordId = props.recordInfo.recordId
  }
})

function cancel() {
  emit('update:visible', false)
  resetForm()
}

function resetForm() {
  handleForm.value = {
    recordId: props.recordInfo.recordId || null,
    handlerId: userStore.id,
    handleResult: '',
    handleTime: '',
    alertStatus: '1'
  }
  if (handleFormRef.value) {
    handleFormRef.value.resetFields()
  }
}

function submitForm() {
  handleFormRef.value.validate((valid) => {
    if (valid) {
      updateWmsAlertRecord(handleForm.value).then(() => {
        proxy.$modal.msgSuccess('处理成功')
        emit('handle-success')
        emit('update:visible', false)
      })
    }
  })
}

// 监听recordInfo变化，更新表单
watch(() => props.recordInfo, (newVal) => {
  if (newVal) {
    handleForm.value.recordId = newVal.recordId
  }
}, { deep: true })
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>