<template>
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="auto"
      class="-mb-15px"
    >
      <el-form-item :label="t('ErpStock.Check.no')" prop="no">
        <el-input
          v-model="queryParams.no"
          :placeholder="t('ErpStock.Check.placeholderNo')"
          clearable
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.warehouse')" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          :placeholder="t('ErpStock.Check.placeholderWarehouse')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.checkTime')" prop="checkTime">
        <el-date-picker
          v-model="queryParams.checkTime"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('ErpStock.Check.placeholderStatus')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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="['erp:stock-check:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.create') }}
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="selectionList.length === 0"
          @click="handleDelete(selectionList.map((item) => item.id))"
        >
          <Icon icon="ep:delete" class="mr-5px" />
          {{ t('action.batchDelete') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      stripe
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" />
      <el-table-column :label="t('ErpStock.Check.no')" prop="no" align="center" min-width="150" />
      <el-table-column
        :label="t('ErpStock.Check.productNames')"
        prop="productNames"
        min-width="180"
        show-overflow-tooltip
      />
      <el-table-column :label="t('ErpStock.Check.warehouse')" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">
          {{ getWarehouseNames(row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('ErpStock.Check.checkTime')"
        prop="checkTime"
        :formatter="dateFormatter"
        min-width="170"
      />
      <el-table-column :label="t('ErpStock.Check.status')" prop="status" align="center" min-width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.Check.checkStatus')" prop="checkStatus" align="center" min-width="100">
        <template #default="scope">
          <el-tag :type="Number(scope.row.checkStatus) === 1 ? 'success' : 'info'">
            {{
              Number(scope.row.checkStatus) === 1
                ? t('ErpStock.Check.checkStatusChecked')
                : t('ErpStock.Check.checkStatusUnchecked')
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('ErpStock.Check.creator')"
        prop="creatorName"
        align="center"
        min-width="120"
      />
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="dateFormatter"
        min-width="170"
      />
      <el-table-column :label="t('ErpStock.Check.auditUserName')" prop="auditUserName" align="center" min-width="120" />
      <el-table-column
        :label="t('ErpStock.Check.remark')"
        prop="remark"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column :label="t('common.operate')" align="center" fixed="right" width="320">
        <template #default="scope">
          <el-button
            v-if="Number(scope.row.status) === 10"
            link
            type="primary"
            @click="openAuditDialog(scope.row, 20)"
          >
            {{ t('ErpStock.Check.auditApprove') }}
          </el-button>
          <el-button
            v-if="Number(scope.row.status) === 10"
            link
            type="danger"
            @click="openAuditDialog(scope.row, 1)"
          >
            {{ t('ErpStock.Check.auditReject') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
          >
            {{ t('action.detail') }}
          </el-button>
          <el-button
            link
            type="primary"
            :disabled="scope.row.status === 20"
            @click="openForm('update', scope.row.id)"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            v-if="[0, 1].includes(Number(scope.row.status)) && Number(scope.row.checkStatus) === 1"
            link
            type="primary"
            @click="openSubmitDialog(scope.row)"
          >
            {{ t('ErpStock.Check.submit') }}
          </el-button>
          <el-button
            v-if="Number(scope.row.checkStatus) !== 1"
            link
            type="warning"
            :disabled="scope.row.status === 20"
            @click="openForm('check', scope.row.id)"
          >
            {{ t('ErpStock.Check.inventoryCheck') }}
          </el-button>
          <el-button
            link
            type="danger"
            :disabled="scope.row.status === 20"
            @click="handleDelete([scope.row.id])"
          >
            {{ 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>

  <Dialog :title="submitActionText" v-model="submitDialogVisible" width="500">
    <el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="auto">
      <el-form-item v-if="!isAuditDisabled" :label="t('ErpStock.Check.auditUserName')" prop="auditUserId">
        <el-select
          v-model="submitForm.auditUserId"
          filterable
          :placeholder="t('ErpStock.Check.placeholderAuditUser')"
          class="!w-1/1"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.submitRemark')" prop="remark">
        <el-input
          v-model="submitForm.remark"
          type="textarea"
          :rows="3"
          :placeholder="t('ErpStock.Check.placeholderSubmitRemark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="submitLoading" @click="handleSubmit">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="submitDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

  <Dialog :title="auditDialogTitle" v-model="auditDialogVisible" width="500">
    <el-form :model="auditForm" label-width="auto">
      <el-form-item :label="t('ErpStock.Check.auditRemark')" prop="remark">
        <el-input
          v-model="auditForm.remark"
          type="textarea"
          :rows="3"
          :placeholder="t('ErpStock.Check.placeholderAuditRemark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="auditLoading" @click="handleAudit">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="auditDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

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

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { StockCheckApi, type StockCheckVO } from '@/api/erp/stock/check'
import { WarehouseApi, type WarehouseVO } from '@/api/erp/stock/warehouse'
import * as UserApi from '@/api/system/user'
import * as ConfigApi from '@/api/infra/config'
import StockCheckExecutionForm from './components/StockCheckExecutionForm.vue'

defineOptions({ name: 'ErpStockCheckExecution' })

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

const loading = ref(false)
const list = ref<StockCheckVO[]>([])
const total = ref(0)
const warehouseList = ref<WarehouseVO[]>([])
const selectionList = ref<StockCheckVO[]>([])
const userList = ref<UserApi.UserVO[]>([])
const queryFormRef = ref()
const formRef = ref()
const submitFormRef = ref()
const submitDialogVisible = ref(false)
const submitLoading = ref(false)
const submitForm = reactive({
  id: undefined as number | undefined,
  auditUserId: undefined as number | undefined,
  remark: undefined as string | undefined
})
const isAuditDisabled = ref(false)
const submitActionText = computed(() =>
  isAuditDisabled.value ? t('ErpStock.Check.inventoryCheck') : t('ErpStock.Check.submit')
)
const submitRules = computed(() => isAuditDisabled.value ? {} : {
  auditUserId: [{ required: true, message: t('ErpStock.Check.validatorAuditUserRequired'), trigger: 'change' }]
})
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const auditForm = reactive({
  id: undefined as number | undefined,
  status: undefined as number | undefined,
  remark: undefined as string | undefined
})
const auditDialogTitle = computed(() =>
  auditForm.status === 20 ? t('ErpStock.Check.auditApprove') : t('ErpStock.Check.auditReject')
)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined as string | undefined,
  warehouseId: undefined as number | undefined,
  checkTime: [] as string[],
  status: undefined as number | undefined
})

const getList = async () => {
  loading.value = true
  try {
    const data = await StockCheckApi.getStockCheckPage(queryParams)
    list.value = data?.list || []
    total.value = data?.total || 0
  } finally {
    loading.value = false
  }
}

const loadAuditConfig = async () => {
  try {
    const data = await ConfigApi.getConfigPage({ pageNo: 1, pageSize: 10, key: 'inventoryAudit' } as PageParam & { key: string })
    const auditConfig = data?.list?.find((item) => item?.key === 'inventoryAudit')
    isAuditDisabled.value = auditConfig?.value === '0'
  } catch {
    isAuditDisabled.value = false
  }
}

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

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

const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (ids: number[]) => {
  if (ids.length === 0) {
    return
  }
  try {
    await message.delConfirm()
    await StockCheckApi.deleteStockCheck(ids)
    message.success(t('common.delSuccess'))
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
    await getList()
  } catch {}
}

const handleSelectionChange = (rows: StockCheckVO[]) => {
  selectionList.value = rows
}

const openSubmitDialog = (row: StockCheckVO) => {
  const hasIncompleteItem = (row.items || []).some(
    (item) => item.actualCount === undefined || item.actualCount === null || item.actualCount === ''
  )
  if (hasIncompleteItem) {
    message.warning(t('ErpStock.Check.validatorCompleteCheckInfo'))
    return
  }
  submitForm.id = row.id
  submitForm.auditUserId = row.auditUserId
  submitForm.remark = undefined
  submitDialogVisible.value = true
  submitFormRef.value?.clearValidate()
}

const handleSubmit = async () => {
  if (!isAuditDisabled.value) {
    await submitFormRef.value.validate()
  }
  if (!submitForm.id || (!isAuditDisabled.value && !submitForm.auditUserId)) {
    return
  }
  submitLoading.value = true
  try {
    if (isAuditDisabled.value) {
      await StockCheckApi.auditStockCheck({
        id: submitForm.id,
        status: 20,
        remark: submitForm.remark
      })
      message.success(t('ErpStock.Check.auditApproveSuccess'))
      submitDialogVisible.value = false
      await getList()
      return
    }
    const data: { id: number; auditUserId?: number; remark?: string } = {
      id: submitForm.id,
      remark: submitForm.remark
    }
    data.auditUserId = submitForm.auditUserId
    await StockCheckApi.submitStockCheck(data)
    message.success(t('ErpStock.Check.submitSuccess'))
    submitDialogVisible.value = false
    await getList()
  } finally {
    submitLoading.value = false
  }
}

const openAuditDialog = (row: StockCheckVO, status: number) => {
  auditForm.id = row.id
  auditForm.status = status
  auditForm.remark = undefined
  auditDialogVisible.value = true
}

const handleAudit = async () => {
  if (!auditForm.id || !auditForm.status) {
    return
  }
  auditLoading.value = true
  try {
    await StockCheckApi.auditStockCheck({
      id: auditForm.id,
      status: auditForm.status,
      remark: auditForm.remark
    })
    message.success(
      auditForm.status === 20
        ? t('ErpStock.Check.auditApproveSuccess')
        : t('ErpStock.Check.auditRejectSuccess')
    )
    auditDialogVisible.value = false
    await getList()
  } finally {
    auditLoading.value = false
  }
}

const getWarehouseNames = (row: StockCheckVO) => {
  const names = Array.from(new Set((row.items || []).map((item) => item.warehouseName).filter(Boolean)))
  return names.length ? names.join('、') : '-'
}

onMounted(async () => {
  const [warehouses, users] = await Promise.all([
    WarehouseApi.getWarehouseSimpleList(),
    UserApi.getSimpleUserList(),
    loadAuditConfig()
  ])
  warehouseList.value = warehouses || []
  userList.value = users || []
  await getList()
})
</script>
