<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading">
      <el-form-item label="所属队伍" prop="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          :check-strictly="false"
          node-key="id"
          filterable
          placeholder="请选择所在部门" />
      </el-form-item>
      <el-form-item label="日期" prop="jsaTime">
        <el-date-picker
          v-model="formData.jsaTime"
          type="date"
          value-format="x"
          placeholder="选择日期"
          style="width: 100%" />
      </el-form-item>

      <el-form-item label="序号" prop="jsaXh">
        <el-input v-model="formData.jsaXh" placeholder="请输入序号" />
      </el-form-item>

      <el-form-item label="工作任务" prop="jobTask">
        <el-input v-model="formData.jobTask" placeholder="请输入工作任务" />
      </el-form-item>

      <el-form-item label="工作地点" prop="jobAddress">
        <el-input v-model="formData.jobAddress" placeholder="请输入工作地点" />
      </el-form-item>

      <el-form-item label="工作负责人" prop="jobDuty">
        <el-input v-model="formData.jobDuty" placeholder="请输入工作负责人" />
      </el-form-item>

      <el-form-item label="附件" prop="jsaFile">
        <UploadFile
          v-model="formData.jsaFile"
          :file-type="['doc', 'docx', 'pdf', 'jpg', 'png', 'jpeg', 'bmp']"
          :limit="3"
          :file-size="100"
          class="min-w-80px" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { QHSEJsaApi } from '@/api/pms/qhse/index'
import { handleTree, defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { useUserStore } from '@/store/modules/user'
/** SOC卡汇总 表单 */
defineOptions({ name: 'IotSocSummaryForm' })

const userStore = useUserStore()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList2 = ref<Tree[]>([]) // 树形结构
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  jsaTime: undefined,
  jsaXh: undefined,
  jobTask: undefined,
  jobAddress: undefined,
  jobDuty: undefined,
  jsaFile: [] as any[],
  remark: undefined,
  deptId: undefined,
  deptName: undefined
})
const formRules = reactive({
  jsaTime: [{ required: true, message: '请选择日期', trigger: 'blur' }],
  jsaXh: [{ required: true, message: '请输入序号', trigger: 'blur' }],
  jobTask: [{ required: true, message: '请输入工作任务', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择所属队伍', trigger: 'blur' }],

  jsaFile: [{ required: true, message: '请上传附件', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  resetForm()
  formData.value.deptId = userStore.getUser.deptId

  console.log('id>>>>>>>>>>>>>', formData.value)
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await QHSEJsaApi.getJsa(id)
      formData.value = {
        ...data,
        jsaFile: Array.isArray(data.jsaFile)
          ? data.jsaFile
          : data.jsaFile
            ? String(data.jsaFile).split(',').filter(Boolean)
            : []
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value }
    data.jsaFile = Array.isArray(data.jsaFile) ? data.jsaFile.join(',') : data.jsaFile || ''
    if (formType.value === 'create') {
      data.deptId = userStore.getUser.deptId
      await QHSEJsaApi.createJsa(data)
      message.success(t('common.createSuccess'))
    } else {
      await QHSEJsaApi.updateJsa(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    jsaTime: undefined,
    jsaXh: undefined,
    jobTask: undefined,
    jobAddress: undefined,
    jobDuty: undefined,
    jsaFile: [],
    remark: undefined,
    deptId: undefined,
    deptName: undefined
  }
  formRef.value?.resetFields()
}

onMounted(async () => {
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>
