<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">
      <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-row :gutter="24">
          <el-col :span="8">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="reset">重置</el-button>
<!--            <el-button type="danger" @click="exportExcel">删除</el-button>-->
            <el-button type="success" @click="exportExcel">导出</el-button>
          </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
          @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>
  </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'
import {ElMessage} from "element-plus";
import axios from "axios";

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)
let pageNum = ref(1)
const listUrl = ref('sto/InRecord/query')
const statisticsUrl = ref('sto/InRecord/statistics')
const multipleSelection = ref([])
const PopupMenuTreeRef = ref(null)
const showPop = () => {
  PopupMenuTreeRef.value?.show?.()
}



const today = new Date()

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

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
        statistics.totalWeight = data.TOTALWEIGHT
      } 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 = ()=>{
  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
  getTableData()
}

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 handleSelectionChange = (val) => {
  multipleSelection.value = val
}

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 convertExportData = (selectedData) => {
  return selectedData.map(item => {
    return {
      // 仓库相关
      wareName: item.inWareName || item.wareName || '',          // 仓库名称
      stackName: item.inStackName || item.stackName || '',      // 垛位号
      layerNo: item.inLayerNo || item.layerNo || '',           // 层号

      // 物料信息
      materialName: item.materialName || '',                    // 物料名称
      stGrade: item.ST_GRADE || item.stGrade || '',            // 钢种
      attrib03: item.specification || item.attrib03 || '',     // 规格
      quantity: item.IN_QUANTITY || item.inQuantity || 0,      // 数量
      weight: item.IN_WEIGHT || item.inWeight || 0,            // 重量(默认吨)

      // 运输信息
      inTruckNo: item.carNo || item.inTruckNo || '',           // 入库车号

      // 公司信息
      ownerCompany: item.ownerCompany || '',                   // 货权公司
      receivingCompany: item.receivingCompany || '',           // 收货公司
      // 注意：前端表格中有"最终客户公司"，但Excel中没有对应字段

      // 编号信息
      prodNo: item.prodNo || '',                               // 材料号
      attrib01: item.orderNo || item.attrib01 || '',           // 订单号
      attrib02: item.contractNo || item.attrib02 || '',        // 合约号
      attrib04: item.bundleNumber || item.attrib04 || '',          // 捆绑包号

      // 地址和产地
      deliveryAddress: item.deliveryAddress || '',             // 收货地址
      attrib05: item.placeOfOrigin || item.attrib05 || '',            // 产地

      // 备注信息
      remark1: item.remark || item.remark1 || '',              // 备注
      remark2: item.stackRemark || item.remark2 || '',         // 垛位备注

      // 人员信息
      inUser: item.inUserName || '',                               // 入库/理货人员

      // 其他可能需要但Excel中没有的字段
      inDtm: item.inDtm || '',                                 // 入库时间（Excel中没有）
      inFlag: item.inFlag || '',                               // 入库标记（Excel中没有）
      customerCompany: item.customerCompany || item.CustomerCompany || '' // 最终客户公司
    };
  });
};

// 修改导出函数
const exportExcel = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要导出的数据');
    return;
  }

  // 转换数据格式
  const exportData = convertExportData(multipleSelection.value);

  axios({
    method: 'POST',
    url: '/sto/InRecord/exportInRecode',
    data: exportData,  // 使用转换后的数据
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((response) => {
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `入库记录_${new Date().getTime()}.xlsx`);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);

    ElMessage.success('导出成功');
  }).catch((error) => {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  });
};

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

