<!-- 可退款的采购退货单列表 -->
<template>
  <!-- 移动端布局 -->
  <el-drawer v-if="isMobile" 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.returnTime) }}</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.refundPrice) }}</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.refundPrice === item.totalPrice ? '#909399' : '#f56c6c' }">¥{{ erpPriceInputFormatter(item.totalPrice - item.refundPrice) }}</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="returnTime">
          <el-date-picker v-model="queryParams.returnTime" 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>

  <!-- PC端布局 -->
  <Dialog v-else title="选择采购退货（仅展示可退款）" v-model="dialogVisible" :appendToBody="true" :scroll="true" width="1080">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="退货单号" prop="no">
          <el-input v-model="queryParams.no" placeholder="请输入退货单号" clearable @keyup.enter="handleQuery" class="!w-160px" />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="queryParams.productId" clearable filterable placeholder="请选择产品" class="!w-160px">
            <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="orderTime">
          <el-date-picker v-model="queryParams.returnTime" 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')]" class="!w-160px" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <ContentWrap>
      <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true" @selection-change="handleSelectionChange">
        <el-table-column width="30" label="选择" type="selection" />
        <el-table-column min-width="180" label="退货单号" align="center" prop="no" />
        <el-table-column label="供应商" align="center" prop="supplierName" />
        <el-table-column label="产品信息" align="center" prop="productNames" min-width="200" />
        <el-table-column label="退货时间" align="center" prop="returnTime" :formatter="dateFormatter2" width="120px" />
        <el-table-column label="创建人" align="center" prop="creatorName" />
        <el-table-column label="应退金额" align="center" prop="totalPrice" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column label="已退金额" align="center" prop="refundPrice" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column label="未退金额" align="center">
          <template #default="scope">
            <span v-if="scope.row.refundPrice === scope.row.totalPrice">0</span>
            <el-tag type="danger" v-else>{{ erpPriceInputFormatter(scope.row.totalPrice - scope.row.refundPrice) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
    <template #footer>
      <el-button :disabled="!selectionList.length" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { Search, Filter } from '@element-plus/icons-vue'
import { ElTable } from 'element-plus'
import { dateFormatter2, formatDate } from '@/utils/formatTime'
import { erpPriceInputFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { PurchaseReturnApi, PurchaseReturnVO } from '@/api/erp/purchase/return'
import { SaleReturnVO } from '@/api/erp/sale/return'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'PurchaseReturnRefundEnableList' })

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

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

/** 移动端选中操作 */
const isSelected = (item: PurchaseReturnVO) => {
  return selectionList.value.some((s) => s.id === item.id)
}
const toggleSelect = (item: PurchaseReturnVO) => {
  const idx = selectionList.value.findIndex((s) => s.id === item.id)
  if (idx >= 0) {
    selectionList.value.splice(idx, 1)
  } else {
    selectionList.value.push(item)
  }
}

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

/** 选中操作 */
const selectionList = ref<SaleReturnVO[]>([])
const handleSelectionChange = (rows: SaleReturnVO[]) => {
  selectionList.value = rows
}

/** 打开弹窗 */
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: SaleReturnVO[]): void
}>()
const submitForm = () => {
  try {
    emits('success', selectionList.value)
  } finally {
    // 关闭弹窗
    dialogVisible.value = false
  }
}

/** 加载列表  */
const getList = async () => {
  loading.value = true
  try {
    const data = await PurchaseReturnApi.getPurchaseReturnPage(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>
