<template>
  <!-- 移动端布局 -->
  <el-form v-if="isMobile" ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-position="top" :inline-message="true" :disabled="disabled">
    <div class="mobile-item-list">
      <div
        v-for="(row, $index) in formData"
        :key="$index"
        class="mobile-item-card"
      >
        <!-- 卡片头部 -->
        <div class="mobile-item-card__header">
          <span class="mobile-item-card__index">#{{ $index + 1 }}</span>
          <span class="mobile-item-card__name">{{ row.productName || '未选择产品' }}</span>
          <el-button
            :disabled="formData.length === 1 || disabled"
            type="danger"
            link
            size="small"
            @click="handleDelete($index)"
          >
            删除
          </el-button>
        </div>

        <!-- 卡片内容 -->
        <div class="mobile-item-card__body">
          <!-- 仓库 -->
          <el-form-item :prop="`${$index}.warehouseId`" :rules="formRules.warehouseId" label="仓库">
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              style="width: 100%"
              @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>

          <!-- 产品名称 -->
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">产品名称</span>
            <span class="mobile-item-card__info-value">{{ row.productName || '-' }}</span>
          </div>

          <!-- 库存 -->
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">库存</span>
            <span class="mobile-item-card__info-value">{{ erpCountInputFormatter(row.stockCount) }}</span>
          </div>

          <!-- 条码 -->
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">条码</span>
            <span class="mobile-item-card__info-value">{{ row.productBarCode || '-' }}</span>
          </div>

          <!-- 单位 -->
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">单位</span>
            <span class="mobile-item-card__info-value">{{ row.productUnitName || '-' }}</span>
          </div>

          <!-- 已出库 -->
          <div class="mobile-item-card__info-row" v-if="row.inCount != null">
            <span class="mobile-item-card__info-label">已出库</span>
            <span class="mobile-item-card__info-value">{{ erpCountInputFormatter(row.inCount) }}</span>
          </div>

          <!-- 已退货 -->
          <div class="mobile-item-card__info-row" v-if="row.returnCount != null">
            <span class="mobile-item-card__info-label">已退货</span>
            <span class="mobile-item-card__info-value">{{ erpCountInputFormatter(row.returnCount) }}</span>
          </div>

          <!-- 数量 & 单价 -->
          <div class="mobile-item-card__input-group">
            <el-form-item label="数量" :prop="`${$index}.count`" :rules="formRules.count">
              <el-input-number
                v-model="row.count"
                controls-position="right"
                :min="0.0001"
                :precision="4"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="单价" :prop="`${$index}.productPrice`">
              <el-input-number
                v-model="row.productPrice"
                controls-position="right"
                :min="0"
                :precision="4"
                style="width: 100%"
              />
            </el-form-item>
          </div>

          <!-- 金额 -->
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">金额</span>
            <span class="mobile-item-card__info-value">{{ erpPriceInputFormatter(row.totalProductPrice) }}</span>
          </div>

          <!-- 税率 -->
          <div class="mobile-item-card__input-group">
            <el-form-item label="税率（%）" :prop="`${$index}.taxPercent`">
              <el-input-number
                v-model="row.taxPercent"
                controls-position="right"
                :min="0"
                :precision="4"
                style="width: 100%"
              />
            </el-form-item>
          </div>

          <!-- 税额 -->
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">税额</span>
            <span class="mobile-item-card__info-value">{{ erpPriceInputFormatter(row.taxPrice) }}</span>
          </div>

          <!-- 税额合计 -->
          <div class="mobile-item-card__info-row mobile-item-card__info-row--highlight">
            <span class="mobile-item-card__info-label">税额合计</span>
            <span class="mobile-item-card__info-value mobile-item-card__info-value--bold">{{ erpPriceInputFormatter(row.totalPrice) }}</span>
          </div>

          <!-- 备注 -->
          <el-form-item label="备注" :prop="`${$index}.remark`">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </div>
      </div>

      <!-- 合计 -->
      <div class="mobile-item-summary" v-if="formData.length > 0">
        <div class="mobile-item-summary__row"><span>合计数量</span><span>{{ erpCountInputFormatter(summaryData.count) }}</span></div>
        <div class="mobile-item-summary__row"><span>合计金额</span><span>{{ erpPriceInputFormatter(summaryData.totalProductPrice) }}</span></div>
        <div class="mobile-item-summary__row"><span>合计税额</span><span>{{ erpPriceInputFormatter(summaryData.taxPrice) }}</span></div>
        <div class="mobile-item-summary__row mobile-item-summary__row--total"><span>税额合计</span><span>{{ erpPriceInputFormatter(summaryData.totalPrice) }}</span></div>
      </div>
    </div>
  </el-form>

  <!-- PC端布局 -->
  <el-form v-else 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="已出库" fixed="right" min-width="80" v-if="formData[0]?.inCount != null"><template #default="{ row }"><el-form-item class="mb-0px!"><el-input disabled v-model="row.inCount" :formatter="erpCountInputFormatter" /></el-form-item></template></el-table-column>
      <el-table-column label="已退货" fixed="right" min-width="80" v-if="formData[0]?.returnCount != null"><template #default="{ row }"><el-form-item class="mb-0px!"><el-input disabled v-model="row.returnCount" :formatter="erpCountInputFormatter" /></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.0001" :precision="4" class="!w-100%" /></el-form-item></template></el-table-column>
      <el-table-column label="产品单价" fixed="right" min-width="120"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.productPrice`" class="mb-0px!"><el-input-number v-model="row.productPrice" controls-position="right" :min="0" :precision="4" class="!w-100%" /></el-form-item></template></el-table-column>
      <el-table-column label="金额" prop="totalProductPrice" fixed="right" min-width="100"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.totalProductPrice`" class="mb-0px!"><el-input disabled v-model="row.totalProductPrice" :formatter="erpPriceInputFormatter" /></el-form-item></template></el-table-column>
      <el-table-column label="税率（%）" fixed="right" min-width="115"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.taxPercent`" class="mb-0px!"><el-input-number v-model="row.taxPercent" controls-position="right" :min="0" :precision="4" class="!w-100%" /></el-form-item></template></el-table-column>
      <el-table-column label="税额" prop="taxPrice" fixed="right" min-width="120"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.taxPrice`" class="mb-0px!"><el-input disabled v-model="row.taxPrice" :formatter="erpPriceInputFormatter" /></el-form-item></template></el-table-column>
      <el-table-column label="税额合计" prop="totalPrice" fixed="right" min-width="100"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!"><el-input disabled v-model="row.totalPrice" :formatter="erpPriceInputFormatter" /></el-form-item></template></el-table-column>
      <el-table-column label="备注" min-width="150"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.remark`" class="mb-0px!"><el-input v-model="row.remark" placeholder="请输入备注" /></el-form-item></template></el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60"><template #default="{ $index }"><el-button :disabled="formData.length === 1" @click="handleDelete($index)" link>—</el-button></template></el-table-column>
    </el-table>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { StockApi } from '@/api/erp/stock/stock'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { erpCountInputFormatter, erpPriceInputFormatter, erpPriceMultiply, getSumValue } from '@/utils'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

const props = defineProps<{ items: any; disabled: boolean }>()
const formData = ref([])
const formLoading = ref(false)
const warehouseList = ref<WarehouseVO[]>([])
const defaultWarehouse = ref<WarehouseVO>(undefined)
const formRef = ref<any>(null)

const formRules = reactive({
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})

// 初始化
watch(
  () => props.items,
  async (val) => {
    if (!val) return
    val.forEach((item) => {
      if (!item.warehouseId) item.warehouseId = defaultWarehouse.value?.id
      if (item.stockCount === null && item.warehouseId != null) setStockCount(item)
    })
    formData.value = val
  },
  { immediate: true }
)

// 自动计算金额
watch(
  () => formData.value,
  (val) => {
    if (!val) return
    val.forEach((item) => {
      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100)
      item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
    })
  },
  { deep: true }
)

// 合计 - 移动端
const summaryData = computed(() =>
  formData.value.reduce(
    (acc, item) => {
      acc.count += Number(item.count || 0)
      acc.totalProductPrice += Number(item.totalProductPrice || 0)
      acc.taxPrice += Number(item.taxPrice || 0)
      acc.totalPrice += Number(item.totalPrice || 0)
      return acc
    },
    { count: 0, totalProductPrice: 0, taxPrice: 0, totalPrice: 0 }
  )
)

// 合计 - PC端
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (index === 0) { sums[index] = '合计'; return }
    if (['count', 'totalProductPrice', 'taxPrice', 'totalPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] = column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else { sums[index] = '' }
  })
  return sums
}

// 新增/删除/仓库切换
const handleAdd = () => {
  formData.value.push({
    id: undefined,
    productId: undefined,
    productUnitName: undefined,
    productBarCode: undefined,
    productPrice: undefined,
    stockCount: undefined,
    count: 1,
    totalProductPrice: undefined,
    taxPercent: undefined,
    taxPrice: undefined,
    totalPrice: undefined,
    remark: undefined
  })
}
const handleDelete = (index: number) => formData.value.splice(index, 1)
const onChangeWarehouse = (warehouseId, row) => setStockCount(row)
const setStockCount = async (row: any) => {
  if (!row.productId) return
  const count = await StockApi.getStockCount(row.productId)
  row.stockCount = count || 0
}
const validate = () => formRef.value?.validate()
defineExpose({ validate })

onMounted(async () => {
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.defaultStatus)
})
</script>

<style scoped lang="scss">
.mobile-item-list { display: flex; flex-direction: column; gap: 10px; }
.mobile-item-card { background: #f9f9fb; border-radius: 8px; padding: 12px; border: 1px solid #ebeef5;
  &__header { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #f0f0f0; }
  &__index { font-size: 12px; color: #909399; font-weight: 600; }
  &__name { flex: 1; font-size: 14px; font-weight: 600; color: #303133; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  &__body { font-size: 13px; }
  &__info-row { display: flex; justify-content: space-between; padding: 4px 0;
    &--highlight { margin-top: 4px; padding-top: 8px; border-top: 1px dashed #e4e7ed; }
  }
  &__info-label { color: #909399; flex-shrink: 0; }
  &__info-value { color: #606266; text-align: right;
    &--bold { font-weight: 600; color: #303133; }
  }
  &__input-group { display: flex; gap: 10px; margin-top: 6px;
    :deep(.el-form-item) { flex: 1; margin-bottom: 10px; }
  }
}
.mobile-item-summary { background: #fff; border-radius: 8px; padding: 12px; border: 1px solid #e6a23c;
  &__row { display: flex; justify-content: space-between; padding: 4px 0; font-size: 13px; color: #606266;
    &--total { margin-top: 4px; padding-top: 8px; border-top: 1px solid #f0f0f0; font-weight: 600; font-size: 14px; color: #303133; }
  }
}
</style>
