<template>
  <!-- 移动端布局 -->
  <div v-if="isMobile" class="mobile-sale-out">
    <div class="mobile-header">
      <div class="mobile-header__search"><el-input v-model="queryParams.no" placeholder="搜索出库单号" clearable @keyup.enter="handleQuery" :prefix-icon="Search" /></div>
      <div class="mobile-header__actions">
        <el-button :icon="Filter" circle @click="filterVisible = true" />
        <el-button type="primary" :icon="Plus" circle @click="openForm('create')" v-hasPermi="['erp:sale-out:create']" />
      </div>
    </div>
    <div class="mobile-header__quick-filter">
      <div
        class="quick-filter-item"
        :class="{ active: queryParams.status === undefined }"
        @click="handleQuickFilter(undefined)"
      >
        全部订单
      </div>
      <div
        class="quick-filter-item"
        :class="{ active: queryParams.status === 10 }"
        @click="handleQuickFilter(10)"
      >
        待审核
      </div>
      <div
        class="quick-filter-item"
        :class="{ active: queryParams.status === 20 }"
        @click="handleQuickFilter(20)"
      >
        已审核
      </div>
    </div>


    <!-- 卡片列表 -->
    <div class="mobile-list" v-loading="loading">
      <div v-if="list.length === 0 && !loading" class="mobile-empty">
        <el-empty description="暂无销售出库" />
      </div>
      <div
        v-for="item in list"
        :key="item.id"
        class="mobile-card"
        @click="handleCardClick(item)"
      >
        <div class="mobile-card__header">
          <span class="mobile-card__no">{{ item.no }}</span>
          <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="item.status" />
        </div>
        <div class="mobile-card__body">
          <div class="mobile-card__row">
            <span class="mobile-card__label">客户</span>
            <span class="mobile-card__value">{{ item.customerName || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">产品</span>
            <span class="mobile-card__value mobile-card__value--ellipsis">{{ item.productNames || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">出库时间</span>
            <span class="mobile-card__value">{{ formatDate2(item.outTime) }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">创建人</span>
            <span class="mobile-card__value">{{ item.creatorName || '-' }}</span>
          </div>
          <div class="mobile-card__nums">
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val">{{ erpCountInputFormatter(item.totalCount) }}</div>
              <div class="mobile-card__num-label">总数量</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val mobile-card__num-val--price">¥{{ erpPriceInputFormatter(item.totalPrice) }}</div>
              <div class="mobile-card__num-label">应收</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val">¥{{ erpPriceInputFormatter(item.receiptPrice) }}</div>
              <div class="mobile-card__num-label">已收</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val" :class="{ 'mobile-card__num-val--danger': item.receiptPrice !== item.totalPrice }">
                ¥{{ erpPriceInputFormatter(item.totalPrice - item.receiptPrice) }}
              </div>
              <div class="mobile-card__num-label">未收</div>
            </div>
          </div>
        </div>
        <div class="mobile-card__footer">
          <el-button size="small" @click.stop="openForm('detail', item.id)" v-hasPermi="['erp:sale-out:query']">详情</el-button>
          <el-button size="small" type="primary" @click.stop="openForm('update', item.id)" v-hasPermi="['erp:sale-out:update']" :disabled="item.status === 20">编辑</el-button>
          <el-button size="small" type="primary" @click.stop="handleUpdateStatus(item.id, 20)" v-hasPermi="['erp:sale-out:update-status']" v-if="item.status === 10">审批</el-button>
          <el-button size="small" type="danger" @click.stop="handleUpdateStatus(item.id, 10)" v-hasPermi="['erp:sale-out:update-status']" v-if="item.status === 20">反审批</el-button>
          <el-button size="small" type="danger" @click.stop="handleDelete([item.id])" v-hasPermi="['erp:sale-out:delete']">删除</el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="mobile-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="filterVisible" title="筛选条件" direction="btt" size="70%">
      <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="customerId">
          <el-select v-model="queryParams.customerId" clearable filterable placeholder="请选择客户" style="width:100%">
            <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库时间" prop="outTime">
          <el-date-picker v-model="queryParams.outTime" 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-item label="仓库" prop="warehouseId">
          <el-select v-model="queryParams.warehouseId" clearable filterable placeholder="请选择仓库" style="width:100%">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-select v-model="queryParams.creator" clearable filterable placeholder="请选择创建人" style="width:100%">
            <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width:100%">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ERP_AUDIT_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="收款状态" prop="receiptStatus">
          <el-select v-model="queryParams.receiptStatus" placeholder="请选择" clearable style="width:100%">
            <el-option label="未收款" value="0" />
            <el-option label="部分收款" value="1" />
            <el-option label="全部收款" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleFilterConfirm">确认筛选</el-button>
      </template>
    </el-drawer>

  </div>

  <!-- PC端布局 -->
  <template v-else>
    <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-240px"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="queryParams.productId"
            clearable
            filterable
            placeholder="请选择产品"
            class="!w-240px"
          >
            <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="outTime">
          <el-date-picker
            v-model="queryParams.outTime"
            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-240px"
          />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="queryParams.customerId"
            clearable
            filterable
            placeholder="请选择供客户"
            class="!w-240px"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select
            v-model="queryParams.warehouseId"
            clearable
            filterable
            placeholder="请选择仓库"
            class="!w-240px"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-select
            v-model="queryParams.creator"
            clearable
            filterable
            placeholder="请选择创建人"
            class="!w-240px"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联订单" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入关联订单"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="结算账户" prop="accountId">
          <el-select
            v-model="queryParams.accountId"
            clearable
            filterable
            placeholder="请选择结算账户"
            class="!w-240px"
          >
            <el-option
              v-for="item in accountList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收款状态" prop="receiptStatus">
          <el-select
            v-model="queryParams.receiptStatus"
            placeholder="请选择有款状态"
            clearable
            class="!w-240px"
          >
            <el-option label="未收款" value="0" />
            <el-option label="部分收款" value="1" />
            <el-option label="全部收款" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.ERP_AUDIT_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </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-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['erp:sale-out:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['erp:sale-out:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
          <el-button
            type="danger"
            plain
            @click="handleDelete(selectionList.map((item) => item.id))"
            v-hasPermi="['erp:sale-out:delete']"
            :disabled="selectionList.length === 0"
          >
            <Icon icon="ep:delete" class="mr-5px" /> 删除
          </el-button>
          <el-button
            type="info"
            plain
            @click="handlePrint"
            v-hasPermi="['erp:sale-out:query']"
            :disabled="selectionList.length === 0"
          >
            <Icon icon="ep:printer" class="mr-5px" /> 打印
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <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="productNames" min-width="200" />
        <el-table-column label="客户" align="center" prop="customerName" />
        <el-table-column
          label="出库时间"
          align="center"
          prop="outTime"
          :formatter="dateFormatter2"
          width="120px"
          sortable
        />
        <el-table-column label="创建人" align="center" prop="creatorName" />
        <el-table-column
          label="总数量"
          align="center"
          prop="totalCount"
          :formatter="erpCountTableColumnFormatter"
        />
        <el-table-column
          label="应收金额"
          align="center"
          prop="totalPrice"
          :formatter="erpPriceTableColumnFormatter"
        />
        <el-table-column
          label="已收金额"
          align="center"
          prop="receiptPrice"
          :formatter="erpPriceTableColumnFormatter"
        />
        <el-table-column label="未收金额" align="center">
          <template #default="scope">
            <span v-if="scope.row.receiptPrice === scope.row.totalPrice">0</span>
            <el-tag type="danger" v-else>
              {{ erpPriceInputFormatter(scope.row.totalPrice - scope.row.receiptPrice) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" fixed="right" width="90" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="scope">
            <el-button
              link
              @click="openForm('detail', scope.row.id)"
              v-hasPermi="['erp:sale-out:query']"
            >
              详情
            </el-button>
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['erp:sale-out:update']"
              :disabled="scope.row.status === 20"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleUpdateStatus(scope.row.id, 20)"
              v-hasPermi="['erp:sale-out:update-status']"
              v-if="scope.row.status === 10"
            >
              审批
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleUpdateStatus(scope.row.id, 10)"
              v-hasPermi="['erp:sale-out:update-status']"
              v-else
            >
              反审批
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete([scope.row.id])"
              v-hasPermi="['erp:sale-out:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </template>

  <!-- 表单弹窗：添加/修改 -->
  <SaleOutForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Search, Filter, Plus } from '@element-plus/icons-vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { formatDate, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { SaleOutApi, SaleOutVO } from '@/api/erp/sale/out'
import SaleOutForm from './SaleOutForm.vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { erpCountInputFormatter, erpPriceInputFormatter, erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { ElMessageBox } from 'element-plus'
import { useCache, CACHE_KEY } from '@/hooks/web/useCache'
import { onActivated } from 'vue'
import { useWindowSize } from '@vueuse/core'

/** ERP 销售出库列表 */
defineOptions({ name: 'ErpSaleOut' })

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

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SaleOutVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const filterVisible = ref(false) // 筛选抽屉
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  customerId: undefined,
  productId: undefined,
  warehouseId: undefined,
  outTime: [],
  orderNo: undefined,
  receiptStatus: undefined,
  accountId: undefined,
  status: undefined,
  remark: undefined,
  creator: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<ProductVO[]>([]) // 产品列表
const customerList = ref<CustomerVO[]>([]) // 客户列表
const userList = ref<UserVO[]>([]) // 用户列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const accountList = ref<AccountVO[]>([]) // 账户列表

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

const applyStorageQuery = () => {
  const noValue = sessionStorage.getItem('erp_sale_out_no')
  if (noValue && noValue.trim()) {
    queryParams.no = noValue.trim()
    queryParams.pageNo = 1
    sessionStorage.removeItem('erp_sale_out_no')
    return true
  }
  sessionStorage.removeItem('erp_sale_out_no')
  return false
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SaleOutApi.getSaleOutPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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

/** 筛选确认 */
const handleFilterConfirm = () => {
  filterVisible.value = false
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 卡片点击 */
const handleCardClick = (row: SaleOutVO) => {
  if (row.status === 20) {
    openForm('detail', row.id)
  } else if (row.status === 10) {
    openForm('update', row.id)
  }
}

/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  try {
    await message.delConfirm()
    await SaleOutApi.deleteSaleOut(ids)
    message.success(t('common.delSuccess'))
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

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

/** 行点击操作(PC端) */
const handleRowClick = (row: SaleOutVO, column: any, event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (target.tagName === 'BUTTON' || target.tagName === 'A' || target.tagName === 'I' || target.tagName === 'svg' || target.closest('button') || target.closest('a') || target.closest('.el-button') || target.closest('.el-checkbox')) return
  if (row.status === 20) {
    openForm('detail', row.id)
  } else if (row.status === 10) {
    openForm('update', row.id)
  }
}
/** 审批/反审批操作 */
const handleUpdateStatus = async (id: number, status: number) => {
  try {
    // 审批的二次确认
    await message.confirm(`确定${status === 20 ? '审批' : '反审批'}该出库吗？`)
    // 发起审批
    await SaleOutApi.updateSaleOutStatus(id, status)
    message.success(`${status === 20 ? '审批' : '反审批'}成功`)
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SaleOutApi.exportSaleOut(queryParams)
    download.excel(data, '销售出库.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取打印设置 */
const getPrintSettings = async () => {
  const { wsCache } = useCache()
  const defaultCompanyName = wsCache.get(CACHE_KEY.TenantName) || ''

  const { value: companyName } = await ElMessageBox.prompt('请输入公司名称', '打印设置', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '公司名称',
    inputValue: defaultCompanyName
  })
  if (!companyName) return null

  const { value: creatorName } = await ElMessageBox.prompt('请输入制单人', '打印设置', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '制单人',
    inputValue: ''
  })
  if (creatorName === null) return null

  const { value: createTime } = await ElMessageBox.prompt('请输入制单时间', '打印设置', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '制单时间 (例如: 2023-12-01 10:00:00)',
    inputValue: new Date().toLocaleString('zh-CN')
  })
  if (createTime === null) return null

  return { companyName, creatorName, createTime }
}

/** 打印按钮操作 */
const handlePrint = async () => {
  const printSettings = await getPrintSettings()
  if (!printSettings) return

  const { companyName, creatorName, createTime } = printSettings

  for (let i = 0; i < selectionList.value.length; i++) {
    const out = selectionList.value[i]
    const outDetail = await SaleOutApi.getSaleOut(out.id)
    await printOut(outDetail, companyName, creatorName, createTime)
    if (i < selectionList.value.length - 1) {
      const confirm = await ElMessageBox.confirm('是否继续打印下一张出库单？', '确认', {
        confirmButtonText: '继续',
        cancelButtonText: '停止',
        type: 'warning'
      })
      if (!confirm) break
    }
  }
}

/** 格式化时间戳 */
const formatTimestamp = (timestamp: number | string) => {
  if (!timestamp) return ''
  const date = new Date(Number(timestamp))
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

/** 生成打印HTML */
const generatePrintHtml = (out: any, companyName: string, creatorName: string, createTime: string) => {
  const saleUserName = out.saleUserId
    ? userList.value.find((user) => user.id === out.saleUserId)?.nickname || ''
    : ''
  const accountName = out.accountId
    ? accountList.value.find((account) => account.id === out.accountId)?.name || ''
    : ''
  const items = out.items || []
  const itemRows = items
    .map((item, index) => {
      const productPrice = Number(item.productPrice || 0)
      const totalProductPrice = Number(item.totalProductPrice || productPrice * Number(item.count || 0))
      const totalPrice = Number(
        item.totalPrice != null ? item.totalPrice : totalProductPrice + Number(item.taxPrice || 0)
      )
      const warehouseName = item.warehouseId
        ? warehouseList.value.find((warehouse) => warehouse.id === item.warehouseId)?.name || ''
        : ''
      return `<tr>
      <td>${index + 1}</td>
      <td>${item.productName || ' '}</td>
      <td>${warehouseName || ' '}</td>
      <td>${item.count || '0.00'}</td>
      <td>${item.productUnitName || ' '}</td>
      <td>${productPrice.toFixed(2)}</td>
      <td>${totalProductPrice.toFixed(2)}</td>
      <td>${item.taxPercent != null ? item.taxPercent : '0.00'}</td>
      <td>${totalPrice.toFixed(2)}</td>
    </tr>`
    })
    .join('')

  return `<!DOCTYPE html>
<html>
<head>
  <title>打印销售出库</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #000; padding: 8px; text-align: center; vertical-align: top; }
    h1 { text-align: center; margin-bottom: 20px; }
  </style>
</head>
<body>
  <h1>${companyName}销售出库单</h1>
  <div style="margin-bottom: 20px;">
    <span style='margin-right: 20px;'>制单人：${creatorName}</span>
    <span>制单时间：${createTime}</span>
    <div style="clear: both;"></div>
  </div>
  <table>
    <tr>
      <td colspan="1">出库单号</td>
      <td colspan="3">${out.no || ''}</td>
      <td colspan="1">客户</td>
      <td colspan="4">${out.customerName || ''}</td>
    </tr>
    <tr>
      <td colspan="1">出库时间</td>
      <td colspan="3">${formatTimestamp(out.outTime)}</td>
      <td colspan="1">销售员</td>
      <td colspan="4">${saleUserName}</td>
    </tr>
    <tr>
      <td colspan="1">关联订单</td>
      <td colspan="3">${out.orderNo || ''}</td>
      <td colspan="1">结算账户</td>
      <td colspan="4">${accountName}</td>
    </tr>
    <tr>
      <th colspan="9">出库明细</th>
    </tr>
    <tr>
      <th>序号</th>
      <th>产品名称</th>
      <th>仓库</th>
      <th>数量</th>
      <th>单位</th>
      <th>产品单价（￥）</th>
      <th>金额（￥）</th>
      <th>税率（%）</th>
      <th>税额合计（￥）</th>
    </tr>
    ${itemRows}
  </table>
</body>
</html>`
}

/** 打印单个出库单 */
const printOut = (out: any, companyName: string, creatorName: string, createTime: string) => {
  const html = generatePrintHtml(out, companyName, creatorName, createTime)
  const printWindow = window.open('', '_blank')
  printWindow.document.write(html)
  printWindow.document.close()
  printWindow.print()
}

/** 初始化 **/
onMounted(async () => {
  applyStorageQuery()
  await getList()
  // 加载产品、仓库列表、客户
  productList.value = await ProductApi.getProductSimpleList()
  customerList.value = await CustomerApi.getCustomerSimpleList()
  userList.value = await UserApi.getSimpleUserList()
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  accountList.value = await AccountApi.getAccountSimpleList()
})

onActivated(() => {
  if (applyStorageQuery()) {
    getList()
  }
})

/** 快捷分类筛选 */
const handleQuickFilter = (status: number | undefined) => {
  queryParams.status = status
  queryParams.pageNo = 1
  getList()
}
// TODO 芋艿：可优化功能：列表界面，支持导入
// TODO 芋艿：可优化功能：详情界面，支持打印
</script>

<style lang="scss" scoped>

.mobile-header__quick-filter {
  display: flex;
  gap: 12px;
  margin: 8px 0;
  justify-content: flex-start;

  .quick-filter-item {
    padding: 4px 12px;
    font-size: 14px;
    border-radius: 20px;
    cursor: pointer;
    color: #909399;
    background: transparent;
    transition: all 0.2s;

    &.active {
      color: #fff;
      background: #409eff;
    }
  }
}

.mobile-sale-out {
  padding: 12px;
  background: #f5f5f5;
  min-height: 100vh;
}

.mobile-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;

  &__search {
    flex: 1;
  }

  &__actions {
    display: flex;
    gap: 4px;
    flex-shrink: 0;
  }
}

.mobile-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.mobile-empty {
  padding: 40px 0;
}

.mobile-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  &__no {
    font-weight: 600;
    font-size: 15px;
    color: #303133;
  }

  &__body {
    font-size: 13px;
  }

  &__row {
    display: flex;
    justify-content: space-between;
    padding: 3px 0;
  }

  &__label {
    color: #909399;
    flex-shrink: 0;
    margin-right: 12px;
  }

  &__value {
    color: #606266;
    text-align: right;

    &--ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 200px;
    }
  }

  &__nums {
    display: flex;
    justify-content: space-around;
    margin-top: 10px;
    padding: 10px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
  }

  &__num-item {
    text-align: center;
  }

  &__num-val {
    font-size: 15px;
    font-weight: 600;
    color: #303133;

    &--price {
      color: #e6a23c;
    }

    &--danger {
      color: #f56c6c;
    }
  }

  &__num-label {
    font-size: 11px;
    color: #909399;
    margin-top: 2px;
  }

  &__footer {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 10px;
  }
}

.mobile-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
