<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.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">
          <div class="date-range">
            <el-date-picker v-model="searchData.requestDateStart" type="date" value-format="yyyy-MM-dd" placeholder="开始" style="width: 100px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.requestDateEnd" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 100px"/>
          </div>
        </el-form-item>
        <el-form-item label="状态" class="search-item">
          <el-select v-model="searchData.status" disabled style="width: 100%">
            <el-option label="已排程" value="Scheduled" />
          </el-select>
        </el-form-item>
      </div>

      <div class="search-row">
        <el-form-item label="申请人员" class="search-item">
          <el-input v-model="searchData.createBy" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="申请单号" class="search-item">
          <el-input v-model="searchData.requestNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="建议验货日期" class="search-item">
          <div class="date-range">
            <el-date-picker v-model="searchData.needInspectDateStart" type="date" value-format="yyyy-MM-dd" placeholder="开始" style="width: 100px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.needInspectDateEnd" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 100px"/>
          </div>
        </el-form-item>
        <el-form-item label="计划验货日期" class="search-item">
          <div class="date-range">
            <el-date-picker v-model="searchData.planStartDate" type="date" value-format="yyyy-MM-dd" placeholder="开始" style="width: 100px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.planEndDate" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 100px"/>
          </div>
        </el-form-item>
        <el-form-item label=" " class="search-item search-btn-item">
          <el-button type="primary" @click="getMainData" style="">查询</el-button>
        </el-form-item>
      </div>
    </el-form>

    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>

    <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
        v-for="(item,index) in columnArray1" :key="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 v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                             style="width: 100px; height: 100px"/></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer; color: #409EFF;" @click="viewDetail(scope.row)">查看</el-link>
        </template>
      </el-table-column>
    </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">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="base">
        <inspection-request-detail :detail-data="currentRow" />
      </el-tab-pane>
      <!-- 验货明细 -->
      <el-tab-pane label="验货明细" name="detail">
        <inspection-request-detail-tab ref="inspectionDetailTab" :detail-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
      <!-- 验货关联PO明细 -->
      <el-tab-pane label="验货关联PO明细" name="poDetail">
        <inspection-request-po-detail-tab ref="poDetailTab" :detail-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
      <!-- 验货结果 -->
      <el-tab-pane label="验货结果" name="result">
        <inspection-result-tab ref="resultTab" :detail-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
      <!-- 附件管理 -->
      <el-tab-pane label="附件管理" name="attachment">
        <inspection-request-attachment-tab ref="attachmentTab" :detail-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { searchInspectionRequestHeaderList } from '@/api/inspection/inspectionRequestHeader.js'
import Chooselist from '@/views/modules/common/Chooselist_eam'
import ComInspectionRequestDetail from './com_inspectionRequestDetail.vue'
import ComInspectionRequestDetailTab from './com_inspectionRequestDetailTab.vue'
import ComInspectionRequestPoDetailTab from './com_inspectionRequestPoDetailTab.vue'
import ComInspectionResultTab from './com_inspectionResultTab.vue'
import ComInspectionRequestAttachmentTab from './com_inspectionRequestAttachmentTab.vue'

export default {
  components: {
    Chooselist,
    InspectionRequestDetail: ComInspectionRequestDetail,
    InspectionRequestDetailTab: ComInspectionRequestDetailTab,
    InspectionRequestPoDetailTab: ComInspectionRequestPoDetailTab,
    InspectionResultTab: ComInspectionResultTab,
    InspectionRequestAttachmentTab: ComInspectionRequestAttachmentTab
  },
  data () {
    return {
      functionId: this.$route.meta.menuId,
      height: 400,
      detailHeight: 400,
      currentRow: {},
      tagNo: '',
      searchType: '',
      activeTab: 'base',
      searchData: {
        requestNo: '',
        supplierNo: '',
        supplierName: '',
        status: 'Scheduled',  // 固定状态为已排程
        qcOperator: this.$store.state.user.name,  // 固定为当前登录用户
        createBy: '',
        requestDateStart: '',
        requestDateEnd: '',
        needInspectDateStart: '',
        needInspectDateEnd: '',
        planStartDate: '',
        planEndDate: '',
        page: 1,
        limit: 50
      },
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      mainDataList: [],
      dataListLoading: false,
      columnArray1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1RequestNo',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'requestNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '申请单号',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1RequestDate',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'requestDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '申请日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1SupplierNo',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'supplierNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '供应商编码',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1SupplierName',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'supplierName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '供应商名称',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1CreateBy',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '申请人员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1NeedInspectDate',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'needInspectDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '建议验货日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1InspectAddress',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'inspectAddress',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '验货地址',
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1Contact',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'inspectContract',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '联系人',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1Remark',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'remark',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备注',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1Status',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'status',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '状态',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1PlanStartDate',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'planStartDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '计划验货日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'PendingTable1QcOperator',
          tableId: 'PendingTable1',
          tableName: '待验货申请单',
          columnProp: 'qcOperator',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'QC人员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        }
      ]
    }
  },
  watch: {
    // 监听路由参数变化（用于从我的代办页面跳转时）
    '$route.query': {
      handler (newQuery, oldQuery) {
        // 只有当路由参数发生变化时才重新查询（避免初始化时重复查询）
        const hasChanges = newQuery.planStartDate !== (oldQuery && oldQuery.planStartDate) ||
                          newQuery.planEndDate !== (oldQuery && oldQuery.planEndDate) ||
                          newQuery.requestNo !== (oldQuery && oldQuery.requestNo) ||
                          newQuery.supplierName !== (oldQuery && oldQuery.supplierName)

        if (hasChanges && (newQuery.planStartDate || newQuery.requestNo || newQuery.supplierName)) {
          // 设置日期筛选条件
          if (newQuery.planStartDate && newQuery.planEndDate) {
            this.searchData.planStartDate = newQuery.planStartDate
            this.searchData.planEndDate = newQuery.planEndDate
          }
          // 设置申请单号筛选条件
          if (newQuery.requestNo) {
            this.searchData.requestNo = newQuery.requestNo
          }
          // 设置供应商名称筛选条件
          if (newQuery.supplierName) {
            this.searchData.supplierName = newQuery.supplierName
          }
          this.getMainData()
        }
      },
      immediate: false
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.height = (window.innerHeight - 220) / 2
      this.detailHeight = (window.innerHeight - 220) / 2

      // 从路由参数获取筛选条件
      const query = this.$route.query

      // 设置日期筛选条件
      if (query.planStartDate && query.planEndDate) {
        this.searchData.planStartDate = query.planStartDate
        this.searchData.planEndDate = query.planEndDate
      }

      // 设置申请单号筛选条件
      if (query.requestNo) {
        this.searchData.requestNo = query.requestNo
      }

      // 设置供应商名称筛选条件
      if (query.supplierName) {
        this.searchData.supplierName = query.supplierName
      }

      // 执行查询
      this.getMainData()
    })
  },
  methods: {
    // 获取基础数据列表
    getBaseList (val, type) {
      this.tagNo = val
      this.searchType = type || ''
      this.$nextTick(() => {
        let strVal = ''
        let conSql = ''
        if (val === 1100) {
          strVal = this.searchData.supplierNo || ''
          conSql = " and site = '" + this.$store.state.user.site + "'"
        }
        if (val === 2016) {
          strVal = type === 'createBy' ? (this.searchData.createBy || '') : ''
        }
        this.$refs.baseList.init(val, strVal, conSql)
      })
    },

    /* 列表方法的回调 */
    getBaseData (val) {
      if (this.tagNo === 1100) {
        this.searchData.supplierNo = val.supplier_no || ''
        this.searchData.supplierName = val.supplier_name || ''
      }
      if (this.tagNo === 2016) {
        if (this.searchType === 'createBy') {
          this.searchData.createBy = val.username || val.user_display || val.name
        }
      }
    },

    // 查询数据 - 🔑 核心方法：固定状态和QC人员
    getMainData () {
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex

      // 🔑 固定状态为"已排程"
      this.searchData.status = 'Scheduled'

      // 🔑 固定QC人员为当前登录用户
      this.searchData.qcOperator = this.$store.state.user.name

      this.dataListLoading = true

      searchInspectionRequestHeaderList(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 === 'detail') {
        this.$nextTick(() => {
          if (this.$refs.inspectionDetailTab) {
            this.$refs.inspectionDetailTab.loadDetailList()
          }
        })
      } else if (tab.name === 'poDetail') {
        this.$nextTick(() => {
          if (this.$refs.poDetailTab) {
            this.$refs.poDetailTab.loadDetailList()
          }
        })
      } else if (tab.name === 'result') {
        this.$nextTick(() => {
          if (this.$refs.resultTab) {
            this.$refs.resultTab.loadDetailList()
          }
        })
      } else if (tab.name === 'attachment') {
        this.$nextTick(() => {
          if (this.$refs.attachmentTab) {
            this.$refs.attachmentTab.loadAttachmentTypeList()
          }
        })
      }
    },

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

    // 查看详情
    viewDetail (row) {
      this.changeData(row)
      // 可以跳转到详情页面或展开详情
    }
  },
  created () {
    // 不在 created 中自动查询，等待 mounted 处理
  }
}
</script>

<style scoped lang="scss">
.search-form-inline {
  background: #fff;
}

.search-row {
  display: flex;
  align-items: flex-end;
  flex-wrap: nowrap;
  gap: 15px;
}

.search-item {
  flex: none;
  margin-bottom: 10px;
}

.search-btn-item {
  flex: none;
  margin-bottom: 10px;
}

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

.search-item /deep/ .el-form-item__label {
  font-size: 13px;
  color: #606266;
  padding-bottom: 5px;
  line-height: 1;
  height: auto;
}

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

.date-range {
  display: flex;
  align-items: center;
}

.split {
  padding: 0 6px;
  color: #606266;
  font-size: 13px;
}

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