<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('EquipmentManagement.TaskManagement.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.taskType')" prop="taskType">
        <el-select
          v-model="queryParams.taskType"
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderTaskType')"
          clearable
          class="!w-240px"
        >
          <el-option v-for="opt in taskTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.TaskManagement.projectForm')" prop="projectForm">
        <el-select
          v-model="queryParams.projectForm"
          multiple
          filterable
          clearable
          :placeholder="t('EquipmentManagement.TaskManagement.placeholderProjectForm')"
          class="!w-240px"
        >
          <el-option v-for="item in planOptions" :key="String(item.id)" :label="item.planName" :value="String(item.id)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('common.query') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('common.reset') }}</el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mes:task-management:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:task-management:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column :label="t('EquipmentManagement.TaskManagement.index')" type="index" align="center" width="70" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.name')" align="center" prop="name" min-width="140" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.taskType')" align="center" prop="taskType" width="90">
        <template #default="scope">
          <el-tag v-if="scope.row.taskType === 1" type="primary">{{ t('EquipmentManagement.TaskManagement.taskTypeInspect') }}</el-tag>
          <el-tag v-else-if="scope.row.taskType === 2" type="success">{{ t('EquipmentManagement.TaskManagement.taskTypeMaintain') }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.TaskManagement.projectForm')" align="center" prop="projectFormName" min-width="140" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.startDate')" align="center" prop="startDate" :formatter="dateFormatter2" width="120" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.endDate')" align="center" prop="endDate" :formatter="dateFormatter2" width="120" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.cronExpression')" align="center" prop="cronExpression" min-width="180" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.enabled')" align="center" prop="enabled" width="90">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.enabled" />
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.TaskManagement.creatorName')" align="center" prop="creatorName" width="120" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
      <el-table-column :label="t('EquipmentManagement.TaskManagement.updateTime')" align="center" prop="updateTime" :formatter="dateFormatter" width="180" />
      <el-table-column
        :label="t('EquipmentManagement.TaskManagement.operate')"
        fixed="right"
        align="center"
        min-width="230"
      >
        <template #default="scope">
          <el-button
            link
            type="success"
            @click="handleCreateTicket(scope.row.id)"
            :loading="ticketLoadingId === scope.row.id"
          >
            {{ t('EquipmentManagement.TaskManagement.createWorkOrder') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
            v-hasPermi="['mes:task-management:update']"
          >{{ t('action.update') }}</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:task-management:delete']">
            {{ t('action.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <TaskConfigurationForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { TaskManagementApi, TaskManagementVO } from '@/api/mold/taskManagement'
import { PlanMaintenanceApi } from '@/api/mold/planmaintenance'
import TaskConfigurationForm from './TaskConfigurationForm.vue'

defineOptions({ name: 'MoldTaskConfiguration' })

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

const taskTypeOptions = [
  { label: t('EquipmentManagement.TaskManagement.taskTypeInspect'), value: 1 },
  { label: t('EquipmentManagement.TaskManagement.taskTypeMaintain'), value: 2 }
]

const loading = ref(true)
const list = ref<TaskManagementVO[]>([])
const total = ref(0)
const exportLoading = ref(false)
const selectedIds = ref<number[]>([])

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

const planOptions = ref<PlanOption[]>([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined as string | undefined,
  taskType: undefined as number | undefined,
  projectForm: [] as string[]
})
const queryFormRef = ref()

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 ensurePlanOptionsLoaded = async () => {
  const planRes = await PlanMaintenanceApi.getPlanMaintenancePage({ pageNo: 1, pageSize: 100 })
  planOptions.value = (planRes?.list ?? []) as PlanOption[]
}

const buildQueryParams = () => {
  return {
    ...queryParams,
    projectForm: toCommaSeparatedIds(queryParams.projectForm)
  }
}

const getList = async () => {
  loading.value = true
  try {
    const data = await TaskManagementApi.getTaskManagementPage(buildQueryParams())
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleSelectionChange = (rows: TaskManagementVO[]) => {
  selectedIds.value = rows
    .map((r) => r.id)
    .filter((id): id is number => typeof id === 'number')
}

const formRef = ref()
const openForm = (type: string, row?: TaskManagementVO) => {
  formRef.value.open(type, row)
}

const handleDelete = async (id?: number) => {
  if (!id) return
  try {
    await message.delConfirm()
    await TaskManagementApi.deleteTaskManagement(String(id))
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const ticketLoadingId = ref<number | undefined>(undefined)
const handleCreateTicket = async (id?: number) => {
  if (!id) return
  ticketLoadingId.value = id
  try {
    await TaskManagementApi.createTaskManagementTicket(id)
    message.success(t('EquipmentManagement.TaskManagement.createTicketSuccess'))
  } catch {
    message.error(t('EquipmentManagement.TaskManagement.createTicketFail'))
  } finally {
    ticketLoadingId.value = undefined
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params: Record<string, any> = buildQueryParams()
    if (selectedIds.value.length > 0) {
      params.ids = selectedIds.value.join(',')
    }
    const data = await TaskManagementApi.exportTaskManagement(params)
    download.excel(data, t('EquipmentManagement.TaskManagement.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

onMounted(async () => {
  try {
    await ensurePlanOptionsLoaded()
  } finally {
    getList()
  }
})
</script>
