<template>
  <div class="mod-config">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item label="Customer">
        <el-input v-model="searchData.customer" clearable style="width: 120px" @keyup.enter.native="getDataList"></el-input>
      </el-form-item>
      <el-form-item label="供应商名称">
        <el-input v-model="searchData.supplierName" clearable style="width: 140px" @keyup.enter.native="getDataList"></el-input>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchData.partNo" clearable style="width: 120px" @keyup.enter.native="getDataList"></el-input>
      </el-form-item>
      <el-form-item label="Buyer">
        <el-input v-model="searchData.buyer" clearable style="width: 120px" @keyup.enter.native="getDataList"></el-input>
      </el-form-item>
      <el-form-item label="PO No">
        <el-input v-model="searchData.poNo" clearable style="width: 140px" @keyup.enter.native="getDataList"></el-input>
      </el-form-item>
      <el-form-item label="SKU">
        <el-input v-model="searchData.sku" clearable style="width: 120px" @keyup.enter.native="getDataList"></el-input>
      </el-form-item>
      <el-form-item label="Status">
        <el-select v-model="searchData.status" placeholder="请选择" style="width:100px" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="已下达" value="已下达"></el-option>
          <el-option label="已取消" value="已取消"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <el-form :inline="true" label-position="top" style="margin-top:10px">
      <el-form-item>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button type="primary" @click="exportExcel" style="margin-left: 2px">导出</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      ref="poTable"
      :height="height"
      :data="dataList"
      border
      highlight-current-row
      v-loading="loading"
      @row-click="changeData"
      style="width: 100%;">
      <el-table-column
        v-for="(item, index) in visibleColumns"
        :key="item.serialNumber || index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed === '' ? false : item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span>{{ scope.row[item.columnProp] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @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">
      <!-- 物流信息 -->
      <el-tab-pane label="物流" name="logistics">
        <logistics-po-list ref="logisticsPoList" />
      </el-tab-pane>
      <!-- 验货明细 -->
      <el-tab-pane label="验货明细" name="inspectionDetail">
        <inspection-detail-list ref="inspectionDetailList" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { searchPoDetailPage } from '@/api/order/poOrder.js'
import excel from '@/utils/excel-util.js'
import LogisticsPoList from './com_logisticsPoList.vue'
import InspectionDetailList from './com_inspectionDetailList.vue'

export default {
  components: {
    LogisticsPoList,
    InspectionDetailList
  },
  name: 'PoOrderQuery',
  data() {
    return {
      loading: false,
      exportLoading: false,
      height: 400,
      activeTab: 'logistics',
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataList: [],
      currentRow: {},
      searchData: {
        site: this.$store.state.user.site,
        customer: '',
        buyer: '',
        poNo: '',
        sku: '',
        status: '',
        supplierName: '',
        partNo: '',
        feeDateStart: '',
        feeDateEnd: ''
      },
      // 列配置（与原始页面保持一致，但隐藏编辑相关列）
      columnList: [
        {
          columnProp: 'customer',
          columnLabel: 'Customer',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'buyer',
          columnLabel: 'Buyer',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'supplierName',
          columnLabel: 'Vendor Name',
          align: 'center',
          columnWidth: 120,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'shortOffice',
          columnLabel: 'V_Short_Office',
          align: 'center',
          columnWidth: 110,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'shortNpc',
          columnLabel: 'V_Short_NPC',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'poNo',
          columnLabel: 'PO_No',
          align: 'center',
          columnWidth: 120,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'partNo',
          columnLabel: 'Item',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'category',
          columnLabel: 'Category',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'sku',
          columnLabel: 'SKU',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'price',
          columnLabel: 'Unit Price',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'qty',
          columnLabel: 'PO Qty',
          align: 'center',
          columnWidth: 80,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'value',
          columnLabel: 'PO Value',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'shipQty',
          columnLabel: 'A-Qty',
          align: 'center',
          columnWidth: 80,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'sumPrice',
          columnLabel: 'A-Value',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'departure',
          columnLabel: 'Departure Port',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'destination',
          columnLabel: 'Destination Port',
          align: 'center',
          columnWidth: 110,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'shipVia',
          columnLabel: 'Method',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'orderDate',
          columnLabel: 'Buyer Release Date',
          align: 'center',
          columnWidth: 130,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'enquiry',
          columnLabel: 'Planner Release Date',
          align: 'center',
          columnWidth: 140,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'status',
          columnLabel: 'Status',
          align: 'center',
          columnWidth: 80,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'confirmed',
          columnLabel: 'PI Confirmed Date',
          align: 'center',
          columnWidth: 120,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'wantReceiveDate',
          columnLabel: 'Original Arrival Date',
          align: 'center',
          columnWidth: 130,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'narrival',
          columnLabel: 'Final Confirmed Arrival Date',
          align: 'center',
          columnWidth: 110,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'crd',
          columnLabel: 'PI Confirmed CRD',
          align: 'center',
          columnWidth: 120,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'inspection',
          columnLabel: 'Inspection Date',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'realCrd',
          columnLabel: 'Actual Completion Date',
          align: 'center',
          columnWidth: 150,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'eta',
          columnLabel: 'ETA',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'flexid',
          columnLabel: 'Flexport Id',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'obd',
          columnLabel: 'On Board Date',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'docSent',
          columnLabel: 'Doc Sent',
          align: 'center',
          columnWidth: 90,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'telexRelease',
          columnLabel: 'Telex Release',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'advancePayment',
          columnLabel: 'Advance Payment',
          align: 'center',
          columnWidth: 120,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'advancePaid',
          columnLabel: 'Advanc Paid',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'createTime',
          columnLabel: 'Create Date',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'planner',
          columnLabel: 'M-Planner',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'edit',
          columnLabel: 'Edit Date',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'endPlanner',
          columnLabel: 'Last Editor',
          align: 'center',
          columnWidth: 100,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'remarkDelay',
          columnLabel: 'Remark Delay',
          align: 'center',
          columnWidth: 110,
          showOverflowTooltip: true,
          headerAlign: 'center'
        },
        {
          columnProp: 'remark',
          columnLabel: 'Comments',
          align: 'center',
          columnWidth: 140,
          showOverflowTooltip: true,
          headerAlign: 'center'
        }
      ]
    }
  },
  computed: {
    visibleColumns() {
      return this.columnList.filter(c => !c.columnHidden)
    }
  },
  created() {
    this.getDataList()
  },
  mounted() {
    this.$nextTick(() => {
      // 模仿 supplierList.vue 的高度分配方式
      this.height = (window.innerHeight - 220) / 2
    })
  },
  methods: {
    // 查询数据
    getDataList() {
      this.loading = true
      const params = {
        ...this.searchData,
        page: this.pageIndex,
        limit: this.pageSize
      }
      searchPoDetailPage(params).then(({ data }) => {
        if (data.code === 0) {
          this.dataList = data.page.list || []
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount

          // 如果有数据，默认选中第一行并触发页签查询
          if (this.dataList.length > 0) {
            this.$nextTick(() => {
              if (this.$refs.poTable) {
                this.$refs.poTable.setCurrentRow(this.dataList[0])
              }
              this.changeData(this.dataList[0])
            })
          }
        } else {
          this.$message.error((data && data.msg) || '获取列表失败')
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('请求失败')
      })
    },

    // 重置查询条件
    resetSearch() {
      this.searchData = {
        site: this.$store.state.user.site,
        customer: '',
        buyer: '',
        poNo: '',
        sku: '',
        status: '',
        supplierName: '',
        partNo: '',
        feeDateStart: '',
        feeDateEnd: ''
      }
      this.pageIndex = 1
      this.getDataList()
    },
    // 导出
    exportExcel () {
      console.log('开始导出...')

      // 生成文件名
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const exportName = `PO订单列表${year}${month}${day}${hour}${minute}${second}`

      // 获取当前查询条件
      const exportParams = {
        ...this.searchData,
        limit: 99999,
        page: 1
      }

      console.log('导出参数:', exportParams)

      try {
        excel.exportTable({
          url: 'pODetail/page',
          columnMapping: this.visibleColumns,
          mergeSetting: [],
          params: exportParams,
          fileName: exportName + '.xlsx',
          rowFetcher: res => {
            console.log('导出接口响应:', res)
            // 接口返回 {code, msg, rows} 结构
            return { rows: (res.data && res.data.rows) || [] }
          },
          columnFormatter: [],
          dropColumns: []
        })
        console.log('导出请求已发送')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败: ' + error.message)
      }
    },

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

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

    // 行点击事件（模仿 supplierList.vue 的 changeData 模式）
    changeData(row) {
      this.currentRow = JSON.parse(JSON.stringify(row))
      this.refreshCurrentTabTable()
    },

    // 刷新当前页签的表格数据（模仿 supplierList.vue 的 refreshCurrentTabTable）
    refreshCurrentTabTable() {
      if (this.currentRow === '' || this.currentRow === null) {
        this.currentRow = { flexid: '', supplierNo: '' }
      }
      if (this.activeTab === 'logistics') {
        this.refreshLogisticsTable()
      }
      if (this.activeTab === 'inspectionDetail') {
        this.refreshInspectionTable()
      }
    },

    // 刷新物流页签表格（模仿 supplierList.vue 的 refreshShareTable）
    refreshLogisticsTable() {
      let inData = {
        flexId: this.currentRow.flexid,
        supplierNo: this.currentRow.supplierNo,
        site: this.$store.state.user.site,
        height: Number(this.height) - 20
      }
      this.$refs.logisticsPoList.init(inData)
    },

    // 刷新验货明细页签表格
    refreshInspectionTable() {
      let inData = {
        site: this.$store.state.user.site,
        orderRef1: this.currentRow.poNo || '',
        height: Number(this.height) - 20
      }
      this.$refs.inspectionDetailList.init(inData)
    },

    // 页签点击事件（模仿 supplierList.vue 的 tabClick）
    handleTabClick(tab, event) {
      this.refreshCurrentTabTable()
    }
  }
}
</script>

<style scoped lang="scss">
.el-table /deep/ .cell {
  height: auto;
  line-height: 1.5;
}

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