<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.bizNo || '未选择单据' }}</span>
          <el-button :disabled="disabled" @click="handleDelete($index)" link type="danger" size="small">删除</el-button>
        </div>
        <div class="mobile-item-card__body">
          <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>
          <div class="mobile-item-card__info-row"><span class="mobile-item-card__info-label">已付金额</span><span class="mobile-item-card__info-value">{{ erpPriceInputFormatter(row.paidPrice) }}</span></div>
          <el-form-item label="本次付款" :prop="`${$index}.paymentPrice`"><el-input-number v-model="row.paymentPrice" controls-position="right" :precision="4" style="width:100%" /></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>{{ erpPriceInputFormatter(summaryData.totalPrice) }}</span></div>
        <div class="mobile-item-summary__row"><span>已付合计</span><span>{{ erpPriceInputFormatter(summaryData.paidPrice) }}</span></div>
        <div class="mobile-item-summary__row mobile-item-summary__row--total"><span>本次付款合计</span><span>{{ erpPriceInputFormatter(summaryData.paymentPrice) }}</span></div>
      </div>
      <div class="mobile-item-add" v-if="!disabled">
        <el-button @click="handleOpenPurchaseIn" round>+ 添加采购入库单</el-button>
        <el-button @click="handleOpenPurchaseReturn" round>+ 添加采购退货单</el-button>
      </div>
    </div>
  </el-form>

  <!-- PC端布局 -->
  <el-form v-if="!isMobile" 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="200">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled >
              <template #prefix>
                <el-link
                  v-if="row.bizNo && row.bizId"
                  type="primary"
                  :underline="false"
                  @click.stop="openBizDetail(row)"
                  class="order-link"
                >
                  {{ row.bizNo }}
                </el-link>
              </template>
            </el-input>
          </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="已付金额" prop="paidPrice" fixed="right" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.paidPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="本次付款" prop="paymentPrice" fixed="right" min-width="115">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.paymentPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.paymentPrice"
              controls-position="right"
              :precision="4"
              class="!w-100%"
            />
          </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 v-if="!isMobile && !disabled" justify="center" class="mt-3">
    <el-button @click="handleOpenPurchaseIn" round>+ 添加采购入库单</el-button>
    <el-button @click="handleOpenPurchaseReturn" round>+ 添加采购退货单</el-button>
  </el-row>

  <!-- 可付款的【采购入库单】列表 -->
  <PurchaseInPaymentEnableList
    ref="purchaseInPaymentEnableListRef"
    @success="handleAddPurchaseIn"
  />
  <!-- 可付款的【采购入库单】列表 -->
  <PurchaseReturnRefundEnableList
    ref="purchaseReturnRefundEnableListRef"
    @success="handleAddPurchaseReturn"
  />

  <!-- 采购入库单详情弹窗 -->
  <PurchaseInForm ref="purchaseInFormRef" />
  <!-- 采购退货单详情弹窗 -->
  <PurchaseReturnForm ref="purchaseReturnFormRef" />
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ProductVO } from '@/api/erp/product/product'
import { erpPriceInputFormatter, getSumValue } from '@/utils'
import PurchaseInPaymentEnableList from '@/views/erp/purchase/in/components/PurchaseInPaymentEnableList.vue'
import PurchaseReturnRefundEnableList from '@/views/erp/purchase/return/components/PurchaseReturnRefundEnableList.vue'
import PurchaseInForm from '@/views/erp/purchase/in/PurchaseInForm.vue'
import PurchaseReturnForm from '@/views/erp/purchase/return/PurchaseReturnForm.vue'
import { PurchaseInVO } from '@/api/erp/purchase/in'
import { ErpBizType } from '@/utils/constants'
import { PurchaseReturnVO } from '@/api/erp/purchase/return'
import { useWindowSize } from '@vueuse/core'

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

const props = defineProps<{
  items: undefined
  supplierId: undefined
  disabled: false
}>()
const message = useMessage()

const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  paymentPrice: [{ required: true, message: '本次付款不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表

/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

/** 合计 - 移动端 */
const summaryData = computed(() => {
  return {
    totalPrice: getSumValue(formData.value.map((item) => Number(item.totalPrice))),
    paidPrice: getSumValue(formData.value.map((item) => Number(item.paidPrice))),
    paymentPrice: getSumValue(formData.value.map((item) => Number(item.paymentPrice)))
  }
})

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

/** 新增【采购入库】按钮操作 */
const purchaseInPaymentEnableListRef = ref()
const handleOpenPurchaseIn = () => {
  if (!props.supplierId) {
    message.error('请选择供应商')
    return
  }
  purchaseInPaymentEnableListRef.value.open(props.supplierId)
}
const handleAddPurchaseIn = (rows: PurchaseInVO[]) => {
  rows.forEach((row) => {
    formData.value.push({
      bizId: row.id,
      bizType: ErpBizType.PURCHASE_IN,
      bizNo: row.no,
      totalPrice: row.totalPrice,
      paidPrice: row.paymentPrice,
      paymentPrice: row.totalPrice - row.paymentPrice
    })
  })
}

/** 新增【采购退货】按钮操作 */
const purchaseReturnRefundEnableListRef = ref()
const handleOpenPurchaseReturn = () => {
  if (!props.supplierId) {
    message.error('请选择供应商')
    return
  }
  purchaseReturnRefundEnableListRef.value.open(props.supplierId)
}
const handleAddPurchaseReturn = (rows: PurchaseReturnVO[]) => {
  rows.forEach((row) => {
    formData.value.push({
      bizId: row.id,
      bizType: ErpBizType.PURCHASE_RETURN,
      bizNo: row.no,
      totalPrice: -row.totalPrice,
      paidPrice: -row.refundPrice,
      paymentPrice: -row.totalPrice + row.refundPrice
    })
  })
}

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

/** 打开单据详情弹窗 */
const purchaseInFormRef = ref()
const purchaseReturnFormRef = ref()
const openBizDetail = (row: any) => {
  if (row.bizType === ErpBizType.PURCHASE_IN) {
    purchaseInFormRef.value.open('detail', row.bizId)
  } else if (row.bizType === ErpBizType.PURCHASE_RETURN) {
    purchaseReturnFormRef.value.open('detail', row.bizId)
  }
}

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