<template>
  <!-- 移动端布局 -->
  <div v-if="isMobile" class="mobile-sale-outwarehouse">
    <!-- 顶部操作栏 -->
    <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-outwarehouse:create']"
        />
      </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.itemList && item.itemList.length > 0 ? getUniqueProductNames(item.itemList).join(', ') : '-' }}
            </span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">出库时间</span>
            <span class="mobile-card__value">{{ formatDate(item.outTime, 'YYYY-MM-DD') }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">仓库</span>
            <span class="mobile-card__value">{{ item.warehouseNames || item.warehouseName || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">收款状态</span>
            <dict-tag :type="DICT_TYPE.ERP_RECEIPT_STATUS" :value="item.receiptStatus" />
          </div>
          <div class="mobile-card__nums">
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val">{{ erpCountTableColumnFormatter(null, null, item.totalCount, null) }}</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">¥{{ erpPriceTableColumnFormatter(null, null, item.totalPrice, null) }}</div>
              <div class="mobile-card__num-label">合计</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val">¥{{ erpPriceTableColumnFormatter(null, null, item.receiptPrice, null) }}</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.totalPrice || 0) - (item.receiptPrice || 0) > 0 }">
                ¥{{ erpPriceTableColumnFormatter(null, null, (item.totalPrice || 0) - (item.receiptPrice || 0), null) }}
              </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-outwarehouse:query']">详情</el-button>
          <el-button size="small" type="primary" @click.stop="openForm('update', item.id)" v-hasPermi="['erp:sale-outwarehouse:update']" :disabled="item.status === 20">修改</el-button>
          <el-button size="small" type="primary" @click.stop="handleUpdateStatus(item.id, item.status === 10 ? 20 : 10)" v-if="item.status === 10 || item.status === 20" v-hasPermi="['erp:sale-outwarehouse:update-status']">
            {{ item.status === 10 ? '审核' : '反审核' }}
          </el-button>
          <el-button size="small" type="success" @click.stop="openReceiptForm(item)" v-if="item.status === 20" v-hasPermi="['erp:sale-outwarehouse:update']">收款</el-button>
          <el-button size="small" type="danger" @click.stop="handleDelete(item.id)" v-hasPermi="['erp:sale-outwarehouse: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="status">
          <el-select v-model="queryParams.status" clearable placeholder="请选择状态" style="width:100%">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ERP_SALE_OUT_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" clearable placeholder="请选择收款状态" style="width:100%">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ERP_RECEIPT_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户" prop="accountId">
          <el-select v-model="queryParams.accountId" clearable filterable placeholder="请选择账户" style="width:100%">
            <el-option v-for="item in accountList" :key="item.id" :label="item.name" :value="item.id" />
          </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>

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

    <!-- 收款表单弹窗 -->
    <el-dialog v-model="receiptDialogVisible" title="收款" width="90%" @closed="receiptDialogVisible = false">
      <div v-if="currentOutwarehouse">
        <div class="mobile-receipt-info">
          <div class="mobile-receipt-info__row">
            <span class="mobile-receipt-info__label">单号</span>
            <span>{{ currentOutwarehouse.no }}</span>
          </div>
          <div class="mobile-receipt-info__row">
            <span class="mobile-receipt-info__label">客户</span>
            <span>{{ currentOutwarehouse.customerName }}</span>
          </div>
          <div class="mobile-receipt-info__row">
            <span class="mobile-receipt-info__label">合计金额</span>
            <span>{{ erpPriceTableColumnFormatter(null, null, currentOutwarehouse.totalPrice, null) }}</span>
          </div>
          <div class="mobile-receipt-info__row">
            <span class="mobile-receipt-info__label">已收款</span>
            <span>{{ erpPriceTableColumnFormatter(null, null, currentOutwarehouse.receiptPrice, null) }}</span>
          </div>
          <div class="mobile-receipt-info__row">
            <span class="mobile-receipt-info__label">未收款</span>
            <span class="mobile-receipt-info__danger">{{ erpPriceTableColumnFormatter(null, null, (currentOutwarehouse.totalPrice || 0) - (currentOutwarehouse.receiptPrice || 0), null) }}</span>
          </div>
        </div>

        <el-form :model="receiptForm" label-position="top" style="margin-top: 12px">
          <el-form-item label="收款金额" required>
            <el-input-number
              v-model="receiptForm.amount"
              :min="0"
              :precision="2"
              :step="0.01"
              :max="(currentOutwarehouse.totalPrice || 0) - (currentOutwarehouse.receiptPrice || 0)"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="收款日期" required>
            <el-date-picker v-model="receiptForm.date" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="receiptForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
          </el-form-item>
        </el-form>

        <div style="margin-top: 12px">
          <div style="font-weight: 600; margin-bottom: 8px">收款记录</div>
          <div v-if="receiptHistory.length > 0">
            <div v-for="(record, idx) in receiptHistory" :key="idx" class="mobile-receipt-record">
              <div class="mobile-receipt-record__row">
                <span>{{ record.date }}</span>
                <span class="mobile-receipt-record__amount">¥{{ erpPriceTableColumnFormatter(null, null, record.amount, null) }}</span>
              </div>
              <div class="mobile-receipt-record__detail" v-if="record.remark">{{ record.remark }}</div>
            </div>
          </div>
          <div v-else style="text-align: center; padding: 16px; color: #909399;">暂无收款记录</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="receiptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReceipt">确定</el-button>
      </template>
    </el-dialog>
  </div>

  <!-- PC端布局 -->
  <div 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="status">
          <el-select
            v-model="queryParams.status"
            clearable
            placeholder="请选择状态"
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.ERP_SALE_OUT_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"
            clearable
            placeholder="请选择收款状态"
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.ERP_RECEIPT_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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="remark">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="创建者" prop="creator">
          <el-input
            v-model="queryParams.creator"
            placeholder="请输入创建者"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" /> 重置</el-button>
          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['erp:sale-outwarehouse:create']"
          >
            <Icon icon="ep:plus" /> 新增
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['erp:sale-outwarehouse:export']"
          >
            <Icon icon="ep:download" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list"  @row-click="handleRowClick">
        <el-table-column label="出库单号" align="center" prop="no" min-width="180">
          <template #default="scope">
            <span>{{ scope.row.no }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户" align="center" prop="customerName" min-width="180">
          <template #default="scope">
            <span>{{ scope.row.customerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品" align="center" min-width="120">
          <template #default="scope">
            <div v-if="scope.row.itemList && scope.row.itemList.length > 0">
              <div v-for="(productName, index) in getUniqueProductNames(scope.row.itemList)" :key="index" class="mb-1">
                {{ productName }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="出库时间" align="center" prop="outTime" min-width="180" sortable>
          <template #default="scope">
            <span>{{ formatDate(scope.row.outTime, 'YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库" align="center" prop="warehouseNames" min-width="180">
          <template #default="scope">
            <div v-if="scope.row.warehouseNames">
              <div v-for="(warehouse, index) in scope.row.warehouseNames.split(',')" :key="index">
                {{ warehouse }}
              </div>
            </div>
            <span v-else>{{ scope.row.warehouseName || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合计数量" align="center" prop="totalCount" min-width="100">
          <template #default="scope">
            <span>{{ erpCountTableColumnFormatter(null, null, scope.row.totalCount, null) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合计金额" align="center" prop="totalPrice" min-width="120">
          <template #default="scope">
            <span>{{ erpPriceTableColumnFormatter(null, null, scope.row.totalPrice, null) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收款状态" align="center" prop="receiptStatus" min-width="100">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.ERP_RECEIPT_STATUS" :value="scope.row.receiptStatus" />
          </template>
        </el-table-column>
        <el-table-column label="已收款金额" align="center" prop="receiptPrice" min-width="120">
          <template #default="scope">
            <span>{{ erpPriceTableColumnFormatter(null, null, scope.row.receiptPrice, null) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出库状态" align="center" prop="status" min-width="100">
          <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"
          width="350"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['erp:sale-outwarehouse:update']"
              :disabled="scope.row.status === 20"
            >
              <Icon icon="ep:edit" />修改
            </el-button>
            <el-button
              link
              type="primary"
              @click="openForm('detail', scope.row.id)"
              v-hasPermi="['erp:sale-outwarehouse:query']"
            >
              <Icon icon="ep:view" />详情
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleUpdateStatus(scope.row.id, scope.row.status === 10 ? 20 : 10)"
              v-if="scope.row.status === 10 || scope.row.status === 20"
              v-hasPermi="['erp:sale-outwarehouse:update-status']"
            >
              <Icon icon="ep:check" />{{ scope.row.status === 10 ? '审核' : '反审核' }}
            </el-button>
            <el-button
              link
              type="success"
              @click="openReceiptForm(scope.row)"
              v-if="scope.row.status === 20"
              v-hasPermi="['erp:sale-outwarehouse:update']"
            >
              <Icon icon="ep:money" />收款
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['erp:sale-outwarehouse:delete']"
            >
              <Icon icon="ep: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>

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

    <!-- 收款表单弹窗 -->
    <el-dialog v-model="receiptDialogVisible" title="收款" width="500px" @closed="receiptDialogVisible = false">
      <div v-if="currentOutwarehouse">
        <div class="mobile-receipt-info">
          <div class="mobile-receipt-info__row"><span class="mobile-receipt-info__label">单号</span><span>{{ currentOutwarehouse.no }}</span></div>
          <div class="mobile-receipt-info__row"><span class="mobile-receipt-info__label">客户</span><span>{{ currentOutwarehouse.customerName }}</span></div>
          <div class="mobile-receipt-info__row"><span class="mobile-receipt-info__label">合计金额</span><span>{{ erpPriceTableColumnFormatter(null, null, currentOutwarehouse.totalPrice, null) }}</span></div>
          <div class="mobile-receipt-info__row"><span class="mobile-receipt-info__label">已收款</span><span>{{ erpPriceTableColumnFormatter(null, null, currentOutwarehouse.receiptPrice, null) }}</span></div>
          <div class="mobile-receipt-info__row"><span class="mobile-receipt-info__label">未收款</span><span class="mobile-receipt-info__danger">{{ erpPriceTableColumnFormatter(null, null, (currentOutwarehouse.totalPrice || 0) - (currentOutwarehouse.receiptPrice || 0), null) }}</span></div>
        </div>
        <el-form :model="receiptForm" label-width="80px" style="margin-top: 12px">
          <el-form-item label="收款金额" required><el-input-number v-model="receiptForm.amount" :min="0" :precision="2" :step="0.01" :max="(currentOutwarehouse.totalPrice || 0) - (currentOutwarehouse.receiptPrice || 0)" style="width: 100%" /></el-form-item>
          <el-form-item label="收款日期" required><el-date-picker v-model="receiptForm.date" type="date" value-format="YYYY-MM-DD" style="width: 100%" /></el-form-item>
          <el-form-item label="备注"><el-input v-model="receiptForm.remark" type="textarea" :rows="2" placeholder="请输入备注" /></el-form-item>
        </el-form>
        <div style="margin-top: 12px">
          <div style="font-weight: 600; margin-bottom: 8px">收款记录</div>
          <div v-if="receiptHistory.length > 0">
            <div v-for="(record, idx) in receiptHistory" :key="idx" class="mobile-receipt-record">
              <div class="mobile-receipt-record__row"><span>{{ record.date }}</span><span class="mobile-receipt-record__amount">¥{{ erpPriceTableColumnFormatter(null, null, record.amount, null) }}</span></div>
              <div class="mobile-receipt-record__detail" v-if="record.remark">{{ record.remark }}</div>
            </div>
          </div>
          <div v-else style="text-align: center; padding: 16px; color: #909399;">暂无收款记录</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="receiptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReceipt">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { Search, Filter, Plus } from '@element-plus/icons-vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { SaleOutwarehouseApi, SaleOutwarehouseVO, SaleOutwarehouseReceiptVO } from '@/api/erp/sale/outwarehouse'
import SaleOutwarehouseForm from './SaleOutwarehouseForm.vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import {
  erpCountTableColumnFormatter,
  erpPriceInputFormatter,
  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 { formatDate } from '@/utils/formatTime'
import { ElMessageBox, ElMessage } from 'element-plus'
import { onActivated } from 'vue'
import { useWindowSize } from '@vueuse/core'

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

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

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

const loading = ref(true) // 列表的加载中
const list = ref<SaleOutwarehouseVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const filterVisible = ref(false) // 筛选抽屉
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  customerId: undefined,
  productId: undefined,
  warehouseId: undefined,
  outTime: [],
  accountId: undefined,
  status: undefined,
  receiptStatus: 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 applyStorageQuery = () => {
  const noValue = sessionStorage.getItem('erp_sale_outwarehouse_no')
  if (noValue && noValue.trim()) {
    queryParams.no = noValue.trim()
    queryParams.pageNo = 1
    sessionStorage.removeItem('erp_sale_outwarehouse_no')
    return true
  }
  sessionStorage.removeItem('erp_sale_outwarehouse_no')
  return false
}

// 收款表单相关数据
const receiptDialogVisible = ref(false)
const currentOutwarehouse = ref<SaleOutwarehouseVO | null>(null)
const receiptForm = reactive({
  amount: 0, // 本次收款金额
  date: new Date(), // 收款日期
  remark: '' // 备注
})
const receiptHistory = ref<any[]>([]) // 收款历史记录

/** 获取去重后的产品名称 */
const getUniqueProductNames = (itemList: any[]) => {
  if (!itemList || itemList.length === 0) return []

  // 提取所有产品名称并去重
  const productNames = itemList
    .filter(item => item.productName) // 过滤掉空的产品名称
    .map(item => item.productName)

  // 使用Set去重，然后转回数组
  return [...new Set(productNames)]
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SaleOutwarehouseApi.getSaleOutwarehousePage(queryParams)

    if (!data || !data.list) {
      list.value = []
      total.value = 0
      return
    }

    // 处理数据，确保所有必要的字段都存在
    const processedList = data.list.map(item => {

      // 获取所有仓库名称
      let warehouseNames = item.warehouseNames || ''
      if (!warehouseNames && item.itemList && item.itemList.length > 0) {
        // 从itemList中提取所有不重复的仓库名称
        const uniqueWarehouses = [...new Set(item.itemList
          .filter(i => i.warehouseName)
          .map(i => i.warehouseName))]
        warehouseNames = uniqueWarehouses.join(',')
      }

      // 计算合计数量和合计金额（如果后端未提供）
      let totalCount = item.totalCount
      let totalPrice = item.totalPrice

      if ((!totalCount || totalCount === 0) && item.itemList && item.itemList.length > 0) {
        totalCount = item.itemList.reduce((sum, i) => sum + (Number(i.count) || 0), 0)
      }

      if ((!totalPrice || totalPrice === 0) && item.itemList && item.itemList.length > 0) {
        totalPrice = item.itemList.reduce((sum, i) => sum + (Number(i.totalPrice) || 0), 0)
      }

      // 确保所有字段都有默认值
      const processedItem = {
        ...item,
        status: item.status || 0,
        warehouseName: item.warehouseName || '',
        warehouseNames: warehouseNames, // 新增字段，包含所有仓库名称
        totalCount: totalCount || 0,
        totalPrice: totalPrice || 0,
        receiptStatus: item.receiptStatus || 0,
        receiptPrice: item.receiptPrice || 0,
        // 处理时间：直接使用后端返回字符串
        outTime: item.outTime ? String(item.outTime) : ''
      }
      return processedItem
    })

    list.value = processedList
    total.value = data.total
  } catch (error) {
    list.value = []
    total.value = 0
  } 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) => {
  try {
    // 确保formRef已经挂载
    if (formRef.value) {
      formRef.value.open(type, id)
    } else {
      ElMessage.error('组件未正确加载，请刷新页面重试')
    }
  } catch (error) {
    console.error('打开表单失败:', error)
    ElMessage.error('打开表单失败，请刷新页面重试')
  }
}

/** 卡片点击 */
const handleCardClick = (row: SaleOutwarehouseVO) => {
  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 {
    // 确认对话框
    const statusText = status === 20 ? '审核' : '反审核'
    const confirmMessage = status === 20
      ? '审核后将减少库存，确认要审核吗？'
      : '反审核后将恢复库存，确认要反审核吗？'

    await ElMessageBox.confirm(confirmMessage, `确认${statusText}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 更新状态
    await SaleOutwarehouseApi.updateSaleOutwarehouseStatus(id, status)
    // 提示成功
    ElMessage.success(status === 20 ? '审核成功' : '反审核成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await ElMessageBox.confirm('是否确认删除该销售出库单？删除后将无法恢复！', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 发起删除
    await SaleOutwarehouseApi.deleteSaleOutwarehouse([id])
    ElMessage.success('删除成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await ElMessageBox.confirm(
      '是否确认导出所有销售出库数据？',
      '导出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // 发起导出
    exportLoading.value = true
    await SaleOutwarehouseApi.exportSaleOutwarehouse(queryParams)
    ElMessage.success('导出成功')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 打开收款表单
const openReceiptForm = async (row: SaleOutwarehouseVO) => {
  currentOutwarehouse.value = row
  receiptDialogVisible.value = true

  // 重置表单
  receiptForm.amount = 0
  receiptForm.date = new Date()
  receiptForm.remark = ''

  // 加载收款历史记录
  try {
    const response = await SaleOutwarehouseApi.getReceiptList(row.id!)
    if (response && Array.isArray(response)) {
      receiptHistory.value = response.map(item => ({
        ...item,
        date: formatDate(item.date, 'YYYY-MM-DD')
      }))
    } else {
      receiptHistory.value = []
    }
  } catch (error) {
    console.error('获取收款记录失败:', error)
    receiptHistory.value = []
  }
}

// 提交收款
const submitReceipt = async () => {
  try {
    if (!currentOutwarehouse.value) return
    if (receiptForm.amount <= 0) {
      ElMessage.warning('收款金额必须大于0')
      return
    }

    const totalPrice = currentOutwarehouse.value.totalPrice || 0
    const currentReceiptPrice = currentOutwarehouse.value.receiptPrice || 0
    const remainingAmount = totalPrice - currentReceiptPrice

    if (receiptForm.amount > remainingAmount) {
      ElMessage.warning(`收款金额不能超过未收款金额 ${erpPriceTableColumnFormatter(null, null, remainingAmount, null)}`)
      return
    }

    // 调用API保存收款记录
    const receiptData: SaleOutwarehouseReceiptVO = {
      outId: currentOutwarehouse.value.id!,
      outNo: currentOutwarehouse.value.no!,
      amount: receiptForm.amount,
      date: receiptForm.date,
      remainAmount: remainingAmount - receiptForm.amount,
      remark: receiptForm.remark
    }

    await SaleOutwarehouseApi.createReceipt(receiptData)
    ElMessage.success('收款成功')
    receiptDialogVisible.value = false

    // 刷新列表
    await getList()
  } catch (error) {
    console.error('收款失败:', error)
    ElMessage.error('收款失败，请重试')
  }
}

/** 初始化 */
onMounted(async () => {
  applyStorageQuery()
  // 获取产品列表
  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()
  // 获取列表数据
  await getList()
})

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

/** 行点击操作 */
const handleRowClick = (row: SaleOutwarehouseVO, column: any, event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (target.tagName === 'BUTTON' || target.tagName === 'A' || target.closest('button') || target.closest('a') || target.closest('.el-button')) return
  if (row.status === 20) openForm('detail', row.id)
  else if (row.status === 10) openForm('update', row.id)
}
</script>

<style lang="scss" scoped>
.mobile-sale-outwarehouse {
  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;
  }
}

.mobile-receipt-info {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 12px;

  &__row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 13px;
  }

  &__label {
    color: #909399;
  }

  &__danger {
    color: #f56c6c;
    font-weight: 600;
  }
}

.mobile-receipt-record {
  background: #f5f7fa;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 8px;

  &__row {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
  }

  &__amount {
    font-weight: 600;
    color: #67c23a;
  }

  &__detail {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}
</style>
