<template>
  <div>
    <SearchBox
      ref="SearchBoxRef"
      formName="selectTop"
      :formData="query"
      @showPop="showPop"
      @reset="reset"
    />
    <ButtonBox
      @search="handleSearch"
      @add="insertDialog"
      @start="start('0')"
      @remove="shutdwon('1')"
    />

    <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.inWareName ?? row.wareName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="垛位名称" min-width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.inStackName ?? row.stackName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="层号" width="100" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.inLayerNo ?? 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 prop="carNo" label="车号" min-width="120" header-align="center" align="center" show-overflow-tooltip />
        <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.IN_WEIGHT ?? row.inWeight ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="入库数量" min-width="140" header-align="center" align="right" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.IN_QUANTITY ?? row.inQuantity ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="入库标记" width="140" header-align="center" align="center">
          <template #default="{ row }">
            <el-tag :type="flagTagType(row.inFlag)" effect="plain">
              {{ flagLabel(row.inFlag) }}
            </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>
    </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'
import ButtonBox from '@/components/ButtonBox.vue'
import SearchBox from '@/components/SearchBox.vue'

const {proxy} = getCurrentInstance()

const cardBodyStyle = ref(tools.style.card)
const SearchBoxRef = ref(null)
const statistics = reactive({
  totalQuantity: 0,
  totalWeight: 0
})
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/InRecord/query')
const statisticsUrl = ref('sto/InRecord/statistics')

const PopupMenuTreeRef = ref(null)
const showPop = () => {
  PopupMenuTreeRef.value?.show?.()
}

const createDefaultQuery = () => {
  const today = new Date()
  return {
    wareName: '',
    stackName: '',
    materialName: '',
    materialStandard: '',
    startDtm: new Date(today.getFullYear(), today.getMonth(), today.getDate()),
    endDtm: new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1),
    ownerCompany: '',
    receivingCompany: '',
    customerCompany: '',
    prodNo: '',
    inTruckNo: '',
    orderNo: '',
    contractNo: ''
  }
}
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 = () => ({
  ...query,
  startDtm: formatDateTime(query.startDtm),
  endDtm: formatDateTime(query.endDtm, 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') {
        const data = response.data.data || {}
        statistics.totalQuantity =
          data.totalQuantity ??
          data.inQuantity ??
          data.IN_QUANTITY ??
          data.totalQty ??
          0
        statistics.totalWeight =
          data.totalWeight ??
          data.inWeight ??
          data.IN_WEIGHT ??
          data.totalWgt ??
          0
      } else {
        ElMessage.error(`统计失败：${response.data.msg || ''}`)
      }
    })
    .catch((error) => {
      ElMessage.error(`统计失败：${error.message || ''}`)
    })
}

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

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

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

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

const insertDialog = () => {
  console.warn('insertDialog action is not implemented yet.')
}
const start = () => {
  console.warn('start action is not implemented yet.')
}
const shutdwon = () => {
  console.warn('shutdwon action is not implemented yet.')
}

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'
}

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

