<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="formData.planName" placeholder="请输入计划名称" />
      </el-form-item>
      <el-form-item label="所属区域" prop="workstationId">
        <el-tree-select
          v-model="formData.workstationId"
          :data="workstationOptions"
          check-strictly
          :render-after-expand="false"
          :props="{ label: 'workstationName', value: 'id' }"
          placeholder="请选择所属区域"
        />
      </el-form-item>
      <el-form-item label="物资柜" prop="cabinetIds">
        <el-select
          v-model="formData.cabinetIds"
          :disabled="visibleSelect"
          placeholder="请选择需要检查的物资柜"
          multiple
          clearable
        >
          <el-option
            v-for="dict in cabinets"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划日期" prop="planDate">
        <el-date-picker
          v-model="formData.planDate"
          type="date"
          placeholder="请选择日期"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item label="检察员" prop="checkUserId">
        <el-select
          v-model="formData.checkUserId"
          placeholder="请选择检察员"
          clearable
        >
          <el-option
            v-for="dict in planPersonOption"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as PlanApi from '@/api/material/plan'
import * as CabinetApi from '@/api/material/information/index'
import * as MarsDeptApi from '@/api/system/marsdept'
import * as UserApi from '@/api/system/user'
import { handleTree } from '@/utils/tree'
defineOptions({ name: 'PlanForm' })

const props = defineProps({
  cabinetId: {
    type: String,
    required: false
  }
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 表单数据
const formData = ref({
  planId: undefined,
  planName: '',
  cabinetIds: [],
  workstationId: undefined,
  planDate: undefined,
  checkUserId: undefined
})

// 表单校验
const formRules = reactive({
  planDate: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
  planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
  checkUserId: [{ required: true, message: '检察员不能为空', trigger: 'blur' }],
  cabinetIds: [{ required: true, message: '物资柜不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
const cabinets = ref([]) // 物资柜数据
const planPersonOption = ref([]) // 检察员选项
const workstationOptions = ref([]) // 所属区域选项
const visibleSelect = ref(false) // 是否显示物资柜选择

/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (row) {
    formLoading.value = true
    try {
      const data = await PlanApi.getPlanInfo(row.id)
      formData.value = data
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.workstationId = null
    if (visibleSelect.value) {
      formData.value.cabinetIds = [props.cabinetId]
    }
    formData.value.planName = `物资检查计划${formatDate(new Date())}`
  }
}
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 {
    const data = { ...formData.value }
    data.planDate = formatDate(data.planDate)
    if (formType.value === 'create') {
      await PlanApi.addPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlanApi.updatePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    planId: undefined,
    planName: '',
    cabinetIds: [],
    workstationId: undefined,
    planDate: undefined,
    checkUserId: undefined
  }
  formRef.value?.resetFields()
}

/** 格式化日期 */
const formatDate = (date: Date) => {
  if (!date) return ''
  const d = new Date(date)
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const year = d.getFullYear()
  return `${year}-${month}-${day}`
}

/** 禁用日期 */
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}
/** 获取检察员列表  */
const getCheckUsers = async () => {
  const data = await UserApi.getRoleUser('check')
  planPersonOption.value = data.map((item) => ({
    label: item.nickname,
    value: item.id
  }))
}
// 岗位下拉
const getOtherList = async () => {
  try {
    const data = await MarsDeptApi.listMarsDept({ pageNo: 1, pageSize: -1 })
    if (data && data.list) {
      workstationOptions.value = handleTree(data.list, 'id', 'parentId')
    } else {
      workstationOptions.value = []
    }
  } catch (error) {
    console.error('获取区域数据失败:', error)
    workstationOptions.value = []
  }
}

onMounted(() => {
  getOtherList()
  getCheckUsers()
})
/** 监听所属区域变更 */
watch(
  () => formData.value.workstationId,
  async (newVal) => {
    if (newVal) {
      const data = await CabinetApi.getMaterialsCabinets({
        pageNo: 1,
        pageSize: -1,
        workstationId: newVal
      })
      if (data?.list) {
        // formData.value.cabinetIds = data.list.map((item) => item.id)
        cabinets.value = data.list.map((item) => ({
          value: item.id,
          label: item.cabinetName
        }))
      }
    }
  }
)
</script>
