<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="moldList">
        <el-select
          v-model="formData.moldList"
          multiple
          filterable
          clearable
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderDeviceList')"
          class="!w-full"
        >
          <el-option v-for="item in deviceOptions" :key="String(item.id)" :label="item.name" :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"
          multiple
          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="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-item :label="t('EquipmentManagement.TaskManagement.enabled')" prop="enabled">
        <el-radio-group v-model="formData.enabled">
          <el-radio
v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)" :key="String(dict.value)"
            :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </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/mold/taskManagement'
import { MoldBrandApi } from '@/api/erp/mold'
import { PlanMaintenanceApi } from '@/api/mold/planmaintenance'
import { getSimpleUserList, UserVO } from '@/api/system/user'

defineOptions({ name: 'MoldTaskConfigurationForm' })

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
  name: 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([
    MoldBrandApi.getMoldPage({}),
    PlanMaintenanceApi.getPlanMaintenancePage({}),
    getSimpleUserList()
  ])
  deviceOptions.value = (deviceRes?.list ?? []) 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,
  moldList: [] as string[],
  projectForm: [] as string[],
  dateRange: [] as string[],
  cronExpression: undefined as string | undefined,
  operableUsers: [] as string[],
  enabled: true 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' }],
  moldList: [{ 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,
    moldList: [],
    projectForm: [],
    dateRange: [],
    cronExpression: undefined,
    operableUsers: [],
    enabled: true
  }
  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.moldList = parseIdsValue((row as any).moldList)
    const projectFormIds = parseIdsValue((row as any).projectForm)
    if (projectFormIds.length) {
      formData.value.projectForm = projectFormIds
    } else {
      const projectFormNames = parseIdsValue((row as any).projectFormName)
      const mappedIds = projectFormNames
        .map((name) => planOptions.value.find((p) => p.planName === name)?.id)
        .filter((id) => id !== undefined && id !== null)
        .map((id) => String(id))
      formData.value.projectForm = mappedIds
    }
    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,
      moldList: toCommaSeparatedIds((formData.value as any).moldList),
      projectForm: toCommaSeparatedIds((formData.value as any).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>
