<template>
  <n-button type="primary" @click="showAddModal">添加数据</n-button>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    title="添加">
    <n-form :model="formValue" label-width="auto" show-require-mark>
      <n-form-item label="测点" path="T_id">
        <n-select
          v-model:value="formValue.T_id"
          label-field="T_id"
          value-field="T_id"
          @update:value="handleUpdateValue"
          :options="classList"
        />
      </n-form-item>
      <n-form-item label="温度" path="T_t">
        <n-input v-model:value="formValue.T_t">
          <template #suffix> ℃ </template>
        </n-input>
      </n-form-item>
      <n-form-item label="湿度" path="T_rh">
        <n-input v-model:value="formValue.T_rh">
          <template #suffix> % </template>
        </n-input>
      </n-form-item>
      <n-form-item label="时间" path="T_time">
        <n-date-picker
          v-model:formatted-value="formValue.T_time"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          clearable
          class="w-full"
        />
      </n-form-item>
      <n-form-item>
        <n-button type="primary" style="margin-right: 20px;" @click="addTask">
          立即提交
        </n-button>
        <n-button @click="showModal = false">取消</n-button>
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup>
import { addTaskData } from '@/api';

// const emit = defineEmits(["submit"]);

const props = defineProps({
  task: {
    required: true,
    default: {},
  },
  classList: {
    required: true,
    default: [],
  },
});

const message = useMessage();

// 是否展示 Modal
const showModal = ref(false);

// 表单数据
const formValue = reactive({
  T_sn: null,
  T_id: null,
  T_t: null,
  T_rh: null,
  T_time: null,
});

// 值更新时执行的回调
const handleUpdateValue = (value, option) => {
  console.log('handleUpdateValue',option)
  formValue.T_id = option.T_id;
  formValue.T_sn = option.T_sn;
};

// 显示添加
const showAddModal = () => {
  showModal.value = true;
  Object.keys(formValue).forEach((key) => (formValue[key] = null));
};

// 获取设备列表
const addTask = async () => { 
  const sto = await inspect(formValue)
  console.log('999',formValue)
  if(sto){
    Object.keys(formValue).forEach((key) => (formValue[key] += ''));
    const { data: res } = await addTaskData({
      T_task_id: props.task.T_task_id,
      ...formValue,
    });
    if (res.Code === 200) {
      showModal.value = false
      message.success(res.Msg);
    }
  }else{
    message.error('所有选项都为必填哦')
    return
  }
};
const inspect = (value)=>{
  return new Promise(resolve=>{
    const j = Object.keys(value).every(key=>{
      return value[key] != null
    })
    resolve(j)
  })
 
} 
</script>

<style lang="scss" scoped></style>
