<!-- 可退款的销售退货单列表 -->
<template>
  <!-- 移动端布局 -->
  <el-drawer
    v-if="isMobile"
    v-model="dialogVisible"
    title="选择销售退货（仅展示可退款）"
    direction="rtl"
    size="100%"
    :close-on-press-escape="true"
    :destroy-on-close="true"
  >
    <div class="mobile-enable-list">
      <!-- 搜索栏 -->
      <div class="mobile-enable-list__search">
        <el-input
          v-model="queryParams.no"
          placeholder="搜索退货单号"
          clearable
          @keyup.enter="handleQuery"
          :prefix-icon="Search"
        />
        <el-button :icon="Filter" circle @click="filterVisible = true" />
      </div>

      <!-- 卡片列表 -->
      <div class="mobile-enable-list__body" v-loading="loading">
        <el-empty v-if="list.length === 0 && !loading" description="暂无可退款退货单" />
        <div
          v-for="item in list"
          :key="item.no"
          class="mobile-enable-list__card"
          :class="{ 'mobile-enable-list__card--selected': selectionList.includes(item) }"
          @click="handleToggleSelection(item)"
        >
          <div class="mobile-enable-list__card-check">
            <el-checkbox :model-value="selectionList.includes(item)" />
          </div>
          <div class="mobile-enable-list__card-content">
            <div class="mobile-enable-list__card-no">{{ item.no }}</div>
            <div class="mobile-enable-list__card-row">
              <span class="mobile-enable-list__card-label">客户</span>
              <span>{{ item.customerName || '-' }}</span>
            </div>
            <div class="mobile-enable-list__card-row">
              <span class="mobile-enable-list__card-label">产品</span>
              <span class="mobile-enable-list__card-ellipsis">{{ item.productNames || '-' }}</span>
            </div>
            <div class="mobile-enable-list__card-row">
              <span class="mobile-enable-list__card-label">退货时间</span>
              <span>{{ formatDate2(item.returnTime) }}</span>
            </div>
            <div class="mobile-enable-list__card-nums">
              <div class="mobile-enable-list__card-num">
                <div class="mobile-enable-list__card-num-val mobile-enable-list__card-num-val--price">
                  ¥{{ erpPriceInputFormatter(item.totalPrice) }}
                </div>
                <div class="mobile-enable-list__card-num-label">应退金额</div>
              </div>
              <div class="mobile-enable-list__card-num">
                <div class="mobile-enable-list__card-num-val mobile-enable-list__card-num-val--price">
                  ¥{{ erpPriceInputFormatter(item.refundPrice || 0) }}
                </div>
                <div class="mobile-enable-list__card-num-label">已退金额</div>
              </div>
              <div class="mobile-enable-list__card-num">
                <div class="mobile-enable-list__card-num-val mobile-enable-list__card-num-val--price">
                  <span v-if="(item.refundPrice || 0) >= item.totalPrice">0</span>
                  <el-tag v-else type="danger">
                    ¥{{ erpPriceInputFormatter(item.totalPrice - (item.refundPrice || 0)) }}
                  </el-tag>
                </div>
                <div class="mobile-enable-list__card-num-label">未退金额</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mobile-enable-list__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>
    </div>

    <!-- 筛选抽屉 -->
    <el-drawer v-model="filterVisible" title="筛选条件" direction="btt" size="60%" :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="['00:00:00', '23:59:59']"
            style="width:100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="filterVisible = false; handleQuery()">确认筛选</el-button>
      </template>
    </el-drawer>

    <template #footer>
      <el-button :disabled="!selectionList.length" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>

  <!-- PC端布局 -->
  <el-dialog v-else v-model="dialogVisible" title="选择销售退货（仅展示可退款）" width="900px" :close-on-press-escape="true" :destroy-on-close="true">
    <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>
        <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>
    <el-table v-loading="loading" :data="list" :stripe="true" @selection-change="handleSelectionChange" style="margin-top:16px">
      <el-table-column type="selection" width="50" />
      <el-table-column label="退货单号" align="center" prop="no" min-width="160" />
      <el-table-column label="客户" align="center" prop="customerName" width="120" />
      <el-table-column label="产品" align="center" prop="productNames" min-width="150" show-overflow-tooltip />
      <el-table-column label="退货时间" align="center" prop="returnTime" width="110" :formatter="(row) => formatDate2(row.returnTime)" />
      <el-table-column label="应退金额" align="center" prop="totalPrice" width="100"><template #default="scope"><span style="color:#e6a23c">¥{{ erpPriceInputFormatter(scope.row.totalPrice) }}</span></template></el-table-column>
      <el-table-column label="已退金额" align="center" prop="refundPrice" width="100"><template #default="scope">¥{{ erpPriceInputFormatter(scope.row.refundPrice || 0) }}</template></el-table-column>
      <el-table-column label="未退金额" align="center" width="100"><template #default="scope"><el-tag v-if="(scope.row.refundPrice || 0) < scope.row.totalPrice" type="danger">¥{{ erpPriceInputFormatter(scope.row.totalPrice - (scope.row.refundPrice || 0)) }}</el-tag><span v-else>0</span></template></el-table-column>
    </el-table>
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button :disabled="!selectionList.length" type="primary" @click="submitForm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { Search, Filter } from '@element-plus/icons-vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { SaleReturnApi, SaleReturnVO } from '@/api/erp/sale/return'
import { formatDate } from '@/utils/formatTime'
import { erpPriceInputFormatter } from '@/utils'
import { useWindowSize } from '@vueuse/core'

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

const list = ref<SaleReturnVO[]>([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const filterVisible = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  productId: undefined,
  returnTime: [],
  refundEnable: true,
  customerId: undefined
})
const queryFormRef = ref()
const productList = ref<ProductVO[]>([])
const selectionList = ref<SaleReturnVO[]>([])

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

// 切换选中状态
const handleToggleSelection = (row: SaleReturnVO) => {
  const index = selectionList.value.indexOf(row)
  if (index > -1) selectionList.value.splice(index, 1)
  else selectionList.value.push(row)
}

/** 打开弹窗 */
const open = async (customerId: number) => {
  dialogVisible.value = true
  await nextTick()
  queryParams.customerId = customerId
  await resetQuery()
  productList.value = await ProductApi.getProductSimpleList()
}
defineExpose({ 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 SaleReturnApi.getSaleReturnPage(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()
}

/** PC端表格选中变化 */
const handleSelectionChange = (rows: SaleReturnVO[]) => {
  selectionList.value = rows
}
</script>

<style lang="scss" scoped>
/* 与其他订单列表相同样式 */
.mobile-enable-list {
  padding: 12px;
  &__search {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 12px;
  }
  &__body {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  &__card {
    display: flex;
    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: var(--el-color-primary);
    }
  }
  &__card-check {
    flex-shrink: 0;
    padding-right: 8px;
    display: flex;
    align-items: flex-start;
    padding-top: 2px;
  }
  &__card-content {
    flex: 1;
    min-width: 0;
  }
  &__card-no {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
    margin-bottom: 6px;
  }
  &__card-row {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    color: #606266;
    padding: 2px 0;
  }
  &__card-label {
    color: #909399;
    flex-shrink: 0;
    margin-right: 10px;
  }
  &__card-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 180px;
    text-align: right;
  }
  &__card-nums {
    display: flex;
    justify-content: space-around;
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
  }
  &__card-num {
    text-align: center;
  }
  &__card-num-val {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    &--price {
      color: #e6a23c;
    }
  }
  &__card-num-label {
    font-size: 11px;
    color: #909399;
    margin-top: 2px;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: center;
    :deep(.el-pagination) {
      flex-wrap: wrap;
      justify-content: center;
    }
  }
}
</style>
