<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="仓库名称" min-width="125">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="条码" min-width="150">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productBarCode" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="换出数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="0.001"
              :precision="3"
              class="!w-100%"
              @change="calculateRowPrice(row)"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单价" prop="productPrice" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" :rules="formRules.productPrice" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0"
              :precision="4"
              class="!w-100%"
              @change="calculateRowPrice(row)"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.totalPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>
            <Icon icon="ep:delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加换出商品</el-button>
  </el-row>

  <!-- 产品选择弹窗 -->
  <ProductEnableList ref="productEnableListRef" @success="handleProductChange" />
</template>

<script setup lang="ts">
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { StockApi } from '@/api/erp/stock/stock'
import { erpCountInputFormatter, erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import ProductEnableList from './ProductEnableList.vue'

defineOptions({ name: 'SaleExchangeOutItemForm' })

interface Props {
  items: any[]
  disabled: boolean
}

const props = withDefaults(defineProps<Props>(), {
  items: () => [],
  disabled: false
})

const formLoading = ref(false)
const formData = ref<any[]>([])
const formRules = reactive({
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  productPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }]
})
const formRef = ref()

const warehouseList = ref<WarehouseVO[]>([])
const productEnableListRef = ref()

watch(
  () => props.items,
  (val) => {
    formData.value = val || []
  },
  { immediate: true, deep: true }
)

const handleAdd = () => {
  productEnableListRef.value.open()
}

const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
  emit('change')
}

const handleProductChange = async (products: any[]) => {
  for (const product of products) {
    const exists = formData.value.find(item => item.productId === product.id)
    if (!exists) {
      formData.value.push({
        productId: product.id,
        productName: product.name,
        productBarCode: product.barCode,
        productUnitId: product.unitId,
        productUnitName: product.unitName,
        warehouseId: undefined,
        warehouseName: undefined,
        count: 1,
        productPrice: product.salePrice || 0,
        totalPrice: product.salePrice || 0,
        stockCount: 0
      })
    }
  }
  emit('change')
}

const onChangeWarehouse = async (warehouseId: number, row: any) => {
  if (!warehouseId || !row.productId) return

  const warehouse = warehouseList.value.find(item => item.id === warehouseId)
  row.warehouseName = warehouse?.name

  try {
    const stock = await StockApi.getStock2(row.productId, warehouseId)
    row.stockCount = stock?.count || 0
  } catch {
    row.stockCount = 0
  }
}

const calculateRowPrice = (row: any) => {
  row.totalPrice = erpPriceMultiply(row.count, row.productPrice)
  emit('change')
}

const emit = defineEmits(['change'])

const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalPrice'].includes(column.property)) {
      const values = data.map((item: any) => Number(item[column.property]))
      if (!values.every((value: any) => isNaN(value))) {
        const sum = values.reduce((prev: any, curr: any) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        if (column.property === 'totalPrice') {
          sums[index] = erpPriceInputFormatter(sum)
        } else {
          sums[index] = erpCountInputFormatter(sum)
        }
      } else {
        sums[index] = ''
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const validate = async () => {
  return await formRef.value?.validate()
}

const getData = () => {
  return formData.value
}

if (onMounted) {
  onMounted(async () => {
    warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  })
}

defineExpose({ validate, getData })
</script>
