<template>
  <el-card :body-style="cardBodyStyle">
    <el-form v-model="query" :inline="true" :label-width="100" >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="仓库名称">
            <el-input v-model="query.wareName" placeholder="请输入仓库名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="垛位名称">
            <el-input v-model="query.stackName" placeholder="请输入垛位名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料名称">
            <el-input v-model="query.materialName" placeholder="请输入物料名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="钢种">
            <el-input v-model="query.stGrade" placeholder="请输入钢种" clearable @input="getStGradeList"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="订单号">
            <el-input v-model="query.attrib_01" placeholder="请输入订单号" clearable @input="getOrderList"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="货权客户名称">
            <el-input v-model="query.ownerCompany" placeholder="请输入货权客户名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合约号">
            <el-input v-model="query.attrib_02" placeholder="请输入合约号" clearable @input="get2List"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="捆包号">
            <el-input v-model="query.attrib_04" placeholder="请输入捆包号" clearable @input="get4List"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="入库车号">
            <el-input v-model="query.inTruckNo" placeholder="请输入入库车号" clearable @input="getTruck"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货公司">
            <el-input v-model="query.receivingCompany" placeholder="请输入收货公司" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格">
            <el-input v-model="query.attrib_03" placeholder="请输入规格" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="材料号">
            <el-input v-model="query.prodNo" placeholder="请输入材料号" clearable @input="getProdNo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="入库时间">
            <el-date-picker v-model="query.inRecordDate" size="small"  type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="24">
      <el-col :span="8">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <!--          <el-button @click="exportExcel">导出</el-button>-->
        <el-button type="success" @click="singleInStore">新增</el-button>
        <el-button type="danger" @click="cancelInStore">取消入库</el-button>
        <el-button @click="importExcel">导入</el-button>
      </el-col>
    </el-row>
  </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
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column type="index" label="序号" align="center" width="60">
        <template #default="scope">
          <span>{{ scope.$index + 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 label="捆绑包号" min-width="140" header-align="center" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.bundleNumber ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column label="规格" min-width="160" header-align="center" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.specification ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="inDtm" label="入库时间" min-width="180" header-align="center" align="center" show-overflow-tooltip >
        <template #default="{ row }">
          {{ formatDateTime(row.inDtm) ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="ownerCompanyName" label="货权公司" min-width="160" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="receivingCompanyName" 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.customerCompanyName ?? row.customerCompanyName ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="prodNo" 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-column label="产地" width="200" header-align="center" align="center">
        <template #default="{ row }">
          {{ row.placeOfOrigin ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column label="入库理货人员" min-width="120" header-align="center" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.inUserName ?? '-' }}
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-card :body-style="cardBodyStyle">
    <el-pagination
        :current-page="pageNum"
        :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>
  <!--  批量入库 -->
  <el-dialog
      v-model="disable"
      title="导入"
      width="1000"
      :destroy-on-close="true"
      @close="handleClose"
  >
    <div class="upload-controls">
      <div class="upload-section">
        <div style="display: flex">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="true"
              accept=".xls,.xlsx"
              action=""
              :limit="1">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </div>
        <!-- 显示选中文件名，限制长度并添加省略号 -->
  <!--        <div v-if="selectedFileName" class="file-name-preview">-->
  <!--          <span class="file-name-text" :title="selectedFileName">{{ selectedFileName }}</span>-->
  <!--        </div>-->
      </div>

      <div class="button-group">
        <el-button @click="exportExcel">下载模板</el-button>
        <el-button type="success" @click="saveExcel">保存</el-button>
      </div>
    </div>
    <div>
      <el-progress :percentage="progress" v-if="prog"/>
    </div>

    <el-table
        v-loading="loading"
        :data="fileUpload"    style="width: 100%"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :cell-style="{background:'#fafafa'}"
        max-height="400"
        border
    >
      <el-table-column label="序号" width="60" fixed="left">
        <template #default="scope">
          <div>{{ scope.$index + 1 }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="wareName" label="仓库名称" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="stackName" label="垛位号" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="layerNo" label="层号" width="80" show-overflow-tooltip></el-table-column>
      <el-table-column prop="materialName" label="物料名称" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="stGrade" label="钢种" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="attrib03" label="规格" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="quantity" label="数量" width="100" align="right">
        <template #default="scope">
          <div>{{ scope.row.quantity ? scope.row.quantity.toFixed(2) : '-' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="weight" label="重量(吨)" width="120" align="right">
        <template #default="scope">
          <div>{{ scope.row.weight ? scope.row.weight.toFixed(3) : '-' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="inTruckNo" label="入库车号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="ownerCompany" label="货权公司" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="receivingCompany" label="收货公司" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="prodNo" label="材料号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="attrib01" label="订单号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="attrib02" label="合约号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="attrib04" label="捆绑包号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="deliveryAddress" label="收货地址" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="attrib05" label="产地" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="remark1" label="备注" width="150" show-overflow-tooltip></el-table-column>
  <!--      <el-table-column prop="remark2" label="垛位备注" width="150" show-overflow-tooltip></el-table-column>-->
      <el-table-column prop="inUser" label="入库/理货人员" width="150" show-overflow-tooltip></el-table-column>
    </el-table>
  </el-dialog>
  <!--  单张入库-->
  <el-dialog
      v-model="singLoading"
      title="新增入库记录"
      width="1000px"
      :destroy-on-close="true"
      @close="handleClose"
  >
    <el-form
        ref="inStoreFormRef"
        :model="inStoreForm"
        :rules="inStoreRules"
        label-width="140px"
        :inline="false"
        status-icon
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="仓库名称" prop="wareName">
            <el-input
                v-model="inStoreForm.wareName"
                placeholder="请输入仓库名称"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="垛位号" prop="stackName">
            <el-input
                v-model="inStoreForm.stackName"
                placeholder="请输入垛位号"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="层号" prop="layerNo">
            <el-input
                v-model="inStoreForm.layerNo"
                placeholder="请输入层号"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="物料名称" prop="materialName">
            <el-input
                v-model="inStoreForm.materialName"
                placeholder="请输入物料名称"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="钢种" prop="stGrade">
            <el-input
                v-model="inStoreForm.stGrade"
                placeholder="请输入钢种"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="规格" prop="attrib03">
            <el-input
                v-model="inStoreForm.attrib03"
                placeholder="请输入规格"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input-number
                v-model="inStoreForm.quantity"
                :precision="2"
                :min="0"
                :step="1"
                placeholder="请输入数量"              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="重量(吨)" prop="weight">
            <el-input-number
                v-model="inStoreForm.weight"
                :precision="3"
                :min="0"
                :step="0.001"
                placeholder="请输入重量"              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库车号" prop="inTruckNo">
            <el-input
                v-model="inStoreForm.inTruckNo"
                placeholder="请输入入库车号"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="货权公司" prop="ownerCompany">
            <el-input
                v-model="inStoreForm.ownerCompany"
                placeholder="请输入货权公司"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="收货公司" prop="receivingCompany">
            <el-input
                v-model="inStoreForm.receivingCompany"
                placeholder="请输入收货公司"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="材料号" prop="prodNo">
            <el-input
                v-model="inStoreForm.prodNo"
                placeholder="请输入材料号"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单号" prop="attrib01">
            <el-input
                v-model="inStoreForm.attrib01"
                placeholder="请输入订单号"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合约号" prop="attrib02">
            <el-input
                v-model="inStoreForm.attrib02"
                placeholder="请输入合约号"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="捆绑包号" prop="attrib04">
            <el-input
                v-model="inStoreForm.attrib04"
                placeholder="请输入捆绑包号"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="收货地址" prop="deliveryAddress">
            <el-input
                v-model="inStoreForm.deliveryAddress"
                placeholder="请输入收货地址"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产地" prop="attrib05">
            <el-input
                v-model="inStoreForm.attrib05"
                placeholder="请输入产地"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="入库/理货人员" prop="inUser">
            <el-input
                v-model="inStoreForm.inUser"
                placeholder="请输入入库/理货人员"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark1">
            <el-input
                v-model="inStoreForm.remark1"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleSingClose">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import tools from '@/tools'
import {ElMessage, ElMessageBox, ElUpload} from 'element-plus';
import axios from "axios";

const {proxy} = getCurrentInstance()

const cardBodyStyle = ref(tools.style.card)
// ====================================查询列表=======================================
let tableLoading = ref( false)
let tableData = ref([])
let totalRows = ref(0)
let pageNum = ref(1)
let pageSize = ref(10)
const pageSizes = ref([10, 20, 50, 100])
const today = new Date()
const statistics = reactive({
  totalQuantity: 0,
  totalWeight: 0
})

const getStatistics = () => {
  const param = {
    params: JSON.stringify(buildQueryParams())
  }
  proxy.$axios
      .get('sto/InRecord/statistics', param)
      .then((response) => {
        if (response.data.code === '0') {
          const data = response.data.data || {}
          statistics.totalQuantity = data.TOTALQUANTITY
          statistics.totalWeight = data.TOTALWEIGHT
        } else {
          ElMessage.error(`统计失败：${response.data.msg || ''}`)
        }
      })
      .catch((error) => {
        ElMessage.error(`统计失败：${error.message || ''}`)
      })
}

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

const createDefaultQuery = () => {
  return {
    wareId: '',
    stackName: '',
    materialName: '',
    stGrade: null,
    materialStandard: '',
    attrib_03: '',
    bundleNo: '',
    prodNo: null,
    attrib_01: null,
    attrib_02: null,
    attrib_04: null,
    attrib_05: null,
    remark_1: '',
    ownerCompany: '',
    customerCompany: '',
    outTruckNo: null,
    outFlag: '',
    startDtm:null,
    endDtm:null,
    inLayerNo: '',
    wareName:'',
    layerNo:null,
    inTruckNo:null,
    receivingCompany:null,
    inRecordDate: [new Date(today.getFullYear(), today.getMonth(), today.getDate()),new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1)]
  }
}
const query = reactive(createDefaultQuery())
const getStGradeList = ()=>{
  if(!query.stGrade || query.stGrade.trim() === ''){
    query.stGrade = null;
  } else {
    query.stGrade = query.stGrade.replace(/[；,，;\s\r\n]+/g, ",").split(',');
  }
}

const getOrderList = () => {
  if(!query.attrib_01 || query.attrib_01.trim() === ''){
    query.attrib_01 = null;
  } else {
    query.attrib_01 = query.attrib_01.replace(/[；,，;\s\r\n]+/g, ",").split(',');
  }
}

const get2List = ()=>{
  if(!query.attrib_02 || query.attrib_02.trim() === ''){
    query.attrib_02 = null;
  } else {
    query.attrib_02 = query.attrib_02.replace(/[；,，;\s\r\n]+/g, ",").split(',');
  }
}

const get4List = ()=>{
  if(!query.attrib_04 || query.attrib_04.trim() === ''){
    query.attrib_04 = null;
  } else {
    query.attrib_04 = query.attrib_04.replace(/[；,，;\s\r\n]+/g, ",").split(',');
  }
}

const getTruck = ()=>{
  if(!query.outTruckNo || query.outTruckNo.trim() === ''){
    query.outTruckNo = null;
  } else {
    query.outTruckNo = query.outTruckNo.replace(/[；,，;\s\r\n]+/g, ",").split(',');
  }
}

const getProdNo = ()=>{
  if(!query.prodNo || query.prodNo.trim() === ''){
    query.prodNo = null;
  } else {
    query.prodNo = query.prodNo.replace(/[；,，;\s\r\n]+/g, ",").split(',');
  }
}


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 = () => {
  return {
    wareId: query.wareId,
    stackName: query.stackName,
    materialName: query.materialName,
    stGrade: query.stGrade,
    materialStandard: query.materialStandard,
    attrib_03: query.attrib_03,
    bundleNo: query.bundleNo,
    prodNo: query.prodNo,
    attrib_01: query.attrib_01,
    attrib_02: query.attrib_02,
    attrib_04: query.attrib_04,
    ownerCompany: query.ownerCompany,
    customerCompany: query.customerCompany,
    outTruckNo: query.outTruckNo,
    outFlag: query.outFlag,
    startDtm:formatDateTime(query.inRecordDate[0]),
    endDtm: formatDateTime(query.inRecordDate[1]),
    inLayerNo: query.inLayerNo,
    wareName: query.wareName,
    inTruckNo: query.inTruckNo,
    receivingCompany: query.receivingCompany,
    inRecordDate: query.inRecordDate
  }
}
const getTableData = () => {
  tableLoading.value = true
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify(buildQueryParams())
  }
  proxy.$axios.get('sto/InRecord/query', 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 handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const flagTagType = (val) => {
  if (val === '1' || val === 1) return 'success'
  if (val === '2' || val === 2) return 'danger'
  return 'info'
}
const flagLabel = (val) => {
  if (val === '1' || val === 1) return '正常'
  if (val === '2' || val === 2) return '取消入库'
  return val ?? '-'
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
const reset = ()=>{
  query.wareName= ''
  query.wareId= ''
  query.stackName= ''
  query.materialName= ''
  query.stGrade= null
  query.materialStandard= ''
  query.attrib_03= ''
  query.bundleNo= ''
  query.prodNo= null
  query.attrib_01= null
  query.attrib_02= null
  query.attrib_04= null
  query.attrib_05= null
  query.remark_1= ''
  query.ownerCompany= ''
  query.customerCompany= ''
  query.outTruckNo= null
  query.outFlag= ''
  query.inRecordDate= [new Date(today.getFullYear(), today.getMonth(), today.getDate()),new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1)]
  query.startDtm=null
  query.endDtm= null
  query.inTruckNo=null
  query.receivingCompany=null
  getTableData()
  getStatistics()
}
// =====================================下载模板=======================================
const exportExcel = () => {
  const params = {
    startTime: '2023-01-01',
    endTime: '2023-12-31',
    status: 'completed'
  };

  axios({
    method: 'GET',
    url: '/sto/InRecord/exportExcel',
    params: { params: JSON.stringify(params) },
    responseType: 'blob' // 重要：指定响应类型为 blob
  }).then((response) => {
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '入库模板.xlsx'); // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
  }).catch((error) => {
    console.error('导出失败:', error);
  });
}
// =====================================文件上传(上传文件获取excel数据)=======================================
let fileUpload = ref([]);
let progress = ref(0)
let prog = ref(false)
// 添加文件名状态
const selectedFileName = ref('')
// 处理文件选择变化
// 更新文件变更处理函数
const handleFileChange = async (file, fileList) => {
  // 更新选中的文件名
  if (fileList.length > 0) {
    selectedFileName.value = fileList[fileList.length - 1].name
  } else {
    selectedFileName.value = ''
  }

  // 只处理最新的文件
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }

  try {
    const result = await upload(file.raw);
    console.log('上传成功，解析数据:', result);
  } catch (error) {
    console.error('处理文件失败:', error);
  }
};

// 文件上传方法
const upload = async (file) => {
  // 文件类型验证
  const fileName = file.name;
  if (!fileName || (!fileName.endsWith('.xls') && !fileName.endsWith('.xlsx'))) {
    ElMessage.error('请上传Excel文件(.xls 或 .xlsx)');
    return Promise.reject(new Error('文件类型不正确'));
  }

  const formData = new FormData();
  formData.append('file', file);

  // 存储 ElMessage 返回的引用
  let messageRef = null;

  try {
    // 显示上传中提示
    // messageRef = ElMessage({
    //   message: '文件上传中...',
    //   type: 'info',
    //   duration: 0 // 持续显示
    // });
    prog.value = true

    const response = await axios.post('/sto/InRecord/uploadExcel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        progress.value = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
        );
        console.log(`上传进度: ${progress.value}%`);
      }
    });

    console.log('上传结果:', response);
    prog.value = false

    // 关闭加载提示
    // if (messageRef) {
    //   messageRef.close();
    // }

    // 检查后端响应结构 - 根据实际后端返回的 code 判断
    if (response.data && (response.data.code === 200 || response.data.code === 0 || response.data.success)) {
      ElMessage.success('文件上传成功');
      fileUpload.value = response.data.data || [];
      return response.data.data;
    } else {
      const errorMsg = response.data?.msg || response.data?.message || '文件上传失败';
      ElMessage.error(errorMsg);
      return Promise.reject(new Error(errorMsg));
    }
  } catch (error) {
    console.error('文件上传失败:', error);

    // 确保关闭加载提示
    if (messageRef) {
      messageRef.close();
    }

    // 更安全的错误信息提取
    let errorMsg = '文件上传失败，请稍后重试';
    if (error.response) {
      // 服务器返回了错误响应
      errorMsg = error.response.data?.msg || error.response.data?.message ||
          error.response.statusText || errorMsg;
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMsg = '网络错误，无法连接到服务器';
    } else {
      // 其他错误
      errorMsg = error.message || errorMsg;
    }

    ElMessage.error(errorMsg);
    return Promise.reject(error);
  }
};

// =====================================批量入库======================================
const batchInStore = () => {
  proxy.$axios.post('/sto/InRecord/batchInStore', {
    dataList: JSON.stringify(fileUpload.value)
  }).then(response => {
    if (response.data.code == '0') {
      ElMessage.success('入库成功！')
      loading.value = false
      handleClose()
    } else {
      ElMessage.error('入库失败！' + response.data.msg)
      fileUpload.value = []
      loading.value = false
    }
  })
};
// =====================================单张入库====================================
let singLoading = ref(false)
const inStoreFormRef = ref(null)
// 新增表单数据
const inStoreForm = reactive({
  wareName: '',
  stackName: '',
  layerNo: '',
  materialName: '',
  stGrade: '',
  attrib03: '',
  quantity: null,
  weight: null,
  inTruckNo: '',
  ownerCompany: '',
  receivingCompany: '',
  prodNo: '',
  attrib01: '',
  attrib02: '',
  attrib04: '',
  deliveryAddress: '',
  attrib05: '',
  remark1: '',
  inUser: ''
})
// 表单验证规则（全部必填）
const inStoreRules = {
  wareName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' }
  ],
  stackName: [
    { required: true, message: '请输入垛位号', trigger: 'blur' }
  ],
  layerNo: [
    { required: true, message: '请输入层号', trigger: 'blur' }
  ],
  materialName: [
    { required: true, message: '请输入物料名称', trigger: 'blur' }
  ],
  stGrade: [
    { required: true, message: '请输入钢种', trigger: 'blur' }
  ],
  attrib03: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '数量不能小于0', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入重量', trigger: 'blur' },
    { type: 'number', min: 0, message: '重量不能小于0', trigger: 'blur' }
  ],
  inTruckNo: [
    { required: true, message: '请输入入库车号', trigger: 'blur' }
  ],
  ownerCompany: [
    { required: true, message: '请输入货权公司', trigger: 'blur' }
  ],
  receivingCompany: [
    { required: true, message: '请输入收货公司', trigger: 'blur' }
  ],
  prodNo: [
    { required: true, message: '请输入材料号', trigger: 'blur' }
  ],
  attrib01: [
    { required: true, message: '请输入订单号', trigger: 'blur' }
  ],
  attrib02: [
    { required: true, message: '请输入合约号', trigger: 'blur' }
  ],
  attrib04: [
    { required: true, message: '请输入捆绑包号', trigger: 'blur' }
  ],
  deliveryAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  attrib05: [
    { required: true, message: '请输入产地', trigger: 'blur' }
  ],
  inUser: [
    { required: true, message: '请输入入库/理货人员', trigger: 'blur' }
  ]
}
const singleInStore = () => {
  singLoading.value = true
  fileUpload.value = []
}
// 重置表单
const resetForm = () => {
  Object.assign(inStoreForm, {
    wareName: '',
    stackName: '',
    layerNo: '',
    materialName: '',
    stGrade: '',
    attrib03: '',
    quantity: null,
    weight: null,
    inTruckNo: '',
    ownerCompany: '',
    receivingCompany: '',
    prodNo: '',
    attrib01: '',
    attrib02: '',
    attrib04: '',
    deliveryAddress: '',
    attrib05: '',
    remark1: '',
    inUser: ''
  })
}
const handleSingClose = () => {
  singLoading.value = false
  resetForm()
  fileUpload.value = []
}
const submitForm = ()=>{
  inStoreFormRef.value.validate((valid) => {
    if (valid) {
      fileUpload.value.push(inStoreForm)
      batchInStore()
    } else {
      return ElMessage.error('请填写所有必填项')
    }
  })
}
// =======================================导入=====================================
// 进度条控制
let disable = ref(false)
// 加载提示
let loading = ref(false)
const saveExcel = () => {
  loading.value = true
  batchInStore()
}
const importExcel = () => {
  disable.value = true
}
const handleClose = ()=>{
  disable.value = false
  fileUpload.value = []
  progress.value = 0
  prog.value = false
  singLoading.value = false
  getTableData()
  getStatistics()
}
// ========================================取消入库=====================================
const cancelInStore = () => {
  if(multipleSelection.value.length>1){
    ElMessage.warning('一次只能取消一个入库单')
    return;
  }
  if(multipleSelection.value.length==0){
    return ElMessage.warning("请选择一个入库记录")
  }
  ElMessageBox.confirm(
      '确认取消入库吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
        const params = {
          id: multipleSelection.value[0].id,
          prodId:multipleSelection.value[0].prodId
        };

        handleCancelInStore(params)
  })
      .catch(() => {

      })
}
const handleCancelInStore = (params) => {
  proxy.$axios.post('/sto/InRecord/cancelInStore',
      { params: JSON.stringify(params) }
  ).then((response) => {
    console.log('完整响应对象:', response);
    console.log('响应数据:', response.data);

    // 首先检查 response 是否存在以及是否包含 data 属性
    if (!response || !response.data) {
      ElMessage.error('服务器未返回有效数据');
      return;
    }
    if (response.data.code == '0') {
      ElMessage.success('取消入库成功');
      getTableData();
      getStatistics()
    } else {
      ElMessage.error(response.data.msg || response.data.message || '操作失败');
    }
  }).catch((error) => {
    console.error('取消入库失败:', error);
    ElMessage.error('请求失败，请重试');
  });
}
// ========================================列表多选框===================================
let multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// ========================================生命周期=====================================
onMounted(() => {
  getTableData()
})
</script>
<style scoped>
.upload-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.upload-section {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 200px; /* 最小宽度确保在小屏幕上也能正常显示 */
}

.file-name-preview {
  margin-left: 12px;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  max-width: 200px;
}

.file-name-text {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
  color: #606266;
}

.button-group {
  display: flex;
  gap: 8px;
}

/* 在较小屏幕上的适配 */
@media (max-width: 768px) {
  .upload-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .button-group {
    justify-content: center;
  }
}
</style>
