<template>
  <ContentWrap>
    <el-form
      class="-mb-15px recipe-library-filter-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item :label="t('RecipeManagement.RecipeLibrary.searchCodeLabel')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('RecipeManagement.RecipeLibrary.searchCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeLibrary.searchNameLabel')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('RecipeManagement.RecipeLibrary.searchNamePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeLibrary.searchRecipeLabel')" prop="recipeId">
        <el-select
          v-model="queryParams.recipeId"
          :placeholder="t('RecipeManagement.RecipeLibrary.searchRecipePlaceholder')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="opt in recipeOptions"
            :key="String(opt.value)"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择来源" clearable class="!w-240px">
          <el-option v-for="opt in sourceOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('RecipeManagement.RecipeLibrary.searchButtonText') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('RecipeManagement.RecipeLibrary.resetButtonText') }}
        </el-button>
        <el-button type="primary" plain @click="openDialog('create')">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('RecipeManagement.RecipeLibrary.createButtonText') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('RecipeManagement.RecipeLibrary.exportButtonText') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      highlight-current-row
      @row-click="handleRowClick"
    >
      <el-table-column
        :label="t('RecipeManagement.RecipeLibrary.tableCodeColumn')"
        align="center"
        prop="code"
        min-width="140"
      />
      <el-table-column
        :label="t('RecipeManagement.RecipeLibrary.tableNameColumn')"
        align="center"
        prop="name"
        min-width="140"
      />
      <el-table-column
        :label="t('RecipeManagement.RecipeLibrary.tableRecipeNameColumn')"
        align="center"
        prop="recipeName"
        min-width="160"
      >
        <template #default="scope">
          <span>{{ scope.row.recipeName ?? '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        :label="t('RecipeManagement.RecipeLibrary.tableCreatorColumn')"
        align="center"
        prop="creator"
        width="120"
      /> -->
      <el-table-column
        :label="t('RecipeManagement.RecipeLibrary.tableCreateTimeColumn')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <!-- <el-table-column label="来源" align="center" prop="source" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.source" :type="getSourceTagType(scope.row.source)">{{ scope.row.source }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column> -->
      <el-table-column
        :label="t('RecipeManagement.RecipeLibrary.tableOperateColumn')"
        align="center"
        width="180"
        fixed="right"
      >
        <template #default="scope">
          <el-button link type="primary" @click.stop="handleRead(scope.row)">
            {{ t('RecipeManagement.RecipeLibrary.tableReadAction') }}
          </el-button>
          <el-button link type="primary" @click.stop="openDialog('update', scope.row)">
            {{ t('RecipeManagement.RecipeLibrary.tableEditAction') }}
          </el-button>
          <el-button link type="danger" @click.stop="handleDelete(scope.row)">
            {{ t('RecipeManagement.RecipeLibrary.tableDeleteAction') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

  <ContentWrap v-if="detailVisible">
    <FormulaLibraryDetailTabs :recipe-id="detailRecipeId" />
  </ContentWrap>

  <FormulaLibraryReadDialog ref="readDialogRef" />

  <Dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="dialogRules"
      class="recipe-library-dialog-form"
      label-width="auto"
      v-loading="dialogLoading"
    >
      <el-form-item :label="t('RecipeManagement.RecipeLibrary.dialogCodeLabel')" prop="code">
        <el-input
          v-model="dialogForm.code"
          :placeholder="t('RecipeManagement.RecipeLibrary.dialogCodePlaceholder')"
          clearable
          :disabled="dialogType == 'update'"
        />
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeLibrary.dialogNameLabel')" prop="name">
        <el-input
          v-model="dialogForm.name"
          :placeholder="t('RecipeManagement.RecipeLibrary.dialogNamePlaceholder')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="t('RecipeManagement.RecipeLibrary.dialogRecipeLabel')" prop="recipeId">
        <el-select
          v-model="dialogForm.recipeId"
          :placeholder="t('RecipeManagement.RecipeLibrary.dialogRecipePlaceholder')"
          clearable
          filterable
          class="!w-full"
          :disabled="dialogType == 'update'"
        >
          <el-option v-for="opt in recipeOptions" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item :label="t('RecipeManagement.RecipeLibrary.dialogSourceLabel')" prop="source">
        <el-select
          v-model="dialogForm.source"
          :placeholder="t('RecipeManagement.RecipeLibrary.dialogSourcePlaceholder')"
          clearable
          class="!w-full"
        >
          <el-option
            v-for="opt in sourceOptions"
            :key="opt.value"
            :label="getSourceLabel(opt.value)"
            :value="opt.value"
          />
        </el-select>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">
        {{ t('RecipeManagement.RecipeLibrary.dialogCancelButton') }}
      </el-button>
      <el-button type="primary" @click="submitDialog" :disabled="dialogLoading">
        {{ t('RecipeManagement.RecipeLibrary.dialogSaveButton') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { dateFormatter } from '@/utils/formatTime'
import { RecipePlanDetailApi, RecipePlanDetailVO } from '@/api/iot/recipePlanDetail'
import { RecipeConfigApi } from '@/api/iot/recipeConfig'
import { RecipePointApi } from '@/api/iot/recipePoint'
import FormulaLibraryDetailTabs from './components/FormulaLibraryDetailTabs.vue'
import FormulaLibraryReadDialog from './components/FormulaLibraryReadDialog.vue'
import { RecipeDeviceRecordApi } from '@/api/iot/recipeDeviceRecord'
import { RecipePointRecordApi } from '@/api/iot/recipepointrecord'

type SelectOption<T = any> = { label: string; value: T }

defineOptions({ name: 'FormulaLibrary' })

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

const loading = ref(false)
const exportLoading = ref(false)
const queryFormRef = ref()

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: '' as string,
  name: '' as string,
  recipeId: undefined as string | number | undefined,
  source: undefined as string | undefined
})

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

const detailVisible = ref(false)
const detailRecipeId = ref<string | number | undefined>(undefined)

const sourceOptions: SelectOption<string>[] = [
  { label: '新增', value: '新增' },
  { label: '生产中', value: '生产中' }
]

const recipeOptions = ref<SelectOption[]>([])

const ensureOptionsLoaded = async () => {
	const recipeRes = await RecipeConfigApi.getRecipeConfigPage({})
  recipeOptions.value = (recipeRes?.list ?? []).map((item: any) => {
    const label = item.name ? `${item.recipeCode ?? ''}${item.recipeCode ? '-' : ''}${item.name}` : String(item.id)
    return { label, value: item.id }
  })
}

const buildQueryParams = () => {
  const code = queryParams.code?.trim()
  const name = queryParams.name?.trim()
  return {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    code: code ? code : undefined,
    name: name ? name : undefined,
		recipeId: queryParams.recipeId ? String(queryParams.recipeId) : undefined,
    source: queryParams.source ? queryParams.source : undefined
  }
}

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

const handleRowClick = (row: RecipePlanDetailVO) => {
  if (!row) return
  detailRecipeId.value = row.recipeId
  detailVisible.value = true
}

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

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

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await RecipePlanDetailApi.exportRecipePlanDetail(buildQueryParams())
    download.excel(data, t('RecipeManagement.RecipeLibrary.exportFileName'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleDelete = async (row: RecipePlanDetailVO) => {
  if (!row?.id) return
  try {
    await message.delConfirm()
    await RecipePlanDetailApi.deleteRecipePlanDetail(row.id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {
  }
}

const getSourceTagType = (source: string) => {
  if (source === '新增') return 'success'
  if (source === '生产中') return 'warning'
  return 'info'
}

const getSourceLabel = (value: string) => {
  if (value === '新增') return t('RecipeManagement.RecipeLibrary.sourceOptionNewLabel')
  if (value === '生产中') return t('RecipeManagement.RecipeLibrary.sourceOptionProducingLabel')
  return value
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogLoading = ref(false)
const dialogFormRef = ref()
const dialogType = ref<'create' | 'update'>('create')

const dialogForm = ref<RecipePlanDetailVO>({
	id: undefined,
	code: '',
	name: '',
	recipeId: undefined,
	source: undefined,
	isEnable: undefined
})

const dialogRules = reactive({
	code: [
		{ required: true, message: t('RecipeManagement.RecipeLibrary.validatorCodeRequired'), trigger: 'blur' }
	],
	name: [
		{ required: true, message: t('RecipeManagement.RecipeLibrary.validatorNameRequired'), trigger: 'blur' }
	],
	recipeId: [
		{ required: true, message: t('RecipeManagement.RecipeLibrary.validatorRecipeRequired'), trigger: 'change' }
	]
})

const resetDialogForm = () => {
  dialogForm.value = {
    id: undefined,
    code: '',
    name: '',
		recipeId: undefined,
		source: undefined
  }
  dialogFormRef.value?.resetFields?.()
}

const openDialog = async (type: 'create' | 'update', row?: RecipePlanDetailVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  dialogType.value = type
  resetDialogForm()
  await ensureOptionsLoaded()
  if (type === 'update' && row) {
    dialogForm.value = {
      id: row.id,
      code: row.code,
      name: row.name,
			recipeId: row.recipeId ?? (row as any).recipeId,
      source: row.source
    }
  }
}

const readDialogRef = ref<InstanceType<typeof FormulaLibraryReadDialog>>()

const checkRecipeRecords = async (recipeId: string | number) => {
  const params = {
    pageNo: 1,
    pageSize: 1,
    recipeId: String(recipeId)
  }
  try {
    const [devicePage, manualPage] = await Promise.all([
      RecipeDeviceRecordApi.getRecipeDeviceRecordPage(params),
      RecipePointRecordApi.getRecipePointRecordPage(params)
    ])
    const deviceTotal = Number((devicePage as any)?.total ?? 0)
    const manualTotal = Number((manualPage as any)?.total ?? 0)
    return {
      hasDeviceRecords: deviceTotal > 0,
      hasManualRecords: manualTotal > 0
    }
  } catch {
    return {
      hasDeviceRecords: false,
      hasManualRecords: false
    }
  }
}

const handleRead = async (row: RecipePlanDetailVO) => {
  const recipeId = row?.recipeId
  const id = row?.id
  if (!recipeId) return
  const recipeName = row?.recipeName
  const { hasDeviceRecords, hasManualRecords } = await checkRecipeRecords(recipeId)
  const data = await RecipePointApi.getRecipePointList(Number(recipeId))
  if (!data?.length) {
    await message.confirm(t('RecipeManagement.RecipeLibrary.readDeviceConfirmMessage'))
    if (id != null) {
      await RecipeDeviceRecordApi.createRecipeDeviceRecordBatch(id)
    message.success(t('common.createSuccess'))
    return
    }
  }
  await readDialogRef.value?.open({
    recipeId,
    recipeName,
    data,
    id,
    hasExistingRecords: hasDeviceRecords || hasManualRecords
  })
}

const submitDialog = async () => {
  await dialogFormRef.value.validate()
  dialogLoading.value = true
  try {
    const payload: Partial<RecipePlanDetailVO> = {
      id: dialogForm.value.id,
      code: dialogForm.value.code,
      name: dialogForm.value.name,
			recipeId: dialogForm.value.recipeId,
      source: dialogForm.value.source
    }
    if (dialogType.value === 'create') {
      await RecipePlanDetailApi.createRecipePlanDetail(payload)
      message.success(t('common.createSuccess'))
    } else {
      await RecipePlanDetailApi.updateRecipePlanDetail(payload)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    await getList()
  } finally {
    dialogLoading.value = false
  }
}

onMounted(async () => {
	await ensureOptionsLoaded()
	await getList()
})
</script>

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

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