<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card shadow="never">
      <el-form :model="queryParams" inline>
        <TenantSelect v-model="queryParams.tenantIds" placeholder="请选择机构名称" prop="tenantIds" @change="fetchWarehouseOptions" />
        <el-form-item label="库房" prop="storeId">
          <el-select v-model="queryParams.storeId" placeholder="全部" clearable class="!w-180px">
            <el-option v-for="w in warehouseOptions" :key="w.id" :label="w.storeName" :value="w.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="月份范围" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="monthrange"
            value-format="YYYY-MM"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="物资名称/物资编码" clearable class="!w-240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button v-hasPermi="['warehouses:stock-search:export']" :loading="exportLoading" type="success" plain @click="handleExport"><Icon icon="ep:download" class="mr-5px" />导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="mt-4">
      <el-table :data="tableData" v-loading="loading" :header-cell-style="tableHeaderColor">
        <el-table-column prop="storeName" label="库房" align="center" />
        <el-table-column prop="categoryName" label="物资类别" align="center" />
        <el-table-column prop="materialName" label="物资名称" align="center" />
        <el-table-column prop="materialUnit" label="计量单位" align="center" />
        <el-table-column label="期初余额" align="center">
          <el-table-column prop="beginQty" label="数量" align="center" />
          <el-table-column prop="beginPrice" label="单价" align="center" :formatter="(row) => fmtMoney(row.beginPrice)" />
          <el-table-column prop="beginAmount" label="金额" align="center" :formatter="(row) => fmtMoney(row.beginAmount)" />
        </el-table-column>

        <el-table-column label="本期收入" align="center">
          <el-table-column prop="inQty" label="数量" align="center" />
          <el-table-column prop="inPrice" label="单价" align="center" :formatter="(row) => fmtMoney(row.inPrice)" />
          <el-table-column prop="inAmount" label="金额" align="center" :formatter="(row) => fmtMoney(row.inAmount)" />
        </el-table-column>

        <el-table-column label="本期支出" align="center">
          <el-table-column prop="outQty" label="数量" align="center" />
          <el-table-column prop="outPrice" label="单价" align="center" :formatter="(row) => fmtMoney(row.outPrice)" />
          <el-table-column prop="outAmount" label="金额" align="center" :formatter="(row) => fmtMoney(row.outAmount)" />
        </el-table-column>

        <el-table-column label="本期结余" align="center">
          <el-table-column prop="endQty" label="数量" align="center" />
          <el-table-column prop="endPrice" label="单价" align="center" :formatter="(row) => fmtMoney(row.endPrice)" />
          <el-table-column prop="closingAmount" label="金额" align="center" :formatter="(row) => fmtMoney(row.endAmount)" />
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="mt-4"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 库存查看弹窗 -->
    <StockDetailDialog v-model="stockDialogVisible" :detail="currentStockDetail" />
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { materialStockSearchPage, materialStockFlowDetail, materialStockSearchExport } from '@/api/material/stockSearch'
import { useUserStore } from '@/store/modules/user'
import { storeList } from '@/api/material/storeManage'
import download from '@/utils/download'

const userStore = useUserStore()
const message = useMessage()

const StockDetailDialog = defineAsyncComponent(() => import('./components/StockDetailDialog.vue'))

const tableHeaderColor = () => ({
  background: '#F5F7FA',
  color: '#606266',
  fontWeight: '600',
})

// 搜索条件
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  tenantIds: userStore.orgTenantId,
  storeId: '',
  month: [],
  keyword: '',
})

// 列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentStockDetail = ref({})
const warehouseOptions = ref([])
const stockDialogVisible = ref(false)
const fmtMoney = (n) => `￥${n}`
const exportLoading = ref(false)
const fetchWarehouseOptions = async () => {
  const res = await storeList({
    tenantIds: queryParams.tenantIds?.length ? queryParams.tenantIds : undefined,
  })
  const data = res ?? []
  console.log(data)
  warehouseOptions.value = Array.isArray(data) ? data : []
}

const getTableData = async () => {
  loading.value = true
  let params = {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    tenantIds: queryParams.tenantIds,
    storeId: queryParams.storeId,
    month: queryParams.month,
    keyword: queryParams.keyword,
  }
  try {
    const res = await materialStockSearchPage(params)
    tableData.value = res.list
    total.value = res.total
  } catch (error) {
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getTableData()
  fetchWarehouseOptions()
})

const handleSearch = () => {
  queryParams.pageNo = 1
  getTableData()
}

const handleReset = () => {
  queryParams.storeId = ''
  queryParams.month = []
  queryParams.keyword = ''
  queryParams.pageNo = 1
  queryParams.tenantIds = userStore.orgTenantId
  queryParams.pageSize = 10
  getTableData()
}

const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getTableData()
}

const handleCurrentChange = (page) => {
  queryParams.pageNo = page
  getTableData()
}

const handleView = async(row) => {
  const [startMonth] = queryParams.month || []
  if (!startMonth) {
    ElMessage.error('请选择月份')
    return
  }
  try {
    const res = await materialStockFlowDetail({
      inboundItemId: row.inboundItemId,
      month: startMonth,
    })
    currentStockDetail.value = res
    stockDialogVisible.value = true
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const handleExport = async() => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await materialStockSearchExport(queryParams)
    download.excel(data, '库存查询报表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}
.mb-4 {
  margin-bottom: 16px;
}
</style>



