<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-width="90px" label-position="right">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="库房名称">
              <el-select
                v-model="query.wareId"
                clearable
                filterable
                placeholder="请选择库房"
                style="width: 100%;"
                @visible-change="handleWareVisible"
              >
                <el-option
                  v-for="item in wareOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="垛位名称">
              <el-input v-model="query.stackName" clearable placeholder="请输入垛位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品名">
              <el-input v-model="query.materialName" clearable placeholder="请输入品名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="钢种">
              <el-input v-model="query.stGrade" clearable placeholder="请输入钢种" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="规格型号">
              <el-input v-model="query.materialStandard" clearable placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="捆包号">
              <el-input v-model="query.bundleNo" clearable placeholder="请输入捆包号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="材料号">
              <el-input v-model="query.inProdNo" clearable placeholder="请输入材料号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单号">
              <el-input v-model="query.orderNo" clearable placeholder="请输入订单号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="合约号">
              <el-input v-model="query.contractNo" clearable placeholder="请输入合约号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货权单位">
              <el-select
                v-model="query.ownerCompany"
                clearable
                filterable
                placeholder="请选择货权单位"
                style="width: 100%;"
                @visible-change="handleOwnerVisible"
              >
                <el-option
                  v-for="item in ownerCompanyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-select
                v-model="query.customerCompany"
                clearable
                filterable
                placeholder="请选择客户名称"
                style="width: 100%;"
                @visible-change="handleCustomerVisible"
              >
                <el-option
                  v-for="item in customerCompanyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库车号">
              <el-input v-model="query.outTruckNo" clearable placeholder="请输入出库车号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="出库时间">
              <el-date-picker
                v-model="query.outDtmRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="defaultRangeTime"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label=" ">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card :body-style="cardBodyStyle" class="summary-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="summary-item">
            <span class="summary-label">出库数量统计：</span>
            <span class="summary-value">{{ statistics.totalQuantity ?? '-' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-item">
            <span class="summary-label">出库重量统计：</span>
            <span class="summary-value">{{ statistics.totalWeight ?? '-' }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        highlight-current-row
      >
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" min-width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.outWareName ?? row.wareName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="垛位名称" min-width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.outStackName ?? row.stackName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="层号" width="100" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.outLayerNo ?? row.layerNo ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称" min-width="160" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.materialName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="钢种" width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.ST_GRADE ?? row.stGrade ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="inDtm" label="入库时间" min-width="180" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="ownerCompany" label="货权公司" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="receivingCompany" label="收货公司" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="最终客户公司" min-width="180" header-align="center" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.customerCompany ?? row.CustomerCompany ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="inProdNo" label="材料号" min-width="140" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="出库车号" min-width="140" header-align="center" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.outTruckNo ?? row.carNo ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="订单号" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="contractNo" label="合约号" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="出库重量" min-width="140" header-align="center" align="right" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.outWeight ?? row.OUT_WEIGHT ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="出库数量" min-width="140" header-align="center" align="right" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.outQuantity ?? row.OUT_QUANTITY ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="出库标记" width="140" header-align="center" align="center">
          <template #default="{ row }">
            <el-tag :type="flagTagType(row.outFlag)" effect="plain">
              {{ flagLabel(row.outFlag) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryAddress" label="收货地址" min-width="200" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="outDtm" label="出库时间" min-width="180" header-align="center" align="center" show-overflow-tooltip />
      </el-table>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalRows"
        background="background"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import tools from '@/tools'

const {proxy} = getCurrentInstance()

const cardBodyStyle = ref(tools.style.card)
const tableLoading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 50, 100])
const pageSize = ref(10)

const listUrl = ref('sto/OutRecord/query')
const statisticsUrl = ref('sto/OutRecord/statistics')

const wareOptions = ref([])
const ownerCompanyOptions = ref([])
const customerCompanyOptions = ref([])
const statistics = reactive({
  totalQuantity: 0,
  totalWeight: 0
})
const defaultRangeTime = [
  new Date(0, 0, 0, 0, 0, 0),
  new Date(0, 0, 0, 23, 59, 59)
]

const toOptions = (list, labelKey, valueKey) =>
  (list || []).map((item) => {
    if (typeof item === 'string') {
      return {
        label: item,
        value: item
      }
    }
    return {
      label: item?.[labelKey] ?? item?.label ?? item?.name ?? item?.value ?? '',
      value: item?.[valueKey] ?? item?.value ?? item?.id ?? item?.code ?? item?.label ?? ''
    }
  }).filter((item) => item.label !== '' && item.value !== '')

const createDefaultQuery = () => {
  const today = new Date()
  const start = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const end = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999)
  return {
    wareId: '',
  stackName: '',
  materialName: '',
    stGrade: '',
  materialStandard: '',
    bundleNo: '',
    inProdNo: '',
    orderNo: '',
    contractNo: '',
  ownerCompany: '',
    customerCompany: '',
    outTruckNo: '',
    outFlag: '',
    outDtmRange: [start, end]
  }
}
const query = reactive(createDefaultQuery())

const formatDateTime = (value, isEnd = false) => {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  if (isEnd && date.getHours() === 0 && date.getMinutes() === 0 && date.getSeconds() === 0) {
    date.setHours(23, 59, 59, 999)
  }
  const pad = (num) => String(num).padStart(2, '0')
  const yyyy = date.getFullYear()
  const mm = pad(date.getMonth() + 1)
  const dd = pad(date.getDate())
  const hh = pad(date.getHours())
  const mi = pad(date.getMinutes())
  const ss = pad(date.getSeconds())
  return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`
}

const buildQueryParams = () => {
  const [startOut, endOut] = query.outDtmRange || []
  return {
    wareId: query.wareId,
    stackName: query.stackName,
    materialName: query.materialName,
    stGrade: query.stGrade,
    materialStandard: query.materialStandard,
    bundleNo: query.bundleNo,
    inProdNo: query.inProdNo,
    orderNo: query.orderNo,
    contractNo: query.contractNo,
    ownerCompany: query.ownerCompany,
    customerCompany: query.customerCompany,
    outTruckNo: query.outTruckNo,
    outFlag: query.outFlag,
    startDtm: formatDateTime(startOut),
    endDtm: formatDateTime(endOut, true)
  }
}

const getTableData = () => {
  tableLoading.value = true
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(buildQueryParams())
  }
  proxy.$axios.get(listUrl.value, param).then((response) => {
    if (response.data.code === '0') {
      tableData.value = response.data.data.records || []
      totalRows.value = response.data.data.total || 0
    } else {
      ElMessage.error(`查询失败：${response.data.msg || ''}`)
    }
  }).catch((error) => {
    ElMessage.error(`查询失败：${error.message || ''}`)
  }).finally(() => {
    tableLoading.value = false
  })
}

const getStatistics = () => {
  const param = {
    params: JSON.stringify(buildQueryParams())
  }
  proxy.$axios
    .get(statisticsUrl.value, param)
    .then((response) => {
      if (response.data.code === '0' || response.data.code === 0) {
        const data = response.data.data || {}
        statistics.totalQuantity =
          data.totalQuantity ??
          data.outQuantity ??
          data.OUT_QUANTITY ??
          data.totalQty ??
          0
        statistics.totalWeight =
          data.totalWeight ??
          data.outWeight ??
          data.OUT_WEIGHT ??
          data.totalWgt ??
          0
      } else {
        ElMessage.error(`统计失败：${response.data.msg || ''}`)
      }
    })
    .catch((error) => {
      ElMessage.error(`统计失败：${error.message || ''}`)
    })
}

const handleSearch = () => {
  currentPage.value = 1
  getTableData()
  getStatistics()
}

const handleReset = () => {
  Object.assign(query, createDefaultQuery())
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

const flagLabel = (val) => {
  if (val === '1' || val === 1) return '正常'
  if (val === '2' || val === 2) return '取消出库'
  return val ?? '-'
}
const flagTagType = (val) => {
  if (val === '1' || val === 1) return 'success'
  if (val === '2' || val === 2) return 'danger'
  return 'info'
}

const fetchWareOptions = () => {
  proxy.$axios.get('sto/Ware/options', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      wareOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}

const fetchOwnerCompanyOptions = () => {
  proxy.$axios.get('sto/Customer/querySelect', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      ownerCompanyOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}

const fetchCustomerOptions = () => {
  proxy.$axios.get('sto/Customer/querySelect', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      customerCompanyOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}

const handleWareVisible = (visible) => {
  if (visible && wareOptions.value.length === 0) {
    fetchWareOptions()
  }
}

const handleOwnerVisible = (visible) => {
  if (visible && ownerCompanyOptions.value.length === 0) {
    fetchOwnerCompanyOptions()
  }
}

const handleCustomerVisible = (visible) => {
  if (visible && customerCompanyOptions.value.length === 0) {
    fetchCustomerOptions()
  }
}

onMounted(() => {
  fetchWareOptions()
  fetchOwnerCompanyOptions()
  fetchCustomerOptions()
  getTableData()
  getStatistics()
})
</script>

<style scoped>
.summary-card {
  margin-top: 10px;
}
.summary-item {
  display: flex;
  align-items: center;
  height: 40px;
}
.summary-label {
  color: #606266;
  margin-right: 6px;
  font-weight: 500;
}
.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
</style>
