<template>
  <ContentWrap v-if="visible">
    <el-tabs v-model="activeTab" class="mb-12px">
      <template #extra>
        <el-button link type="info" @click="handleClose">
          {{ t('RecipeManagement.RecipeConfig.detailCollapseButton') }}
        </el-button>
      </template>
      <el-tab-pane
        :label="`${t('RecipeManagement.RecipeConfig.detailTabDetailLabel')}：${recipeCode} - ${name}`"
        name="detail"
      >
        <div class="mb-12px text-left">
          <el-button type="primary" @click="handleConfig">
            {{ t('RecipeManagement.RecipeConfig.detailConfigButton') }}
          </el-button>
        </div>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" row-key="id">
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.detailIndexColumn')"
            align="center"
            width="80"
          >
            <template #default="scope">
              {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.detailPointNameColumn')"
            align="center"
            prop="pointName"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.detailPointTypeColumn')"
            align="center"
            prop="pointType"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.detailDataTypeColumn')"
            align="center"
            prop="dataType"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.detailDataUnitColumn')"
            align="center"
            prop="dataUnit"
          />
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </el-tab-pane>

      <el-tab-pane :label="t('RecipeManagement.RecipeConfig.detailTabManualLabel')" name="manual">
        <div class="mb-12px flex justify-start">
          <el-button type="primary" @click="openManualDialog('create')">
            {{ t('RecipeManagement.RecipeConfig.manualCreateButton') }}
          </el-button>
        </div>
        <el-table
          v-loading="manualLoading"
          :data="manualList"
          :stripe="true"
          :show-overflow-tooltip="true"
          row-key="id"
        >
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.manualTableNameColumn')"
            align="center"
            prop="name"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.manualTableMaxColumn')"
            align="center"
            prop="max"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.manualTableMinColumn')"
            align="center"
            prop="min"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.manualTableDataUnitColumn')"
            align="center"
            prop="dataUnitName"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.manualTableRemarkColumn')"
            align="center"
            prop="remark"
          />
          <el-table-column
            :label="t('RecipeManagement.RecipeConfig.manualTableOperateColumn')"
            align="center"
            width="150px"
            fixed="right"
          >
            <template #default="scope">
              <el-button link type="primary" @click="openManualDialog('update', scope.row)">
                {{ t('RecipeManagement.RecipeConfig.manualTableEditAction') }}
              </el-button>
              <el-button link type="danger" @click="handleManualDelete(scope.row)">
                {{ t('RecipeManagement.RecipeConfig.manualTableDeleteAction') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="manualTotal"
          v-model:page="manualQueryParams.pageNo"
          v-model:limit="manualQueryParams.pageSize"
          @pagination="handleManualPagination"
        />
      </el-tab-pane>
    </el-tabs>

    <Dialog
      :title="
        manualDialogMode === 'create'
          ? t('RecipeManagement.RecipeConfig.manualDialogCreateTitle')
          : t('RecipeManagement.RecipeConfig.manualDialogEditTitle')
      "
      v-model="manualDialogVisible"
      width="640px"
    >
      <el-form
        ref="manualFormRef"
        :model="manualForm"
        :rules="manualRules"
        class="recipe-config-manual-dialog-form"
        label-width="auto"
        v-loading="manualDialogLoading"
      >
        <el-form-item :label="t('RecipeManagement.RecipeConfig.manualDialogNameLabel')" prop="name">
          <el-input
            v-model="manualForm.name"
            :placeholder="t('RecipeManagement.RecipeConfig.manualDialogNamePlaceholder')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="t('RecipeManagement.RecipeConfig.manualDialogMaxLabel')" prop="max">
          <el-input
            v-model="manualForm.max"
            :placeholder="t('RecipeManagement.RecipeConfig.manualDialogMaxPlaceholder')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="t('RecipeManagement.RecipeConfig.manualDialogMinLabel')" prop="min">
          <el-input
            v-model="manualForm.min"
            :placeholder="t('RecipeManagement.RecipeConfig.manualDialogMinPlaceholder')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="t('RecipeManagement.RecipeConfig.manualDialogDataTypeLabel')" prop="dataType">
          <el-select
            v-model="manualForm.dataType"
            :placeholder="t('RecipeManagement.RecipeConfig.manualDialogDataTypePlaceholder')"
            clearable
            filterable
            class="!w-full"
          >
            <el-option
              v-for="dict in dataTypeDictOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('RecipeManagement.RecipeConfig.manualDialogDataUnitLabel')" prop="dataUnit">
          <el-select
            v-model="manualForm.dataUnit"
            :placeholder="t('RecipeManagement.RecipeConfig.manualDialogDataUnitPlaceholder')"
            clearable
            filterable
            class="!w-full"
          >
            <el-option
              v-for="unit in unitList"
                :key="unit.id"
                :label="unit.name"
                :value="unit.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('RecipeManagement.RecipeConfig.manualDialogRemarkLabel')" prop="remark">
          <el-input
            v-model="manualForm.remark"
            :placeholder="t('RecipeManagement.RecipeConfig.manualDialogRemarkPlaceholder')"
            clearable
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="manualDialogVisible = false">
          {{ t('RecipeManagement.RecipeConfig.manualDialogCancelButton') }}
        </el-button>
        <el-button type="primary" :disabled="manualDialogLoading" @click="submitManualDialog">
          {{ t('RecipeManagement.RecipeConfig.manualDialogSaveButton') }}
        </el-button>
      </template>
    </Dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { RecipeConfigApi, RecipePointDetailVO } from '@/api/iot/recipeConfig'
import { RecipePointApi, RecipePointVO } from '@/api/iot/recipePoint'
import { getStrDictOptions } from '@/utils/dict'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'

defineOptions({ name: 'RecipeDetailList' })

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

const props = defineProps<{
  visible: boolean
  recipeId?: string
  manualRecipeId?: string | number
  recipeCode: string
  name: string
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'config'): void
}>()

const activeTab = ref('detail')
const loading = ref(false)
const list = ref<RecipePointDetailVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

const unitList = ref<ProductUnitVO[]>([]) // 产品单位列表
const manualLoading = ref(false)
const manualList = ref<RecipePointVO[]>([])
const manualTotal = ref(0)
const manualQueryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

type ManualDialogMode = 'create' | 'update'
const manualDialogVisible = ref(false)
const manualDialogMode = ref<ManualDialogMode>('create')
const manualDialogLoading = ref(false)
const manualFormRef = ref()
const manualForm = reactive({
  id: undefined as number | undefined,
  name: '',
  max: '' as string | undefined,
  min: '' as string | undefined,
  dataType: '' as string | undefined,
  dataUnit: '' as string | undefined,
  remark: '' as string | undefined
})
const manualRules = reactive({
  name: [
    {
      required: true,
      message: t('RecipeManagement.RecipeConfig.manualValidatorNameRequired'),
      trigger: 'blur'
    }
  ],
  max: [
    {
      required: true,
      message: t('RecipeManagement.RecipeConfig.manualValidatorMaxRequired'),
      trigger: 'blur'
    }
  ],
  min: [
    {
      required: true,
      message: t('RecipeManagement.RecipeConfig.manualValidatorMinRequired'),
      trigger: 'blur'
    }
  ],
  dataType: [
    {
      required: true,
      message: t('RecipeManagement.RecipeConfig.manualValidatorDataTypeRequired'),
      trigger: 'change'
    }
  ],
  dataUnit: [
    {
      required: true,
      message: t('RecipeManagement.RecipeConfig.manualValidatorDataUnitRequired'),
      trigger: 'change'
    }
  ]
})

const dataTypeDictOptions = computed(() => getStrDictOptions('iot_device_data_type'))
// const unitDictOptions = computed(() => getStrDictOptions('iot_device_attribute_unit'))

const normalizeDetail = (item: any): RecipePointDetailVO => {
  return {
    ...item,
    pointName: item.pointName ?? item.attributeName,
    pointType: item.pointType ?? item.attributeType
  }
}

const getList = async () => {
  if (!props.recipeId) return
  loading.value = true
  try {
    const pageSize = Math.min(100, Math.max(1, Number(queryParams.pageSize) || 10))
    const data = await RecipeConfigApi.getRecipePointDetailPage({
      pageNo: queryParams.pageNo,
      pageSize,
      recipeId: props.recipeId
    })
    const rawList = Array.isArray((data as any)?.list)
      ? (data as any).list
      : Array.isArray((data as any)?.data)
      ? (data as any).data
      : Array.isArray(data)
      ? data
      : []
    list.value = rawList.map(normalizeDetail)
    total.value = (data as any)?.total ?? rawList.length
    unitList.value = await ProductUnitApi.getProductUnitSimpleList()
  } finally {
    loading.value = false
  }
}

const handlePagination = () => {
  getList()
}

const getManualList = async () => {
  if (!props.manualRecipeId) return
  manualLoading.value = true
  try {
    const pageSize = Math.min(100, Math.max(1, Number(manualQueryParams.pageSize) || 10))
    const data = await RecipePointApi.getRecipePointPage({
      pageNo: manualQueryParams.pageNo,
      pageSize,
      recipeId: props.manualRecipeId
    })
    manualList.value = data.list ?? []
    manualTotal.value = data.total
  } finally {
    manualLoading.value = false
  }
}

const handleManualPagination = () => {
  getManualList()
}

const openManualDialog = (mode: ManualDialogMode, row?: RecipePointVO) => {
  manualDialogMode.value = mode
  manualDialogVisible.value = true
  nextTick(() => {
    manualFormRef.value?.clearValidate?.()
  })
  if (mode === 'create') {
    manualForm.id = undefined
    manualForm.name = ''
    manualForm.max = ''
    manualForm.min = ''
    manualForm.dataType = ''
    manualForm.dataUnit = ''
    manualForm.remark = ''
    return
  }
  manualForm.id = row?.id
  manualForm.name = row?.name ?? ''
  manualForm.max = row?.max === undefined || row?.max === null ? '' : String(row.max)
  manualForm.min = row?.min === undefined || row?.min === null ? '' : String(row.min)
  manualForm.dataType = row?.dataType === undefined || row?.dataType === null ? '' : String(row.dataType)
  manualForm.dataUnit = row?.dataUnit ?? ''
  manualForm.remark = row?.remark ?? ''
}

const submitManualDialog = async () => {
  if (!props.manualRecipeId) return
  await manualFormRef.value?.validate?.()
  manualDialogLoading.value = true
  try {
    const params = {
      id: manualForm.id,
      recipeId: props.manualRecipeId,
      name: manualForm.name,
      max: manualForm.max,
      min: manualForm.min,
      dataType: manualForm.dataType,
      dataUnit: manualForm.dataUnit,
      remark: manualForm.remark
    }
    if (manualDialogMode.value === 'create') {
      await RecipePointApi.createRecipePoint(params)
      message.success(t('common.createSuccess'))
    } else {
      await RecipePointApi.updateRecipePoint(params)
      message.success(t('common.updateSuccess'))
    }
    manualDialogVisible.value = false
    await getManualList()
  } finally {
    manualDialogLoading.value = false
  }
}

const handleManualDelete = async (row: RecipePointVO) => {
  try {
    await message.delConfirm()
    await RecipePointApi.deleteRecipePoint(row.id)
    message.success(t('common.delSuccess'))
    await getManualList()
  } catch {}
}

const handleClose = () => {
  emit('close')
}

const handleConfig = () => {
  emit('config')
}

watch(
  () => [props.visible, props.recipeId],
  ([visible]) => {
    if (!visible) return
    queryParams.pageNo = 1
    manualQueryParams.pageNo = 1
    activeTab.value = 'detail'
    getList()
  },
  { immediate: true }
)

watch(
  () => activeTab.value,
  (tab) => {
    if (!props.visible) return
    if (tab === 'manual') {
      getManualList()
    }
  }
)

const refresh = async () => {
  if (activeTab.value === 'manual') {
    await getManualList()
    return
  }
  await getList()
}

defineExpose({ refresh })
</script>

<style scoped>
.recipe-config-manual-dialog-form :deep(.el-form-item__label) {
  min-width: 90px;
}
</style>
