<template>
  <div class="customer-css">
    <!-- 操作按钮 -->
    <el-form :inline="true" style="margin-bottom: 2px;">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="showSelectPoDialog" :disabled="!supplierNo">选择PO</el-button>
    </el-form>

    <!-- 已关联PO列表表格 -->
    <el-table
      :data="issuePoList"
      border
      v-loading="loading"
      style="width: 100%;"
      :height="tableHeight"
      :header-cell-style="{ textAlign: 'center' }">
      <el-table-column
        prop="poNo"
        label="PO"
        width="180"
        align="center"/>

      <el-table-column
        prop="poDate"
        label="PO Date"
        width="180"
        align="center"/>

      <el-table-column
        prop="sku"
        label="SKU"
        min-width="250"
        show-overflow-tooltip/>

      <el-table-column
        prop="poQty"
        label="Qty"
        width="120"
        align="right"/>

      <el-table-column
        prop="shippedQty"
        label="Qty Shipped"
        width="110"
        align="right"/>

      <el-table-column
        label="操作"
        width="80"
        align="center"
        fixed="right">
        <template slot-scope="scope">
          <el-link type="danger" @click="handleDeletePo(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 选择PO对话框 -->
    <el-dialog
      title="选择PO"
      :visible.sync="selectPoDialogVisible"
      width="50%"
      top="10vh"
      :close-on-click-modal="false"
      append-to-body>

      <!-- 查询条件 -->
      <el-form :inline="true" label-position="top" class="search-form-inline">
        <div class="search-row">

          <el-form-item label="PO" class="search-item">
            <el-input
              v-model="poSearchData.poNo"
              placeholder="PO号"
              style="width:120px"
              @keyup.enter.native="loadAvailablePoList"/>
          </el-form-item>

          <el-form-item label="Part No" class="search-item">
            <el-input
              v-model="poSearchData.partNo"
              placeholder="料号"
              style="width:120px"
              @keyup.enter.native="loadAvailablePoList"/>
          </el-form-item>

          <el-form-item label="开始日期" class="search-item">
            <el-date-picker
              v-model="poSearchData.beginDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始日期"
              style="width:120px"
              clearable>
            </el-date-picker>
          </el-form-item>

          <el-form-item label="结束日期" class="search-item">
            <el-date-picker
              v-model="poSearchData.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="结束日期"
              style="width:120px"
              clearable>
            </el-date-picker>
          </el-form-item>

          <el-form-item label=" " class="search-item search-btn-item">
            <el-button
              type="primary"
              size="small"
              @click="loadAvailablePoList">
              查询
            </el-button>
          </el-form-item>

        </div>
      </el-form>

      <!-- 可用PO列表 -->
      <el-table
        ref="availablePoTable"
        :data="availablePoList"
        border
        size="mini"
        style="width: 100%; margin-top: 10px;"
        height="300"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="poNo" label="PO" width="120" />
        <el-table-column prop="poDate" label="PO Date" width="160" />
        <el-table-column prop="sku" label="SKU" />
        <el-table-column prop="qty" label="Qty" width="100" align="right" />
        <el-table-column prop="shippedQty" label="Qty Shipped" width="120" align="right" />
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="saveLoading" @click="handleSavePo">保存</el-button>
        <el-button @click="selectPoDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getIssuePoList, getAvailablePoList, saveIssuePo, deleteIssuePo } from '@/api/quality/qualityIssue.js'

export default {
  name: 'QualityIssuePoList',

  props: {
    issueNo: {
      type: String,
      default: ''
    },
    site: {
      type: String,
      default: ''
    },
    supplierNo: {
      type: String,
      default: ''
    },
    tableHeight: {
      type: Number,
      default: 400
    }
  },

  data() {
    return {
      issuePoList: [],
      loading: false,
      saveLoading: false,
      selectPoDialogVisible: false,
      availablePoList: [],
      selectedPoRows: [],
      poSearchData: {
        poNo: '',
        partNo: '',
        beginDate: '',
        endDate: ''
      }
    }
  },

  watch: {
    issueNo: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.loadIssuePoList()
        } else {
          this.issuePoList = []
        }
      }
    }
  },

  mounted() {
    // 组件加载时默认执行一次查询
    if (this.issueNo) {
      this.loadIssuePoList()
    }
  },

  methods: {
    // 供父组件调用的加载数据方法
    loadData() {
      this.loadIssuePoList()
    },

    // 加载已关联的PO列表
    loadIssuePoList() {
      if (!this.issueNo) {
        this.issuePoList = []
        return
      }

      this.loading = true
      getIssuePoList({
        site: this.site,
        issueNo: this.issueNo
      }).then(({ data }) => {
        if (data.code === 0) {
          this.issuePoList = data.data || []
        } else {
          this.issuePoList = []
        }
        this.loading = false
      }).catch(error => {
        console.error('加载PO列表失败:', error)
        this.loading = false
      })
    },

    // 显示选择PO对话框
    showSelectPoDialog() {
      if (!this.supplierNo) {
        this.$message.warning('请先选择有供应商的质量问题记录')
        return
      }
      this.selectPoDialogVisible = true
      // 重置搜索条件
      this.poSearchData = {
        poNo: '',
        partNo: '',
        beginDate: '',
        endDate: ''
      }
      this.loadAvailablePoList()
    },

    // 加载可用PO列表
    loadAvailablePoList() {
      const params = {
        site: this.site,
        supplierNo: this.supplierNo,
        poNo: this.poSearchData.poNo || undefined,
        partNo: this.poSearchData.partNo || undefined,
        beginDate: this.poSearchData.beginDate || undefined,
        endDate: this.poSearchData.endDate || undefined
      }

      getAvailablePoList(params).then(({ data }) => {
        if (data.code === 0) {
          this.availablePoList = (data.page && data.page.list) || []
          this.$nextTick(() => {
            if (this.$refs.availablePoTable) {
              this.$refs.availablePoTable.clearSelection()
            }
          })
        } else {
          this.availablePoList = []
        }
      }).catch(error => {
        console.error('加载可用PO列表失败:', error)
        this.availablePoList = []
      })
    },

    // 选择行变化
    handleSelectionChange(selection) {
      this.selectedPoRows = selection
    },

    // 保存选中的PO
    handleSavePo() {
      if (this.selectedPoRows.length === 0) {
        this.$message.warning('请至少选择一条PO记录')
        return
      }

      // 检查 site 和 issueNo 是否有效
      if (!this.site || !this.issueNo) {
        this.$message.error('缺少必要参数：site或issueNo为空')
        console.error('保存失败：site=', this.site, 'issueNo=', this.issueNo)
        return
      }

      const poList = this.selectedPoRows.map(row => ({
        poNo: row.poNo,
        itemNo: row.itemNo,
        partNo: row.partNo,
        sku: row.sku,
        qty: row.qty,
        shippedQty: row.shippedQty
      }))

      const params = {
        site: this.site,
        issueNo: this.issueNo,
        poList: poList
      }

      console.log('保存PO数据：', params)

      this.saveLoading = true
      saveIssuePo(params).then(({ data }) => {
        if (data.code === 0) {
          this.$message.success('保存成功')
          this.selectPoDialogVisible = false
          this.loadIssuePoList()
        } else {
          this.$message.error(data.msg || '保存失败')
        }
        this.saveLoading = false
      }).catch(error => {
        console.error('保存PO失败:', error)
        this.$message.error('保存失败，请稍后重试')
        this.saveLoading = false
      })
    },

    // 删除PO
    handleDeletePo(row) {
      this.$confirm('确定要删除该PO吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          site: this.site,
          issueNo: this.issueNo,
          poNo: row.poNo,
          itemNo: row.itemNo
        }

        deleteIssuePo(params).then(({ data }) => {
          if (data.code === 0) {
            this.$message.success('删除成功')
            this.loadIssuePoList()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除PO失败:', error)
          this.$message.error('删除失败，请稍后重试')
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.customer-css {
  padding: 0;
  margin: 0;
  background: #fff;
  height: 100%;
}
.search-form-inline {
  background: #fff;
  padding: 0;
  margin-bottom: 10px;
}

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

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

.search-item /deep/ .el-form-item__label {
  padding-bottom: 5px;
  line-height: 1;
  height: auto;
}

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

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

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

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

.dialog-footer {
  text-align: center;
}

// 表格样式统一 - 表头背景色改为青绿色
/deep/ .el-table {
  font-size: 12px;
}

/deep/ .el-table th {
  background-color: #17B3A3;
  color: #fff;
  font-weight: 500;
  text-align: center;
}

/deep/ .el-table tr {
  background-color: #fff;
}

/deep/ .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

/deep/ .el-link {
  font-size: 12px;
}
</style>
