<template>
  <div class="customer-css">
    <div class="toolbar">
      <el-button type="primary" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
    </div>
    <!-- 列表 -->
    <el-table
      ref="mainTable"
      :data="dataList"
      :height="height"
      border
      highlight-current-row
      v-loading="loading"
      style="width: 100%">
      <el-table-column prop="requestNo" label="申请单号" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
      <el-table-column prop="orderRef1" label="PO号" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
      <el-table-column prop="supplierNo" label="供应商编码" header-align="center" align="left" min-width="120" show-overflow-tooltip/>
      <el-table-column prop="supplierName" label="供应商名称" header-align="center" align="left" min-width="200" show-overflow-tooltip/>
      <el-table-column prop="partNo" label="产品编码" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
      <el-table-column prop="partDesc" label="产品名称" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
      <el-table-column prop="qty" label="验货数量" header-align="center" align="right" width="120"/>
      <el-table-column prop="approveQty" label="检验通过数量" header-align="center" align="right" width="120"/>
      <el-table-column prop="status" label="状态" header-align="center" align="center" width="100">
        <template slot-scope="scope">
          {{ getStatusText(scope.row.statusDb) }}
        </template>
      </el-table-column>
      <el-table-column prop="needInspectDate" label="建议验货日期" header-align="center" align="center" width="120"/>
      <el-table-column prop="planStartDate" label="计划开始日期" header-align="center" align="center" width="120"/>
      <el-table-column prop="planEndDate" label="计划结束日期" header-align="center" align="center" width="120"/>
      <el-table-column prop="qcOperator" label="QC人员" header-align="center" align="center" width="100"/>
      <el-table-column prop="inspectAddress" label="验货地址" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
      <el-table-column prop="inspectContract" label="联系人" header-align="center" align="center" width="100"/>
      <el-table-column fixed="right" header-align="center" align="center" width="120" label="操作">
        <template slot-scope="scope">
          <a v-if="scope.row.statusDb === 'Scheduled'" class="customer-a" @click="startInspection(scope.row)">开始验货</a>
          <a v-if="scope.row.statusDb === 'Inspecting'" class="customer-a" @click="goToIQCResult(scope.row)">跳转</a>
        </template>
      </el-table-column>
    </el-table>

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

<script>
import { getMyInspectionList, createIqc, startInspection } from '@/api/inspection/inspectionRequestHeader.js'
import { actionIQCInspection, qcIQCInspectionSearch } from '@/api/qc/qc.js'


export default {
  components: {
  },
  name: 'MyInspectionList',
  data () {
    return {
      height: 400,
      loading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      searchData: {
        page: 1,
        limit: 50,
        statusDb: 'Scheduled,Inspecting'
      }
    }
  },
  mounted () {
    this.$nextTick(() => {

      this.height = window.innerHeight - 180

    })

    this.getList()
  },
  beforeDestroy () {

  },
  methods: {
    handleRefresh () {
      this.getList()
    },

    // 获取列表数据
    getList () {
      this.loading = true
      this.searchData.page = this.pageIndex
      this.searchData.limit = this.pageSize
      getMyInspectionList(this.searchData).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
        } else {
          this.$message.error((data && data.msg) || '获取列表失败')
        }
        this.loading = false
        this.$nextTick(() => {
          if (this.$refs.mainTable) {
            this.$refs.mainTable.doLayout()
          }
        })
      }).catch(() => {
        this.loading = false
      })
    },


    // 每页条数变化
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getList()
    },

    // 当前页变化
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getList()
    },

    // 状态转换
    getStatusText (statusDb) {
      const statusMap = {
        'Draft': '草稿',
        'Confirmed': '已确认',
        'Scheduled': '已排程',
        'Audited': '已审核',
        'Inspecting': '验货中',
        'Inspected': '已验货',
        'Completed': '已完成',
        'Cancelled': '已取消'
      }
      return statusMap[statusDb] || statusDb || '-'
    },

    // 跳转到 IQCResultEntry 页面
    goToIQCResult (row) {
      // 使用检验单号进行跳转
      const inspectionNo = row.inspectNo || ''
      if (!inspectionNo) {
        this.$message.warning('未找到检验单号')
        return
      }
      this.$router.push({
        name: 'qc-IQCResultEntry',
        query: {
          inspectionNo: inspectionNo
        }
      })
    },

    // 开始验货
    startInspection (row) {
      this.$confirm(`确认开始验货？\n申请单号：${row.requestNo}\n供应商：${row.supplierName}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 构建创建IQC的参数
        const iqcData = {
          site: row.site,
          requestNo: row.requestNo,
          itemNo: row.itemNo
        }

        // 第一步：调用 createIqc 接口
        createIqc(iqcData).then(({ data }) => {
          if (data.code === 0) {
            const inspectionNo = data.inspectionNo
            this.$message.success('IQC检验单创建成功：' + inspectionNo)

            // 第二步：createIqc 成功后，立即查询检验单并执行开始检验逻辑
            const searchParams = {
              site: row.site,
              userName: this.$store.state.user.name,
              inspectionNo: inspectionNo,
              inspectionTypeNo: '105',
              states: ['未开始', '待检验'],
              page: 1,
              limit: 1
            }
            
            qcIQCInspectionSearch(searchParams).then(({ data }) => {
              if (data.code === 0 && data.page.list && data.page.list.length > 0) {
                const iqcRecord = data.page.list[0]
                
                // 调用开始检验接口，更新状态为"待检验"
                const actionIQCData = {
                  site: iqcRecord.site,
                  buNo: iqcRecord.buNo,
                  inspectionNo: inspectionNo,
                  actionBy: this.$store.state.user.name,
                  state: '待检验',
                  equipmentList: []
                }
                
                actionIQCInspection(actionIQCData).then(({ data }) => {
                  if (data.code === 0) {
                    this.$message.success('开始检验成功')
                  } else {
                    this.$message.warning((data && data.msg) || '开始检验失败，但不影响后续操作')
                  }
                  
                  // 第三步：执行原有的 startInspection 逻辑
                  const startInspectionData = {
                    requestNo: row.requestNo,
                    itemNo: row.itemNo
                  }
                  startInspection(startInspectionData).then(({ data }) => {
                    if (data.code === 0) {
                      this.$message.success('开始验货成功')
                      this.getList()
                      this.$router.push({
                        name: 'qc-IQCResultEntry',
                        query: {
                          inspectionNo: inspectionNo
                        }
                      })
                    } else {
                      this.$message.error((data && data.msg) || '开始验货失败')
                    }
                  }).catch((error) => {
                    this.$message.error('开始验货失败：' + error.message)
                  })
                }).catch((error) => {
                  this.$message.warning('开始检验异常：' + error.message + '，继续执行后续操作')
                  // 即使开始检验失败，也继续执行 startInspection
                  const startInspectionData = {
                    requestNo: row.requestNo,
                    itemNo: row.itemNo
                  }
                  startInspection(startInspectionData).then(({ data }) => {
                    if (data.code === 0) {
                      this.$message.success('开始验货成功')
                      this.getList()
                      this.$router.push({
                        name: 'qc-IQCResultEntry',
                        query: {
                          inspectionNo: inspectionNo
                        }
                      })
                    } else {
                      this.$message.error((data && data.msg) || '开始验货失败')
                    }
                  }).catch((error) => {
                    this.$message.error('开始验货失败：' + error.message)
                  })
                })
              } else {
                this.$message.warning('未找到检验单信息，将直接执行开始验货')
                // 如果查询不到检验单，直接执行原有的 startInspection 逻辑
                const startInspectionData = {
                  requestNo: row.requestNo,
                  itemNo: row.itemNo
                }
                startInspection(startInspectionData).then(({ data }) => {
                  if (data.code === 0) {
                    this.$message.success('开始验货成功')
                    this.getList()
                    this.$router.push({
                      name: 'qc-IQCResultEntry',
                      query: {
                        inspectionNo: inspectionNo
                      }
                    })
                  } else {
                    this.$message.error((data && data.msg) || '开始验货失败')
                  }
                }).catch((error) => {
                  this.$message.error('开始验货失败：' + error.message)
                })
              }
            }).catch((error) => {
              this.$message.warning('查询检验单失败：' + error.message + '，将直接执行开始验货')
              // 查询失败，直接执行原有的 startInspection 逻辑
              const startInspectionData = {
                requestNo: row.requestNo,
                itemNo: row.itemNo
              }
              startInspection(startInspectionData).then(({ data }) => {
                if (data.code === 0) {
                  this.$message.success('开始验货成功')
                  this.getList()
                  this.$router.push({
                    name: 'qc-IQCResultEntry',
                    query: {
                      inspectionNo: inspectionNo
                    }
                  })
                } else {
                  this.$message.error((data && data.msg) || '开始验货失败')
                }
              }).catch((error) => {
                this.$message.error('开始验货失败：' + error.message)
              })
            })
          } else {
            this.$message.error((data && data.msg) || '创建IQC检验单失败')
          }
        }).catch((error) => {
          this.$message.error('创建IQC检验单失败：' + error.message)
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

<style scoped lang="scss">
.customer-css {
  padding: 5px;
}

.toolbar {
  margin-bottom: 8px;
}
</style>
