<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="disabled || formData.length === 1"
            @click="handleDelete($index)"
            link
            type="danger"
            size="small"
          >
            删除
          </el-button>
        </div>
        <div class="mobile-item-card__body">
          <el-form-item
            label="产品"
            :prop="`${$index}.productId`"
            :rules="formRules.productId"
          >
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
              style="width: 100%"
            >
              <el-option
                v-for="item in productList"
                :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">{{ 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">
            <span class="mobile-item-card__info-label">供应商</span>
            <span class="mobile-item-card__info-value">{{ row.supplierName || '-' }}</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`" :rules="formRules.productPrice">
              <el-input-number
                v-model="row.productPrice"
                controls-position="right"
                :min="0.0001"
                :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>
          <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 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>
          <el-form-item label="税额合计" :prop="`${$index}.totalPrice`">
            <el-input-number
              v-model="row.totalPrice"
              controls-position="right"
              :min="0"
              :precision="4"
              style="width: 100%"
              @change="onChangeTotalPrice(row)"
            />
          </el-form-item>
          <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 class="mobile-item-add" v-if="!disabled"><el-button @click="handleAdd" round>+ 添加采购产品</el-button></div>
    </div>
  </el-form>

  <!-- PC端布局 -->
  <template v-else>
    <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="180"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!"><el-select v-model="row.productId" clearable filterable @change="onChangeProduct($event, row)" placeholder="请选择产品"><el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id" /></el-select></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="供应商" min-width="150"><template #default="{ row }"><el-form-item class="mb-0px!"><el-input disabled v-model="row.supplierName" /></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`" :rules="formRules.productPrice" class="mb-0px!"><el-input-number v-model="row.productPrice" controls-position="right" :min="0.0001" :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="120"><template #default="{ row, $index }"><el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!"><el-input-number v-model="row.totalPrice" controls-position="right" :min="0" :precision="4" class="!w-100%" @change="onChangeTotalPrice(row)" /></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 @click="handleDelete($index)" link>—</el-button></template></el-table-column>
      </el-table>
    </el-form>
    <el-row justify="center" class="mt-3" v-if="!disabled"><el-button @click="handleAdd" round>+ 添加采购产品</el-button></el-row>
  </template>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { StockApi } from '@/api/erp/stock/stock'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'
import { computed } from 'vue'
import { useWindowSize } from '@vueuse/core'

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

const props = withDefaults(
  defineProps<{
    items: any[]
    disabled?: boolean
  }>(),
  {
    items: () => [],
    disabled: false
  }
)
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref<any>([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表

/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val as any[]
    // 当从请购单带入产品时，自动加载库存和条码
    if (val && val.length > 0 && productList.value.length > 0) {
      await initProductInfo(val)
    }
  },
  { immediate: true }
)

/** 初始化产品的库存和条码信息（用于请购单带入的数据） */
const initProductInfo = async (items: any[]) => {
  for (const row of items) {
    if (row.productId) {
      // 如果条码为空，从产品列表中获取
      if (!row.productBarCode) {
        const product = productList.value.find((item) => item.id === row.productId)
        if (product) {
          row.productBarCode = product.barCode
          row.supplierId = product.supplierId
          row.supplierName = product.supplierName
        }
      }
      // 如果库存为空，调用API获取
      if (row.stockCount === undefined || row.stockCount === null) {
        await setStockCount(row)
      }
    }
  }
}

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item: any) => {
      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100.0)
      if (item.totalProductPrice != null) {
        item.totalPrice = (item.totalProductPrice || 0) + (item.taxPrice || 0)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  { deep: true }
)

/** 合计 - 移动端 */
const summaryData = computed(() => {
  const data = formData.value || []
  return {
    count: getSumValue(data.map((item) => Number(item.count))),
    totalProductPrice: getSumValue(data.map((item) => Number(item.totalProductPrice))),
    taxPrice: getSumValue(data.map((item) => Number(item.taxPrice))),
    totalPrice: getSumValue(data.map((item) => Number(item.totalPrice)))
  }
})

/** 合计 - 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 = () => {
  const row: any = {
    id: undefined,
    productId: undefined,
    productUnitName: undefined, // 产品单位
    productBarCode: undefined, // 产品条码
    productPrice: undefined,
    stockCount: undefined,
    supplierId: undefined,
    supplierName: undefined,
    count: 1,
    totalProductPrice: undefined,
    taxPercent: undefined,
    taxPrice: undefined,
    totalPrice: undefined,
    remark: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productName = product.name
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.purchasePrice
    row.supplierId = product.supplierId
    row.supplierName = product.supplierName
  }
  // 加载库存
  setStockCount(row)
}

/** 加载库存 */
const setStockCount = async (row: any) => {
  if (!row.productId) {
    return
  }
  const count = await StockApi.getStockCount(row.productId)
  row.stockCount = count || 0
}

/** 处理税额合计变更，反算单价和金额 */
const onChangeTotalPrice = (row: any) => {
  if (row.totalPrice == null || row.count == null || row.count <= 0) {
    return
  }
  // 税率，默认为0
  const taxPercent = row.taxPercent || 0
  // 金额 = 税额合计 / (1 + 税率/100)
  const totalProductPrice = row.totalPrice / (1 + taxPercent / 100)
  row.totalProductPrice = Math.round(totalProductPrice * 10000) / 10000
  // 税额 = 税额合计 - 金额
  row.taxPrice = Math.round((row.totalPrice - row.totalProductPrice) * 10000) / 10000
  // 单价 = 金额 / 数量
  row.productPrice = Math.round((row.totalProductPrice / row.count) * 10000) / 10000
}

/** 表单校验 */
const validate = () => {
  return (formRef.value as any).validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
  // 产品列表加载完成后，初始化已有产品的库存和条码（处理请购单带入的数据）
  if (formData.value.length > 0) {
    await initProductInfo(formData.value)
  } else {
    // 默认添加一个
    handleAdd()
  }
})
</script>

<style lang="scss" scoped>
.mobile-item-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-item-card {
  background: #f9fafb;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  overflow: hidden;
  &__header {
    display: flex;
    align-items: center;
    padding: 10px 12px;
    background: #f0f2f5;
    gap: 8px;
  }
  &__index {
    font-size: 13px;
    font-weight: 600;
    color: #409eff;
    flex-shrink: 0;
  }
  &__name {
    flex: 1;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &__body {
    padding: 10px 12px;
  }
  &__info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    font-size: 13px;
  }
  &__info-label {
    color: #909399;
    flex-shrink: 0;
  }
  &__info-value {
    color: #606266;
    text-align: right;
  }
  &__input-group {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
}
.mobile-item-summary {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  padding: 10px 12px;
  &__row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 13px;
    color: #606266;
    &--total {
      font-weight: 600;
      color: #303133;
      border-top: 1px solid #ebeef5;
      padding-top: 8px;
      margin-top: 4px;
    }
  }
}
.mobile-item-add {
  text-align: center;
  padding: 8px 0;
}
</style>
