<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">
          <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 || !!row.stockRecordId"
            @click="handleDelete($index)"
            link
            type="danger"
            size="small"
          >
            删除
          </el-button>
        </div>
        <div class="mobile-item-card__body">
          <el-form-item
            label="仓库"
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
              style="width: 100%"
            >
              <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="产品"
            :prop="`${$index}.productId`"
            :rules="formRules.productId"
          >
            <el-select
              v-model="row.productId"
              clearable
              filterable
              placeholder="请选择产品"
              @change="onChangeProduct($event, row)"
              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" v-if="row.batchCode">
            <span class="mobile-item-card__info-label">批号</span>
            <span class="mobile-item-card__info-value">{{ row.batchCode }}</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__input-group">
            <el-form-item label="数量" :prop="`${$index}.count`" :rules="formRules.count">
              <el-input-number
                v-model="row.count"
                controls-position="right"
                :min="0"
                :precision="4"
                style="width: 100%"
                :disabled="!!row.stockRecordId"
              />
            </el-form-item>
            <el-form-item label="产品单价" :prop="`${$index}.productPrice`">
              <el-input-number
                v-model="row.productPrice"
                controls-position="right"
                :min="0"
                :precision="8"
                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="2"
              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>
          <div class="mobile-item-card__info-row">
            <span class="mobile-item-card__info-label">税额合计</span>
            <span class="mobile-item-card__info-value">{{ 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 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>
</template>
<script setup lang="ts">
import { StockApi } from '@/api/erp/stock/stock'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'

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

/** 初始化设置出库项 */
watch(
  () => props.items,
  async (val) => {
    if (!val) return
    val.forEach((item) => {
      if (item.warehouseId == null) {
        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 || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100.0)
      if (item.totalProductPrice != null) {
        item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  { deep: true }
)

/** 合计 */
const summaryData = computed(() => {
  return {
    count: getSumValue(formData.value.map((item) => Number(item.count))),
    totalProductPrice: getSumValue(formData.value.map((item) => Number(item.totalProductPrice))),
    taxPrice: getSumValue(formData.value.map((item) => Number(item.taxPrice))),
    totalPrice: getSumValue(formData.value.map((item) => Number(item.totalPrice)))
  }
})

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    warehouseId: defaultWarehouse.value?.id,
    productId: undefined,
    productUnitId: undefined,
    productUnitName: undefined, // 产品单位
    productBarCode: undefined, // 产品条码
    batchCode: undefined, // 批次编号
    productPrice: undefined,
    stockCount: undefined,
    count: 1,
    totalProductPrice: undefined,
    taxPercent: 0,
    taxPrice: undefined,
    totalPrice: undefined,
    remark: undefined
  }
  formData.value.push(row)
}

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

/** 选择仓库 */
const onChangeWarehouse = (warehouseId: number, row: any) => {
  setStockCount(row)
}

/** 选择产品 */
const onChangeProduct = (productId: number, row: any) => {
  if (!productId) {
    row.productUnitId = undefined
    row.productUnitName = undefined
    row.productBarCode = undefined
    row.productPrice = undefined
    return
  }
  // 设置产品信息
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productName = product.name
    row.productUnitId = product.unitId
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.price
    row.taxPercent = product.taxPercent || 0
  }
  // 设置库存信息
  setStockCount(row)
}

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

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

/** 初始化 */
onMounted(async () => {
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.defaultStatus)
  productList.value = await ProductApi.getProductSimpleList()
})
</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>
