<!-- 新增参试任务 -->
<script lang="ts" setup name="SystemUserAddDialog">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { addTask, delTask, getTaskList, updateTask } from '@/api/eqpt/device/task'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
const emits = defineEmits(['resetData'])
const ruleFormRef = ref<FormInstance>()
const dialogFormVisible = ref<boolean>(false)// 对话框是否显示
const dialogStatus = ref<string>('')// 对话框类型：create,update
const userStore = useUserStore()
const userForm = ref({
  endTime: '',
  startTime: '',
  taskName: '',
  remark: '',
  createDeptId: '',
  createTime: '',
  createUserId: '',
})// 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
}// 表头显示标题

const rules: FormRules = reactive({
  taskName: [{ required: true, message: '任务名称必填', trigger: ['blur', 'change'] }],
  startTime: [{ required: true, message: '开始时间必选', trigger: ['blur', 'change'] }],
  endTime: [{ required: true, message: '结束时间必选', trigger: ['blur', 'change'] }],
})// 前端校验规则

// 重置表单
const resetForm1 = () => {
  userForm.value.endTime = ''
  userForm.value.startTime = ''
  userForm.value.taskName = ''
  userForm.value.remark = ''
  userForm.value.createDeptId = ''
  userForm.value.createTime = ''
  userForm.value.createUserId = ''
}
// 新增数据
const createData = () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      const data = {
        ...userForm.value,
        startTime: `${userForm.value.startTime} 00:00:00`,
        endTime: `${userForm.value.endTime} 23:59:59`,
      }
      addTask(data).then((response) => {
        ElMessage.success('添加成功')
        dialogFormVisible.value = false
        emits('resetData')
      })
    }
  })
}
// 修改数据
const updateData = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      updateTask(userForm.value).then((response) => {
        ElMessage.success('修改成功')
        dialogFormVisible.value = false
        emits('resetData')
      })
    }
  })
}

// 保存数据
const saveData = () => {
  if (dialogStatus.value === 'update') {
    updateData()
  }
  else if (dialogStatus.value === 'create') {
    createData()
  }
}

const cancel = () => {
  dialogFormVisible.value = false
  resetForm1()
  ruleFormRef.value?.resetFields()
  emits('resetData')
}
// 初始化对话框
const initDialog = (dialogStatusflag: string, row: any) => {
  dialogStatus.value = dialogStatusflag
  dialogFormVisible.value = true
  if (dialogStatus.value === 'create') { // 如果是新增，清除验证
    resetForm1()
    nextTick(() => {
      ruleFormRef.value?.clearValidate()
    })
    userForm.value.createUserId = userStore.id
    userForm.value.createDeptId = userStore.deptId
    userForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    // getUserDept().then((res) => {
    //   userForm.value.createDeptId = res.data.id
    // })
  }
  else if (dialogStatus.value === 'update') { // 如果是修改，将row中数据填写到输入框中
    userForm.value = JSON.parse(JSON.stringify(row))
  }
}
defineExpose({ initDialog })
</script>

<template>
  <el-dialog v-if="dialogFormVisible" v-model="dialogFormVisible" width="35%" :title="textMap[dialogStatus]" append-to-body>
    <el-form ref="ruleFormRef" :rules="rules" :model="userForm" label-position="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model.trim="userForm.taskName" type="text"
              placeholder="参试任务名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="userForm.startTime"
              type="date"
              placeholder="开始时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="userForm.endTime"
              type="date"
              placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="userForm.remark"
              maxlength="50"
              placeholder="备注"
              show-word-limit
              type="textarea"
              :row="2"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer footer">
      <el-button type="primary" @click="saveData">
        保存
      </el-button>
      <el-button @click="cancel">
        取消
      </el-button>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: flex-end;
}
</style>
