<!-- 可付款的采购入库单列表 -->
<template>
  <el-drawer
    v-model="dialogVisible"
    title="选择采购入库（仅展示可付款）"
    direction="rtl"
    size="100%"
    :append-to-body="true"
    class="mobile-enable-drawer"
  >
    <!-- 搜索栏 -->
    <div class="mobile-enable__search">
      <el-input
        v-model="queryParams.no"
        placeholder="搜索入库单号"
        clearable
        @keyup.enter="handleQuery"
        :prefix-icon="Search"
      />
      <el-button :icon="Filter" circle @click="enableFilterVisible = true" />
    </div>

    <!-- 卡片列表 -->
    <div class="mobile-enable__list" v-loading="loading">
      <div v-if="list.length === 0 && !loading" class="mobile-enable__empty">
        <el-empty description="暂无可付款入库单" />
      </div>
      <div
        v-for="item in list"
        :key="item.id"
        class="mobile-enable__card"
        :class="{ 'mobile-enable__card--selected': isSelected(item) }"
        @click="toggleSelect(item)"
      >
        <div class="mobile-enable__card-check">
          <el-checkbox :model-value="isSelected(item)" @click.stop />
        </div>
        <div class="mobile-enable__card-content">
          <div class="mobile-enable__card-header">
            <span class="mobile-enable__card-no">{{ item.no }}</span>
          </div>
          <div class="mobile-enable__card-row">
            <span class="mobile-enable__card-label">供应商</span>
            <span class="mobile-enable__card-value">{{ item.supplierName || '-' }}</span>
          </div>
          <div class="mobile-enable__card-row">
            <span class="mobile-enable__card-label">产品</span>
            <span class="mobile-enable__card-value mobile-enable__card-value--ellipsis">{{ item.productNames || '-' }}</span>
          </div>
          <div class="mobile-enable__card-row">
            <span class="mobile-enable__card-label">入库时间</span>
            <span class="mobile-enable__card-value">{{ formatDate2(item.inTime) }}</span>
          </div>
          <div class="mobile-enable__card-row">
            <span class="mobile-enable__card-label">创建人</span>
            <span class="mobile-enable__card-value">{{ item.creatorName || '-' }}</span>
          </div>
          <div class="mobile-enable__card-nums">
            <div class="mobile-enable__card-num">
              <div class="mobile-enable__card-num-val">¥{{ erpPriceInputFormatter(item.totalPrice) }}</div>
              <div class="mobile-enable__card-num-label">应付</div>
            </div>
            <div class="mobile-enable__card-num">
              <div class="mobile-enable__card-num-val" style="color:#67c23a">¥{{ erpPriceInputFormatter(item.paymentPrice) }}</div>
              <div class="mobile-enable__card-num-label">已付</div>
            </div>
            <div class="mobile-enable__card-num">
              <div class="mobile-enable__card-num-val" :style="{ color: item.paymentPrice === item.totalPrice ? '#909399' : '#f56c6c' }">
                ¥{{ erpPriceInputFormatter(item.totalPrice - item.paymentPrice) }}
              </div>
              <div class="mobile-enable__card-num-label">未付</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="mobile-enable__pagination" v-if="total > 0">
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" :page-sizes="[10, 20]" layout="total, prev, pager, next" :pager-count="5" @pagination="getList" />
    </div>

    <!-- 筛选抽屉 -->
    <el-drawer v-model="enableFilterVisible" title="筛选条件" direction="btt" size="50%" :append-to-body="true">
      <el-form :model="queryParams" ref="queryFormRef" label-position="top">
        <el-form-item label="产品" prop="productId">
          <el-select v-model="queryParams.productId" clearable filterable 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>
        <el-form-item label="入库时间" prop="inTime">
          <el-date-picker v-model="queryParams.inTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange" start-placeholder="开始" end-placeholder="结束" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="enableFilterVisible = false; handleQuery()">确认筛选</el-button>
      </template>
    </el-drawer>

    <template #footer>
      <div class="mobile-enable__footer">
        <span class="mobile-enable__footer-info">已选 {{ selectionList.length }} 项</span>
        <div>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button :disabled="!selectionList.length" type="primary" @click="submitForm">
            确 定
          </el-button>
        </div>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { Search, Filter } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/formatTime'
import { erpPriceInputFormatter } from '@/utils'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { PurchaseInApi, PurchaseInVO } from '@/api/erp/purchase/in'

defineOptions({ name: 'PurchaseInPaymentEnableList' })

const list = ref<PurchaseInVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  productId: undefined,
  inTime: [],
  paymentEnable: true,
  supplierId: undefined
})
const queryFormRef = ref() // 搜索的表单
const productList = ref<ProductVO[]>([]) // 产品列表
const enableFilterVisible = ref(false) // 筛选抽屉

const formatDate2 = (date: any) => {
  if (!date) return '-'
  return formatDate(new Date(date), 'YYYY-MM-DD')
}

/** 选中操作 */
const selectionList = ref<PurchaseInVO[]>([])
const isSelected = (item: PurchaseInVO) => {
  return selectionList.value.some((s) => s.id === item.id)
}
const toggleSelect = (item: PurchaseInVO) => {
  const idx = selectionList.value.findIndex((s) => s.id === item.id)
  if (idx >= 0) {
    selectionList.value.splice(idx, 1)
  } else {
    selectionList.value.push(item)
  }
}

/** 打开弹窗 */
const open = async (supplierId: number) => {
  dialogVisible.value = true
  await nextTick() // 等待，避免 queryFormRef 为空
  // 加载可入库的订单列表
  queryParams.supplierId = supplierId
  await resetQuery()
  // 加载产品列表
  productList.value = await ProductApi.getProductSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交选择 */
const emits = defineEmits<{
  (e: 'success', value: PurchaseInVO[]): void
}>()
const submitForm = () => {
  try {
    emits('success', selectionList.value)
  } finally {
    // 关闭弹窗
    dialogVisible.value = false
  }
}

/** 加载列表  */
const getList = async () => {
  loading.value = true
  try {
    const data = await PurchaseInApi.getPurchaseInPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  selectionList.value = []
  getList()
}
</script>

<style lang="scss" scoped>
.mobile-enable__search {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
  .el-input { flex: 1; }
}
.mobile-enable__list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-enable__empty {
  padding: 40px 0;
}
.mobile-enable__card {
  display: flex;
  gap: 10px;
  background: #fff;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  border: 2px solid transparent;
  transition: border-color 0.2s;
  &--selected {
    border-color: #409eff;
    background: #f0f7ff;
  }
}
.mobile-enable__card-check {
  display: flex;
  align-items: flex-start;
  padding-top: 2px;
}
.mobile-enable__card-content {
  flex: 1;
  min-width: 0;
}
.mobile-enable__card-header {
  margin-bottom: 6px;
}
.mobile-enable__card-no {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}
.mobile-enable__card-row {
  display: flex;
  justify-content: space-between;
  padding: 2px 0;
  font-size: 13px;
}
.mobile-enable__card-label {
  color: #909399;
  flex-shrink: 0;
  margin-right: 12px;
}
.mobile-enable__card-value {
  color: #606266;
  text-align: right;
  &--ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 180px;
  }
}
.mobile-enable__card-nums {
  display: flex;
  justify-content: space-around;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}
.mobile-enable__card-num {
  text-align: center;
}
.mobile-enable__card-num-val {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}
.mobile-enable__card-num-label {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}
.mobile-enable__pagination {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  :deep(.el-pagination) { flex-wrap: wrap; justify-content: center; }
}
.mobile-enable__footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.mobile-enable__footer-info {
  font-size: 13px;
  color: #909399;
}
</style>
