<template>
  <el-form
    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">
          <div class="mobile-item-card__header-left">
            <span class="mobile-item-card__index">#{{ $index + 1 }}</span>
            <span class="mobile-item-card__name">{{ row.productName || '未选择产品' }}</span>
          </div>
          <el-button @click="handleDelete($index)" link type="danger" size="small" :disabled="disabled">删除</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">{{ row.productSpec || '-' }}</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__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" :precision="4" style="width: 100%" />
            </el-form-item>
          </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" style="color: #e6a23c; font-weight: 600">{{ 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>{{ summaryData.count }}</span>
        </div>
        <div class="mobile-item-summary__row">
          <span>合计金额</span>
          <span>{{ summaryData.totalPrice }}</span>
        </div>
      </div>

      <!-- 添加按钮 -->
      <div class="mobile-item-add" v-if="!disabled">
        <el-button @click="handleAdd" round>+ 添加请购产品</el-button>
      </div>
    </div>
  </el-form>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'

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[]
  },
  { immediate: true }
)

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

/** 合计 */
const summaryData = computed(() => {
  const countSum = getSumValue(formData.value.map((item) => Number(item.count || 0)))
  const priceSum = getSumValue(formData.value.map((item) => Number(item.totalPrice || 0)))
  return {
    count: erpCountInputFormatter(countSum),
    totalPrice: erpPriceInputFormatter(priceSum)
  }
})

/** 新增按钮操作 */
const handleAdd = () => {
  const row: any = {
    id: undefined,
    productId: undefined,
    productName: undefined,
    productSpec: undefined, // 产品规格
    productUnitId: undefined,
    productUnitName: undefined, // 产品单位
    productBarCode: undefined, // 产品条码
    productPrice: undefined,
    count: 1,
    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.productSpec = product.standard // 规格
    row.productUnitId = product.unitId // 产品单位编号
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.purchasePrice // 采购价格
  }
}

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

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>

<style lang="scss" scoped>
.mobile-item-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-item-card {
  background: #fff;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
  overflow: hidden;
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 12px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }
  &__header-left {
    display: flex;
    align-items: center;
    gap: 6px;
  }
  &__index {
    font-weight: 600;
    font-size: 13px;
    color: #909399;
  }
  &__name {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
  }
  &__body {
    padding: 12px;
  }
  &__info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    font-size: 13px;
    &--highlight {
      padding: 6px 0;
      margin-top: 4px;
      border-top: 1px dashed #e4e7ed;
    }
  }
  &__info-label {
    color: #909399;
  }
  &__info-value {
    color: #606266;
  }
  &__input-group {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
}
.mobile-item-summary {
  background: #fff;
  border-radius: 10px;
  padding: 12px;
  &__row {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    padding: 3px 0;
  }
}
.mobile-item-add {
  display: flex;
  justify-content: center;
  padding: 8px 0;
}
</style>
