<template>
  <div class="schedule-page-container">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" class="search-form-inline">
      <div class="search-row">
        <el-form-item class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(1100)"><a href="#">供应商编码</a></span>
          <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: 250px" @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: 150px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.requestDateEnd" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 150px"/>
          </div>
        </el-form-item>
        <el-form-item label="状态" class="search-item">
          <el-select v-model="searchData.status" style="width: 60%">
            <el-option label="已下达" value="AUDITED" />
            <el-option label="已排程" value="SCHEDULED" />
          </el-select>
        </el-form-item>
      </div>

      <div class="search-row">
        <el-form-item class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(2016, 'createBy')"><a href="#">申请人员</a></span>
          <el-input v-model="searchData.createBy" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(2016, 'qcOperator')"><a href="#">QC人员</a></span>
          <el-input v-model="searchData.qcOperator" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item class="search-item">
          <span style="cursor: pointer" slot="label" @click="openRequestNoChooser"><a href="#">申请单号</a></span>
          <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: 150px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.needInspectDateEnd" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 150px"/>
          </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: 150px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.planEndDate" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 150px"/>
          </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-dialog title="选择申请单号" :visible.sync="requestNoDialogVisible" width="800px" append-to-body :close-on-click-modal="false" @close="closeRequestNoChooser">
      <el-form :inline="true" size="mini" label-position="top">
        <el-form-item label="申请单号">
          <el-input v-model="requestNoSearchParam" style="width: 150px" @keyup.enter.native="loadRequestNoList"/>
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="loadRequestNoList">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="requestNoList" border height="300" @row-dblclick="selectRequestNo" v-loading="requestNoListLoading" highlight-current-row style="width: 100%">
        <el-table-column prop="requestNo" label="申请单号" header-align="center" align="left" min-width="150"/>
        <el-table-column prop="requestDate" label="申请日期" header-align="center" align="center" width="120"/>
        <el-table-column prop="supplierNo" label="供应商编码" header-align="center" align="left" width="120"/>
        <el-table-column prop="supplierName" label="供应商名称" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
        <el-table-column prop="status" label="状态" header-align="center" align="center" width="100"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="requestNoDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <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="150" label="操作">
        <template slot-scope="scope">
          <!-- 移除单个排程按钮，统一在页签中操作 -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <el-pagination style="margin-top: 5px"
                   @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"
                   small>
    </el-pagination>

    <!-- 详情页签 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="customer-tab" type="border-card">
      <!-- 排程视图 -->
      <el-tab-pane label="排程" name="schedule">
        <inspection-schedule-view
          ref="scheduleView"
          :request-nos="selectedRequestNos"
          :current-row="currentRow"
          :current-status-db="currentRow.statusDb"
          @schedule-success="handleScheduleSuccess" />
      </el-tab-pane>
      <!-- 基本信息 -->
      <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="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 ComInspectionRequestAttachmentTab from './com_inspectionRequestAttachmentTab.vue'
import ComInspectionScheduleView from './com_inspectionScheduleView.vue'

export default {
  components: {
    Chooselist,
    InspectionRequestDetail: ComInspectionRequestDetail,
    InspectionRequestDetailTab: ComInspectionRequestDetailTab,
    InspectionRequestPoDetailTab: ComInspectionRequestPoDetailTab,
    InspectionRequestAttachmentTab: ComInspectionRequestAttachmentTab,
    InspectionScheduleView: ComInspectionScheduleView
  },
  data () {
    return {
      functionId: this.$route.meta.menuId,
      height: 400,
      detailHeight: 400,
      currentRow: {},
      tagNo: '',
      searchType: '',
      requestNoDialogVisible: false,
      requestNoList: [],
      requestNoListLoading: false,
      requestNoSearchParam: '',
      activeTab: 'schedule',
      selectedRequestNos: [],
      searchData: {
        requestNo: '',
        supplierNo: '',
        supplierName: '',
        status: 'AUDITED',  // 默认状态为已审核
        qcOperator: '',
        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: 'ScheduleTable1RequestNo',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1RequestDate',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1SupplierNo',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1SupplierName',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1CreateBy',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1NeedInspectDate',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1InspectAddress',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1Contact',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1Remark',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1Status',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1PlanStartDate',
          tableId: 'ScheduleTable1',
          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: 'ScheduleTable1QcOperator',
          tableId: 'ScheduleTable1',
          tableName: '验货排程',
          columnProp: 'qcOperator',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'QC人员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        }
      ]
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 计算表格高度，留出查询表单、分页和页签的空间
      this.height = 250
      this.detailHeight = 300
      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) {
          if (type === 'createBy') {
            strVal = this.searchData.createBy || ''
          } else if (type === 'qcOperator') {
            strVal = this.searchData.qcOperator || ''
          }

          // 防止 Druid 拦截 where 1=1
          conSql = " and username <> '' "
        }
        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
        } else if (this.searchType === 'qcOperator') {
          this.searchData.qcOperator = val.username || val.user_display || val.name
        }
      }
    },

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

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

    // 处理排程成功事件 - 刷新整个页面数据
    handleScheduleSuccess() {
      // 重新查询主表数据（会触发 changeData，进而刷新页签）
      this.getMainData()
    },

    // 页签点击事件
    handleTabClick (tab) {
      if (tab.name === 'schedule') {
        // 排程页签
        this.$nextTick(() => {
          if (this.$refs.scheduleView) {
            this.$refs.scheduleView.loadQcList()
          }
        })
      } else 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 === 'attachment') {
        this.$nextTick(() => {
          if (this.$refs.attachmentTab) {
            this.$refs.attachmentTab.loadAttachmentTypeList()
          }
        })
      }
    },

    // 行点击事件
    changeData (row) {
      console.log('======changeData======')
      console.log('row=', row)

      this.currentRow = row ? JSON.parse(JSON.stringify(row)) : {}

      if (row && row.requestNo) {
        this.selectedRequestNos = [row.requestNo]
      } else {
        this.selectedRequestNos = []
      }

      // 如果当前在排程页签，刷新排程视图（重新加载QC列表+排程数据）
      if (this.activeTab === 'schedule' && this.$refs.scheduleView) {
        console.log('[排程] 刷新排程视图')
        this.$refs.scheduleView.loadQcList()
      }
    },
    // 主表格行样式
    mainTableRowClassName ({ row }) {
      return ''
    },

    // 打开申请单号选择弹窗
    openRequestNoChooser () {
      this.requestNoDialogVisible = true
      this.requestNoSearchParam = this.searchData.requestNo || ''
      this.$nextTick(() => {
        this.loadRequestNoList()
      })
    },

    // 加载申请单号列表
    loadRequestNoList () {
      this.requestNoListLoading = true
      const params = {
        requestNo: this.requestNoSearchParam,
        page: 1,
        limit: 200
      }
      searchInspectionRequestHeaderList(params).then(({ data }) => {
        if (data.code === 0 && data.page) {
          this.requestNoList = data.page.list || []
        } else {
          this.requestNoList = []
        }
        this.requestNoListLoading = false
      }).catch(() => {
        this.requestNoList = []
        this.requestNoListLoading = false
      })
    },

    // 选中申请单号
    selectRequestNo (row) {
      this.searchData.requestNo = row.requestNo || ''
      this.requestNoDialogVisible = false
    },

    // 关闭申请单号选择弹窗
    closeRequestNoChooser () {
      this.requestNoList = []
      this.requestNoSearchParam = ''
    },


  },
}
</script>
<style scoped lang="scss">
// 主容器 - 固定高度,滚动条
.schedule-page-container {
  height: calc(100vh - 120px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 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），移除自定义的13px和颜色 */
.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;
}

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

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

// 表格区域 - 自动高度
/deep/ .el-table {
  margin-bottom: 5px;
  flex-shrink: 0;
}

// 分页 - 自动高度
/deep/ .el-pagination {
  margin-bottom: 8px;
  flex-shrink: 0;
}

// 页签区域 - 占据剩余空间，内部滚动
/deep/ .customer-tab {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .el-tabs__header {
    margin-bottom: 0;
    flex-shrink: 0;
  }

  .el-tabs__content {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 10px !important;
  }
}
</style>
