<!-- 可退货的订单列表 -->
<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.id"
          class="mobile-enable-list__card"
          :class="{ 'mobile-enable-list__card--selected': currentRowValue === item.id }"
          @click="handleCurrentChange(item)"
        >
          <div class="mobile-enable-list__card-check">
            <el-radio :value="item.id" v-model="currentRowValue">&nbsp;</el-radio>
          </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.supplierName || '-' }}</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.orderTime) }}</span>
            </div>
            <div class="mobile-enable-list__card-nums">
              <div class="mobile-enable-list__card-num">
                <div class="mobile-enable-list__card-num-val">{{ erpCountInputFormatter(item.totalCount) }}</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">{{ erpCountInputFormatter(item.inCount) }}</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">{{ erpCountInputFormatter(item.returnCount) }}</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.totalPrice) }}</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="orderTime">
          <el-date-picker
            v-model="queryParams.orderTime"
            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="filterVisible = false; handleQuery()">确认筛选</el-button>
      </template>
    </el-drawer>

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

  <!-- PC端布局 -->
  <Dialog v-else title="选择采购订单（仅展示可退货）" v-model="dialogVisible" :appendToBody="true" :scroll="true" width="1100">
    <ContentWrap>
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="-mb-15px">
        <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.orderTime" 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">
        <el-table-column align="center" width="65"><template #default="{ row }"><el-radio :value="row.id" v-model="currentRowValue" @change="handleCurrentChange(row)">&nbsp;</el-radio></template></el-table-column>
        <el-table-column label="订单单号" align="center" prop="no" min-width="180" />
        <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="orderTime" :formatter="dateFormatter2" width="120px" />
        <el-table-column label="总数量" align="center" prop="totalCount" :formatter="erpCountTableColumnFormatter" />
        <el-table-column label="入库数量" align="center" prop="inCount" :formatter="erpCountTableColumnFormatter" />
        <el-table-column label="退货数量" align="center" prop="returnCount" :formatter="erpCountTableColumnFormatter" />
        <el-table-column label="金额合计" align="center" prop="totalProductPrice" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column label="含税金额" align="center" prop="totalPrice" :formatter="erpPriceTableColumnFormatter" />
      </el-table>
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </ContentWrap>
    <template #footer>
      <el-button :disabled="!currentRow" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { Search, Filter } from '@element-plus/icons-vue'
import { PurchaseOrderApi, PurchaseOrderVO } from '@/api/erp/purchase/order'
import { formatDate, dateFormatter2 } from '@/utils/formatTime'
import { erpCountInputFormatter, erpPriceInputFormatter, erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'PurchaseOrderReturnEnableList' })

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

const list = ref<PurchaseOrderVO[]>([]) // 列表的数据
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,
  orderTime: [],
  returnEnable: true
})
const queryFormRef = ref() // 搜索的表单
const productList = ref<ProductVO[]>([]) // 产品列表

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

/** 选中行 */
const currentRowValue = ref(undefined) // 选中行的 value
const currentRow = ref(undefined) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
  currentRowValue.value = row.id
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  await nextTick()
  await resetQuery()
  productList.value = await ProductApi.getProductSimpleList()
}
defineExpose({ open })

/** 提交选择 */
const emits = defineEmits<{
  (e: 'success', value: PurchaseOrderVO): void
}>()
const submitForm = () => {
  try {
    emits('success', currentRow.value)
  } finally {
    dialogVisible.value = false
  }
}

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  currentRowValue.value = undefined
  currentRow.value = undefined
  getList()
}
</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>
