<template>
  <div class="app-container">
    <el-card style="height: 850px">
      <div style="margin-top: 7px; margin-bottom: 7px">
        <span class="show-text">订单编号:</span>
        <el-input v-model="equipmentName" placeholder="订单编号" size="small" clearable style="width:200px;margin-left: 0px"/>
        <span class="show-text">单据状态:</span>
        <el-select v-model="equipmentType" placeholder="单据状态" filterable size="small" style="width:200px" clearable >
          <el-option label="全部" value="全部" />
          <el-option label="已关闭" value="已关闭" />
          <el-option label="未关闭" value="未关闭" />
          <el-option label="可关闭" value="可关闭" />
          <el-option label="SAP未关闭" value="SAP未关闭" />
          
        </el-select>
        <span class="show-text">单据状态:</span>
        <el-select v-model="orderType" placeholder="属性" filterable size="small" style="width:200px" clearable >
          <el-option label="全部" value="全部" />
          <el-option label="机加" value="机加" />
          <el-option label="装配" value="装配" />
        </el-select>
        <!-- <el-input v-model="opName" placeholder="工位" size="small" clearable style="width:200px;margin-left: 0px"/> -->
        <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 20px" plain @click="pageSize = 20;pageCurrent = 1;searchTable()">查询</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" style="margin-left: 10px" plain :loading="batchConfirming" :disabled="selectedConfirmRows.length === 0" @click="handleBatchConfirm">批量确认</el-button>
        <el-button type="danger" icon="el-icon-circle-close" size="small" style="margin-left: 10px" plain :loading="batchClosing" :disabled="selectedCloseRows.length === 0" @click="handleBatchClose">批量关闭</el-button>

      </div>
      <div>
        <el-table :data="tableData" border size="small" stripe highlight-current-row height="740px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" width="55" :selectable="isRowSelectable" />
          <el-table-column label="订单编号" prop="订单编号" align="center" width="80px" />
          <el-table-column label="合同号" prop="合同号" align="center" width="120px" />
          <el-table-column label="产品编码" prop="产品编码" align="center" width="250px" />
          <el-table-column label="产品名称" prop="产品名称" align="center" width="120px" />
          <el-table-column label="计划数量" prop="计划数量" align="center" width="80px" />
          <el-table-column label="入库数量" prop="入库数量" align="center" width="80px" />
          <el-table-column label="终检不合格" prop="终检不合格数合计" align="center" width="100px" />
          <el-table-column label="终检合格" prop="终检合格数合计" align="center" width="80px" />
          <!-- <el-table-column label="收检合格" prop="合格数合计" align="center" width="80px" />
          <el-table-column label="收检不合格" prop="不合格数合计" align="center" width="100px" /> -->
          
  
          <el-table-column label="操作" align="center" width="250px" >
            <template slot-scope="scope">
              <el-button type="primary" size="mini"  @click="handledo(scope.row)" :disabled="scope.row.确认状态 == 1">确认</el-button>
              <el-button type="primary" size="mini"  @click="handleDelete(scope.row)" :disabled="scope.row.确认状态 != 1 || scope.row.单据状态 =='已关闭'">关闭</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { patchB1 } from '@/api/b1s';
export default {
  data() {
    return {
      routineCheckType: [],
      dialogFormVisible: false,
      title: '',
      equipmentValue: '',
      equipmentName: '',
      equipmentType: '可关闭',
      orderType:'机加',
      opName: '',
      process: [],
      form: {
        设备名称: '',
        设备型号: '',
        设备类型: '',

      },
      basedatalx:[{
        
      }],
      original: '',

      tableData: [], // 设备信息表
      multipleSelection: [],
      batchConfirming: false,
      batchClosing: false

    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ]),
    selectedConfirmRows() {
      return this.multipleSelection.filter(row => this.isRowConfirmable(row))
    },
    selectedCloseRows() {
      return this.multipleSelection.filter(row => this.isRowCloseSelectable(row))
    }
  },
  created() {
    this.searchTable()
    // this.getbasedata()
    // this.getRoutineCheckType()
  },
  methods: {
    
    searchTable() {

      var param = []
      param.push(["订单号",this.equipmentName])
      param.push(["单据状态",this.equipmentType])
      param.push(["属性",this.orderType])
      var Data = this.CreateData('11', '计划排产_生产订单关闭_查询全部订单', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data
      })
    },
    
    isRowConfirmable(row) {
      return row.确认状态 != 1
    },
    isRowCloseSelectable(row) {
      return row.确认状态 == 1 && row.单据状态 !== '已关闭'
    },
    isRowSelectable(row) {
      return this.isRowConfirmable(row) || this.isRowCloseSelectable(row)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async confirmOrder(row) {
      var param = []
      param[0] = ['订单号', row.订单编号]
      var Data = this.CreateData('12', '计划排产_生产订单关闭_确认订单', param)
      const response = await this.ExecDatabase(Data)
      const result = response.data && response.data[0] ? response.data[0] : {}
      if (String(result.result) === '1') {
        return { success: true }
      }
      return {
        success: false,
        message: result.提示信息 || '确认失败'
      }
    },
    async closeOrder(row) {
      var param = []
      param[0] = ['订单号', row.订单编号]
      var Data = this.CreateData('11', '计划排产_生产订单关闭_关闭订单', param)
      const response = await this.ExecDatabase(Data)
      const result = response.data && response.data[0] ? response.data[0] : {}
      if (String(result.result) === '1') {
        await patchB1('/ProductionOrders(' + row.订单编号 + ')', {
          AbsoluteEntry: row.订单编号,
          ProductionOrderStatus: 'boposClosed'
        })
        return { success: true }
      }
      return {
        success: false,
        message: result.提示信息 || '关闭失败'
      }
    },
    async handleDelete(row) {
      try {
        const result = await this.closeOrder(row)
        if (result.success) {
          this.$message.success('关闭成功')
          this.pageCurrent = 1
          this.searchTable()
        } else {
          this.$message.error(result.message)
        }
      } catch (error) {
        this.$message.error(error.message || '关闭失败')
      }
    },
    async handleBatchClose() {
      const rows = this.selectedCloseRows
      if (rows.length === 0) {
        this.$message.warning('请选择可关闭的订单')
        return
      }

      const confirmResult = await this.$confirm(`确认批量关闭选中的 ${rows.length} 个订单吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => false)

      if (!confirmResult) {
        return
      }

      this.batchClosing = true
      const failedOrders = []
      for (const row of rows) {
        try {
          const result = await this.closeOrder(row)
          if (!result.success) {
            failedOrders.push(`${row.订单编号}:${result.message}`)
          }
        } catch (error) {
          failedOrders.push(`${row.订单编号}:${error.message || '关闭失败'}`)
        }
      }

      this.batchClosing = false
      this.multipleSelection = []
      this.pageCurrent = 1
      this.searchTable()

      const successCount = rows.length - failedOrders.length
      if (failedOrders.length === 0) {
        this.$message.success(`批量关闭成功，共 ${successCount} 个订单`)
        return
      }

      this.$message.warning(`批量关闭完成，成功 ${successCount} 个，失败 ${failedOrders.length} 个：${failedOrders.join('；')}`)
    },
    async handledo(row){
      try {
        const result = await this.confirmOrder(row)
        if (result.success) {
          this.$message.success('确认成功')
          this.pageCurrent = 1
          this.searchTable()
        } else {
          this.$message.error(result.message)
        }
      } catch (error) {
        this.$message.error(error.message || '确认失败')
      }
    },
    async handleBatchConfirm() {
      const rows = this.selectedConfirmRows
      if (rows.length === 0) {
        this.$message.warning('请选择可确认的订单')
        return
      }

      const confirmResult = await this.$confirm(`确认批量确认选中的 ${rows.length} 个订单吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => false)

      if (!confirmResult) {
        return
      }

      this.batchConfirming = true
      const failedOrders = []
      for (const row of rows) {
        try {
          const result = await this.confirmOrder(row)
          if (!result.success) {
            failedOrders.push(`${row.订单编号}:${result.message}`)
          }
        } catch (error) {
          failedOrders.push(`${row.订单编号}:${error.message || '确认失败'}`)
        }
      }

      this.batchConfirming = false
      this.multipleSelection = []
      this.pageCurrent = 1
      this.searchTable()

      const successCount = rows.length - failedOrders.length
      if (failedOrders.length === 0) {
        this.$message.success(`批量确认成功，共 ${successCount} 个订单`)
        return
      }

      this.$message.warning(`批量确认完成，成功 ${successCount} 个，失败 ${failedOrders.length} 个：${failedOrders.join('；')}`)
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>
<style>
.el-button {
  width: auto !important; 
}
</style>