<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('EquipmentManagement.TaskManagement.name')" prop="name">
        <el-input
          v-model="formData.name"
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderName')"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.taskType')" prop="taskType">
        <el-radio-group v-model="formData.taskType">
          <el-radio :label="1">{{ t('EquipmentManagement.TaskManagement.taskTypeInspect') }}</el-radio>
          <el-radio :label="2">{{ t('EquipmentManagement.TaskManagement.taskTypeMaintain') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.deviceList')" prop="deviceList">
        <el-select
          v-model="formData.deviceList"
          multiple
          filterable
          clearable
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderDeviceList')"
          class="!w-full"
        >
          <el-option v-for="item in deviceOptions" :key="String(item.id)" :label="item.deviceName" :value="String(item.id)" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.projectForm')" prop="projectForm">
        <el-select
          v-model="formData.projectForm"
          filterable
          clearable
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderProjectForm')"
          class="!w-full"
        >
          <el-option v-for="item in planOptions" :key="String(item.id)" :label="item.planName" :value="Number(item.id)" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.dateRange')" prop="dateRange">
        <el-date-picker
          v-model="formData.dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          :start-placeholder="t('EquipmentManagement.TaskManagement.placeholderStartDate')"
          :end-placeholder="t('EquipmentManagement.TaskManagement.placeholderEndDate')"
          class="!w-320px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.cronExpression')" prop="cronExpression">
        <crontab v-model="formData.cronExpression" />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.operableUsers')" prop="operableUsers">
        <el-select
          v-model="formData.operableUsers"
          multiple
          filterable
          clearable
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderOperableUsers')"
          class="!w-full"
        >
          <el-option v-for="item in users" :key="String(item.id)" :label="item.nickname" :value="String(item.id)" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getBoolDictOptions } from '@/utils/dict'
import { TaskManagementApi, TaskManagementVO } from '@/api/mes/taskManagement'
import { DeviceLedgerApi } from '@/api/mes/deviceledger'
import { PlanMaintenanceApi } from '@/api/mes/planmaintenance'
import { getSimpleUserList, UserVO } from '@/api/system/user'

defineOptions({ name: 'TaskManagementForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()

type DeviceOption = {
  id: number | string
  deviceName: string
}

type PlanOption = {
  id: number | string
  planName: string
}

const deviceOptions = ref<DeviceOption[]>([])
const planOptions = ref<PlanOption[]>([])
const users = ref<UserVO[]>([])

const parseIdsValue = (value: any): string[] => {
  if (!value) return []
  if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter(Boolean)
  return String(value)
    .split(',')
    .map((v) => v.trim())
    .filter(Boolean)
}

const toCommaSeparatedIds = (value: any): string | undefined => {
  const ids = parseIdsValue(value)
  return ids.length ? ids.join(',') : undefined
}

const ensureOptionsLoaded = async () => {
  const [deviceRes, planRes, userRes] = await Promise.all([
    DeviceLedgerApi.getDeviceLedgerList({}),
    PlanMaintenanceApi.getPlanMaintenancePage({ pageNo: 1, pageSize: 100 }),
    getSimpleUserList()
  ])
  deviceOptions.value = (Array.isArray(deviceRes) ? deviceRes : deviceRes?.list ?? deviceRes?.data ?? []) as DeviceOption[]
  planOptions.value = (planRes?.list ?? []) as PlanOption[]
  users.value = userRes ?? []
}

const formData = ref({
  id: undefined as number | undefined,
  name: undefined as string | undefined,
  taskType: undefined as number | undefined,
  deviceList: [] as string[],
  projectForm: undefined as number | undefined,
  dateRange: [] as string[],
  cronExpression: undefined as string | undefined,
  operableUsers: [] as string[],
  enabled: false as boolean
})

const formRules = reactive({
  name: [
    { required: true, message: t('EquipmentManagement.TaskManagement.placeholderName'), trigger: 'blur' }
  ],
  taskType: [
    { required: true, message: t('EquipmentManagement.TaskManagement.placeholderTaskType'), trigger: 'change' }
  ],
  enabled: [
    { required: true, message: t('EquipmentManagement.TaskManagement.placeholderEnabled'), trigger: 'change' }
  ],
  deviceList: [
    { required: true, message: t('EquipmentManagement.TaskManagement.placeholderDeviceList'), trigger: 'change' }
  ],
  projectForm: [
    { required: true, message: t('EquipmentManagement.TaskManagement.placeholderProjectForm'), trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: t('EquipmentManagement.TaskManagement.placeholderDateRange'), trigger: 'change' }
  ]
})

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    taskType: undefined,
    deviceList: [],
    projectForm: undefined,
    dateRange: [],
    cronExpression: undefined,
    operableUsers: [],
    enabled: false
  }
  formRef.value?.resetFields()
}

const open = async (type: string, row?: TaskManagementVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await ensureOptionsLoaded()

  if (type === 'update' && row) {
    formData.value.id = row.id
    formData.value.name = row.name
    formData.value.taskType = row.taskType
    formData.value.deviceList = parseIdsValue((row as any).deviceList)
    const projectFormIds = parseIdsValue((row as any).projectForm)
    if (projectFormIds.length) {
      const n = Number(projectFormIds[0])
      formData.value.projectForm = Number.isFinite(n) ? n : undefined
    } else {
      const projectFormNames = parseIdsValue((row as any).projectFormName)
      const mapped = projectFormNames
        .map((name) => planOptions.value.find((p) => p.planName === name)?.id)
        .filter((id) => id !== undefined && id !== null)
        .map((id) => Number(id))
      const firstId = mapped[0]
      formData.value.projectForm = typeof firstId === 'number' && Number.isFinite(firstId) ? firstId : undefined
    }
    formData.value.dateRange = [row.startDate, row.endDate].filter(Boolean) as string[]
    formData.value.cronExpression = row.cronExpression
    formData.value.operableUsers = parseIdsValue((row as any).operableUsers)
    if (typeof row.enabled === 'boolean') {
      formData.value.enabled = row.enabled
    } else if (row.enabled === 'true' || row.enabled === 'false') {
      formData.value.enabled = row.enabled === 'true'
    } else {
      formData.value.enabled = true
    }
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const [startDate, endDate] = Array.isArray(formData.value.dateRange) ? formData.value.dateRange : []
    const payload: TaskManagementVO = {
      id: formData.value.id,
      name: formData.value.name,
      taskType: formData.value.taskType,
      deviceList: toCommaSeparatedIds((formData.value as any).deviceList),
      projectForm: formData.value.projectForm,
      startDate: startDate || undefined,
      endDate: endDate || undefined,
      cronExpression: formData.value.cronExpression,
      operableUsers: toCommaSeparatedIds((formData.value as any).operableUsers),
      enabled: formData.value.enabled
    }

    if (formType.value === 'create') {
      await TaskManagementApi.createTaskManagement(payload)
      message.success(t('common.createSuccess'))
    } else {
      await TaskManagementApi.updateTaskManagement(payload)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
