<template>
  <ContentWrap>
    <el-form
      class="-mb-15px recipe-type-filter-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item :label="t('RecipeManagement.RecipeType.searchNameLabel')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('RecipeManagement.RecipeType.searchNamePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeType.searchProcessLabel')" prop="process">
        <el-select
          v-model="queryParams.process"
          :placeholder="t('RecipeManagement.RecipeType.searchProcessPlaceholder')"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="option in processOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('RecipeManagement.RecipeType.searchButtonText') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('RecipeManagement.RecipeType.resetButtonText') }}
        </el-button>
        <el-button type="primary" plain @click="openDialog('create')">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('RecipeManagement.RecipeType.createButtonText') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('RecipeManagement.RecipeType.exportButtonText') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" reserve-selection /> -->
      <el-table-column
        :label="t('RecipeManagement.RecipeType.tableNameColumn')"
        align="center"
        prop="name"
      />
      <el-table-column
        :label="t('RecipeManagement.RecipeType.tableProcessColumn')"
        align="center"
        prop="process"
      >
        <template #default="scope">
          {{ getProcessLabel(scope.row.process) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('RecipeManagement.RecipeType.tableRemarkColumn')"
        align="center"
        prop="remark"
      />
      <el-table-column
        :label="t('RecipeManagement.RecipeType.tableOperateColumn')"
        align="center"
        width="160px"
        fixed="right"
      >
        <template #default="scope">
          <el-button link type="primary" @click="openDialog('update', scope.row)">
            {{ t('RecipeManagement.RecipeType.tableEditAction') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">
            {{ t('RecipeManagement.RecipeType.tableDeleteAction') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handlePagination"
    />
  </ContentWrap>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="dialogRules"
      class="recipe-type-dialog-form"
      label-width="auto"
      v-loading="dialogLoading"
    >
      <el-form-item :label="t('RecipeManagement.RecipeType.dialogNameLabel')" prop="name">
        <el-input
          v-model="dialogForm.name"
          :placeholder="t('RecipeManagement.RecipeType.dialogNamePlaceholder')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeType.dialogProcessLabel')" prop="process">
        <el-select
          v-model="dialogForm.process"
          :placeholder="t('RecipeManagement.RecipeType.dialogProcessPlaceholder')"
          clearable
          class="!w-full"
        >
          <el-option
            v-for="option in processOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeType.dialogRemarkLabel')" prop="remark">
        <el-input
          v-model="dialogForm.remark"
          :placeholder="t('RecipeManagement.RecipeType.dialogRemarkPlaceholder')"
          clearable
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">
        {{ t('RecipeManagement.RecipeType.dialogCancelButton') }}
      </el-button>
      <el-button type="primary" @click="submitDialog" :disabled="dialogLoading">
        {{ t('RecipeManagement.RecipeType.dialogSaveButton') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import { RecipeApi, RecipeVO } from '@/api/iot/recipe'

type ProcessOption = { label: string; value: string }

/** 配方类型 列表 */
defineOptions({ name: 'FormulaType' })

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

const processOptions = computed<ProcessOption[]>(() => {
  return getStrDictOptions(DICT_TYPE.MES_PROGRESS_TYPE).map((dict) => ({
    label: dict.label,
    value: dict.value
  }))
})

const processLabelMap = computed<Record<string, string>>(() => {
  return processOptions.value.reduce((acc, cur) => {
    acc[cur.value] = cur.label
    return acc
  }, {} as Record<string, string>)
})

const getProcessLabel = (value: string) => {
  return processLabelMap.value[value] ?? value
}

const loading = ref(false)
const tableRef = ref()
const queryFormRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  process: ''
})

const exportLoading = ref(false)

const selectedIds = ref<number[]>([])
const handleSelectionChange = (rows: any[]) => {
  selectedIds.value = rows?.map((row) => row.id).filter((id) => id !== undefined) ?? []
}

const list = ref<RecipeVO[]>([])
const total = ref(0)

const buildQueryParams = () => {
  const name = queryParams.name?.trim()
  return {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    name: name ? name : undefined,
    process: queryParams.process ? queryParams.process : undefined
  }
}

const getList = async () => {
  loading.value = true
  try {
    const data = await RecipeApi.getRecipePage(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 handlePagination = () => {
  getList()
}

const handleExport = async () => {
  if (!selectedIds.value.length) {
    message.error(t('RecipeManagement.RecipeType.exportNoSelectionMessage'))
    return
  }
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await RecipeApi.exportRecipe({ ids: selectedIds.value.join(',') })
    download.excel(data, t('RecipeManagement.RecipeType.exportFileName'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

type DialogMode = 'create' | 'update'

const dialogVisible = ref(false)
const dialogMode = ref<DialogMode>('create')
const dialogTitle = computed(() =>
  dialogMode.value === 'create'
    ? t('RecipeManagement.RecipeType.dialogCreateTitle')
    : t('RecipeManagement.RecipeType.dialogEditTitle')
)
const dialogFormRef = ref()
const dialogLoading = ref(false)
const dialogForm = reactive({
  id: undefined as number | undefined,
  name: '',
  process: '',
  remark: ''
})

const dialogRules = reactive({
  name: [{ required: true, message: t('RecipeManagement.RecipeType.validatorNameRequired'), trigger: 'blur' }],
  process: [
    {
      required: true,
      message: t('RecipeManagement.RecipeType.validatorProcessRequired'),
      trigger: 'change'
    }
  ]
})

const openDialog = (mode: DialogMode, row?: RecipeVO) => {
  dialogMode.value = mode
  dialogVisible.value = true
  nextTick(() => {
    dialogFormRef.value?.clearValidate?.()
  })

  if (mode === 'create') {
    dialogForm.id = undefined
    dialogForm.name = ''
    dialogForm.process = ''
    dialogForm.remark = ''
    return
  }

  dialogForm.id = row?.id
  dialogForm.name = row?.name ?? ''
  dialogForm.process = row?.process ?? ''
  dialogForm.remark = row?.remark ?? ''
}

const submitDialog = async () => {
  if (!dialogFormRef.value) return
  await dialogFormRef.value.validate()
  dialogLoading.value = true
  try {
    const data = {
      id: dialogForm.id,
      name: dialogForm.name,
      process: dialogForm.process,
      remark: dialogForm.remark
    }
    if (dialogMode.value === 'create') {
      await RecipeApi.createRecipe(data)
      message.success(t('common.createSuccess'))
    } else {
      await RecipeApi.updateRecipe(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    await getList()
  } finally {
    dialogLoading.value = false
  }
}

const handleDelete = async (row: RecipeVO) => {
  try {
    await message.delConfirm()
    await RecipeApi.deleteRecipe(row.id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.recipe-type-filter-form :deep(.el-form-item__label) {
  min-width: 68px;
}

.recipe-type-dialog-form :deep(.el-form-item__label) {
  min-width: 100px;
}
</style>
