<template>
  <div class="customer-css">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" class="search-form-inline">
      <div class="search-row">
        <el-form-item label="进仓编号" class="search-item">
          <el-input v-model="searchData.flexId" style="width: 150px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="供应商编码" class="search-item">
          <el-input v-model="searchData.supplierNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="供应商名称" class="search-item">
          <el-input v-model="searchData.supplierName" style="width: 200px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label=" " class="search-item search-btn-item">
          <el-button type="primary" @click="getMainData">查询</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      @row-click="changeData"
      v-loading="dataListLoading"
      style="margin-top: 0px; width: 100%;">
      <el-table-column
        prop="flexId"
        label="进仓编号"
        min-width="150"
        show-overflow-tooltip />
      <el-table-column
        prop="supplierNo"
        label="供应商编码"
        width="120"
        align="center" />
      <el-table-column
        prop="supplierName"
        label="供应商名称"
        min-width="200"
        show-overflow-tooltip />
      <el-table-column
        prop="poCount"
        label="PO数量"
        width="100"
        align="center" />
      <el-table-column
        prop="shippedQty"
        label="已出货数量"
        width="120"
        align="center" />
    </el-table>

    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px"
                   @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[20, 50, 100, 200, 500]"
                   :page-size="pageSize"
                   :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 详情页签 -->
    <el-tabs v-model="activeTab" style="margin-top: 0px; width: 99%;" @tab-click="handleTabClick" class="customer-tab" type="border-card">
      <!-- PO清单 -->
      <el-tab-pane label="PO清单" name="poList">
        <el-table
          :data="poListData"
          border
          :height="detailHeight"
          v-loading="poListLoading"
          style="width: 100%;">
<!--          <el-table-column-->
<!--            type="index"-->
<!--            label="序号"-->
<!--            width="80"-->
<!--            align="center" />-->
          <el-table-column
            prop="orderRef1"
            label="PO"
            min-width="150"
            show-overflow-tooltip />
          <el-table-column
            prop="orderDate"
            label="PO日期"
            width="120"
            align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.orderDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="sku"
            label="SKU"
            min-width="150"
            show-overflow-tooltip />
          <el-table-column
            prop="qty"
            label="Qty"
            width="100"
            align="center" />
          <el-table-column
            prop="shippedQty"
            label="Qty Shipped"
            width="120"
            align="center" />
        </el-table>
      </el-tab-pane>
      <!-- 附件 -->
      <el-tab-pane label="附件" name="attachment">
        <logistics-attachment-tab ref="attachmentTab" :detail-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import LogisticsAttachmentTab from './com_logisticsAttachmentTab.vue'
import { searchLogistics, getPoList } from '@/api/npcIqc/npcIqc.js'

export default {
  components: {
    LogisticsAttachmentTab
  },
  data () {
    return {
      height: 400,
      detailHeight: 400,
      currentRow: {},
      activeTab: 'poList',
      searchData: {
        flexId: '',
        supplierNo: '',
        supplierName: '',
        site: this.$store.state.user.site,
        page: 1,
        limit: 50
      },
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      mainDataList: [],
      poListData: [],
      dataListLoading: false,
      poListLoading: false
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.height = (window.innerHeight - 220) / 2
      this.detailHeight = (window.innerHeight - 220) / 2
      this.getMainData()
    })
  },
  methods: {
    // 设置高度（供父组件调用）
    setHeight(height) {
      this.height = height * 0.5
      this.detailHeight = height * 0.5
    },

    // 查询数据
    getMainData () {
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      this.dataListLoading = true

      searchLogistics(this.searchData).then(({ data }) => {
        if (data.code === 0) {
          this.mainDataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount

          this.$nextTick(() => {
            if (this.$refs.mainTable) {
              this.$refs.mainTable.clearSelection()
            }
          })

          // 判断是否有数据
          if (this.mainDataList.length > 0) {
            this.$refs.mainTable.setCurrentRow(this.mainDataList[0])
            this.changeData(this.mainDataList[0])
          } else {
            this.changeData(null)
          }
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataListLoading = false
      })
    },

    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getMainData()
    },

    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getMainData()
    },

    // 页签点击事件
    handleTabClick (tab) {
      if (tab.name === 'poList') {
        this.loadPoList()
      } else if (tab.name === 'attachment') {
        this.$nextTick(() => {
          if (this.$refs.attachmentTab) {
            this.$refs.attachmentTab.searchTable()
          }
        })
      }
    },

    // 行点击事件
    changeData (row) {
      this.currentRow = row ? JSON.parse(JSON.stringify(row)) : {}
      this.loadPoList()
    },

    // 加载PO清单
    loadPoList () {
      if (!this.currentRow.flexId) {
        this.poListData = []
        return
      }

      this.poListLoading = true
      const params = {
        flexId: this.currentRow.flexId,
        supplierNo: this.currentRow.supplierNo || '',
        site: this.$store.state.user.site,
        page: 1,
        limit: 1000
      }

      getPoList(params).then(({ data }) => {
        if (data.code === 0 && data.page) {
          this.poListData = data.page.list || []
        } else {
          this.poListData = []
        }
        this.poListLoading = false
      }).catch(() => {
        this.poListData = []
        this.poListLoading = false
      })
    },

    // 格式化日期为 yyyy-MM-dd
    formatDate (date) {
      if (!date) return ''
      // 如果已经是 yyyy-MM-dd 格式，直接返回
      if (typeof date === 'string' && date.length === 10) {
        return date
      }
      // 如果是时间戳或其他格式，进行转换
      const d = new Date(date)
      if (isNaN(d.getTime())) return date
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  },
  created () {
    this.getMainData()
  }
}
</script>

<style scoped lang="scss">
.customer-css {
  padding: 0;
  margin: 0;
  background: #fff;
}

.search-form-inline {
  background: #fff;
  padding: 0;
  margin-bottom: 0;
}

.search-row {
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
  gap: 0;
  margin-bottom: 0;
}

.search-item {
  flex: none;
  margin-bottom: 0;
  margin-right: 12px;
}

/* 统一标签样式：使用 Element UI 默认字体大小（14px），移除自定义颜色 */
.search-item /deep/ .el-form-item__label {
  padding-bottom: 5px;
  line-height: 1;
  height: auto;
}

.search-btn-item {
  flex: none;
  margin-bottom: 0;
  margin-right: 0;
}

.search-item /deep/ .el-form-item__content {
  line-height: normal;
}

/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}
</style>
