<template>
  <el-table :data="tableData" style="width: 100%" border v-loading="confirmLoading">
    <el-table-column prop="coilId" label="钢卷号">
      <template slot-scope="scope">
        <CoilNo :coil-no="scope.row.coil.enterCoilNo" :coil="scope.row.coil" />
      </template>
    </el-table-column>
    <el-table-column prop="coilId" label="当前钢卷号">
      <template slot-scope="scope">
        <current-coil-no :current-coil-no="scope.row.coil.currentCoilNo" />
      </template>
    </el-table-column>
    <el-table-column prop="materialTypeBefore" label="调拨前类型" width="100">
      <template slot-scope="scope">
        {{ scope.row.materialTypeBefore == '1' ? '原料' : '产品' }}
      </template>
    </el-table-column>
    <el-table-column prop="itemIdBefore" label="调拨前物料" width="260">
      <template slot-scope="scope">
        <ProductInfo v-if="scope.row.materialTypeBefore == '2'" :product="scope.row.oBefore" />
        <RawMaterialInfo v-else-if="scope.row.materialTypeBefore == '1'" :material="scope.row.oBefore" />
      </template>
    </el-table-column>
    <el-table-column prop="warehouseNameBefore" label="调拨前库区" width="180" />

    <el-table-column prop="materialTypeAfter" label="调拨后类型" width="100">
      <template slot-scope="scope">
        <el-select v-if="!scope.row.isConfirmed && canEdit" v-model="scope.row.materialTypeAfter"
          @change="handleMaterialChange(scope.row)" placeholder="请选择">
          <el-option label="原料" :value="1" />
          <el-option label="产品" :value="2" />
        </el-select>
        <div v-else>
          {{ scope.row.materialTypeAfter == '1' ? '原料' : '产品' }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="itemIdAfter" v-loading="materialLoading" label="调拨后物料" width="260">
      <template slot-scope="scope">
        <div v-loading="materialLoading" v-if="!scope.row.isConfirmed && canEdit">
          <RawMaterialSelect v-model="scope.row.itemIdAfter" v-if="scope.row.materialTypeAfter == '1'" />
          <ProductSelect v-model="scope.row.itemIdAfter" v-else-if="scope.row.materialTypeAfter == '2'" />
        </div>
        <div v-else>
          <ProductInfo v-if="scope.row.materialTypeAfter == '2'" :product="scope.row.oAfter" />
          <RawMaterialInfo v-else-if="scope.row.materialTypeAfter == '1'" :material="scope.row.oAfter" />
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="warehouseIdAfter" label="调拨后库区" width="200">
      <template slot-scope="scope">
        <el-select v-if="!scope.row.isConfirmed && canEdit" v-model="scope.row.warehouseIdAfter" @change="handleWarehouseChange(scope.row)" placeholder="请选择">
          <el-option v-for="item in warehouseList" :disabled="!item.isEnabled" :key="item.warehouseId"
            :label="item.warehouseName" :value="item.warehouseId" />
        </el-select>
        <div v-else>
          {{ scope.row.warehouseNameAfter }}
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="isTransferred" label="生效状态" width="200">
      <template slot-scope="scope">
        <el-tag :type="scope.row.isTransferred == '1' ? 'success' : 'info'">
          {{ scope.row.isTransferred == '1' ? '已生效' : '未生效' }}
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column type="action" label="操作" width="180" v-if="canEdit">
      <template slot-scope="scope">
        <div v-if="orderStatus == 0">
          <!-- <el-button icon="el-icon-check" size="mini" v-if="!scope.row.isConfirmed" @click="handleUpdate(scope.row)"
            :loading="buttonLoading">保存</el-button> -->
          <el-button icon="el-icon-close" size="mini" @click="handleCancel(scope.row)"
            :loading="buttonLoading">删除</el-button>
        </div>
        <div v-else>
          <!-- <el-button icon="el-icon-check" size="mini" v-if="!scope.row.isConfirmed" @click="handleConfirm(scope.row)"
            :loading="buttonLoading" :disabled="orderStatus != '2'">执行</el-button> -->
          <!-- <el-button icon="el-icon-close" size="mini" @click="handleCancel(scope.row)"
            :loading="buttonLoading" :disabled="orderStatus !== '2'">取消</el-button> -->
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { matchOrCreateMaterial, confirmTransferOrderItem, cancelTransferOrderItem, updateTransferOrderItem } from '@/api/wms/transferOrderItem'
import ProductSelect from "@/components/KLPService/ProductSelect";
import RawMaterialSelect from "@/components/KLPService/RawMaterialSelect";
import { listWarehouse } from '@/api/wms/warehouse';
import CoilNo from "@/components/KLPService/Renderer/CoilNo";
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";

export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
    canEdit: {
      type: Boolean,
      default: false
    },
    orderStatus: {
      type: String,
      default: ''
    }
  },
  components: {
    // WarehouseSelect,
    ProductSelect,
    RawMaterialSelect,
    CoilNo,
    ProductInfo,
    RawMaterialInfo
  },
  data() {
    return {
      tableData: [],
      materialLoading: false,
      warehouseList: [],
      buttonLoading: false,
      confirmLoading: false,
    }
  },
  mounted() {
    this.getWarehouseList()
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          // 预处理数据
          this.tableData = newVal.map(item => {
            const isEmpty = this.isEmpty(item);
            if (isEmpty) {
              return {
                ...item,
                oBefore: {
                  manufacturer: item.manufacturerBefore,
                  specification: item.specificationBefore,
                  material: item.materialBefore,
                  itemName: item.materialNameBefore,
                  surfaceTreatmentDesc: item.surfaceTreatmentBefore,
                  zincLayer: item.zincLayerBefore
                },
                oAfter: {
                  manufacturer: item.manufacturerAfter,
                  specification: item.specificationAfter,
                  material: item.materialAfter,
                  itemName: item.materialNameAfter,
                  surfaceTreatmentDesc: item.surfaceTreatmentAfter,
                  zincLayer: item.zincLayerAfter
                },
                isConfirmed: this.isConfirmed(item)
              }
            } else {
              return {
                ...item,
                oBefore: {
                  manufacturer: item.manufacturerBefore,
                  specification: item.specificationBefore,
                  material: item.materialBefore,
                  itemName: item.materialNameBefore,
                  surfaceTreatmentDesc: item.surfaceTreatmentBefore,
                  zincLayer: item.zincLayerBefore
                },
                // 将三个after字段设置为与before相同
                itemIdAfter: item.itemIdBefore,
                warehouseIdAfter: item.warehouseIdBefore,
                materialTypeAfter: item.materialTypeBefore,
                isConfirmed: this.isConfirmed(item)
              }
            }
          });
        }
      },
      immediate: true
    }
  },
  methods: {
    // 获取库区列表
    getWarehouseList() {
      listWarehouse().then(res => {
        this.warehouseList = res.data
      })
    },
    // 是否是已调拨状态
    isConfirmed(item) {
      // 只有三个after字段有值，才认为是已调拨状态
      // return item && item.itemIdAfter && item.warehouseIdAfter && item.materialTypeAfter
      return item.isTransferred == 1
    },
    // isEmpty 是否为空
    isEmpty(item) {
      return item && item.itemIdAfter && item.warehouseIdAfter && item.materialTypeAfter
    },
    handleUpdate(row) {
      updateTransferOrderItem(row).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        // 刷新数据
        this.$emit('refreshData')
      })
    },
    // 确认调拨
    handleConfirm(item) {
      this.buttonLoading = true
      confirmTransferOrderItem(item).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '确认调拨成功',
            type: 'success'
          })
          // 刷新数据
          this.$emit('refreshData')
        }
      }).finally(() => {
        this.buttonLoading = false
      })
    },
    handleConfirmAll() {
      const unconfirmedItems = this.tableData.filter(item => !item.isConfirmed && !item.isTransferred);
      if (unconfirmedItems.length === 0) {
        this.$message({ message: '没有可执行的调拨项', type: 'info' });
        return;
      }
      
      this.buttonLoading = true;
      const promises = unconfirmedItems.map(item => confirmTransferOrderItem(item));
      this.confirmLoading = true;
      return Promise.all(promises).then(results => {
        const successCount = results.filter(res => res.code === 200).length;
        if (successCount > 0) {
          this.$message({
            message: `成功执行 ${successCount} 项调拨`,
            type: 'success'
          });
          this.$emit('refreshData');
        }
      }).catch(error => {
        this.$message({
          message: '执行调拨时发生错误',
          type: 'error'
        });
      }).finally(() => {
        this.buttonLoading = false;
        this.confirmLoading = false;
      });
    },
    // 取消调拨
    handleCancel(item) {
      this.$confirm('确认取消调拨吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.buttonLoading = true
        cancelTransferOrderItem(item.orderItemId).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '取消调拨成功',
              type: 'success'
            })
            // 刷新数据
            this.$emit('refreshData')
          }
        }).finally(() => {
          this.buttonLoading = false
        })
      })

    },
    handleMaterialChange(row) {
      // 如果修改后是产品，说明切换前是原料
      const itemType = row.materialTypeAfter == '1' ? 'product' : 'raw_material'
      this.materialLoading = true
      matchOrCreateMaterial({
        itemType,
        itemId: row.itemIdAfter
      }).then(res => {
        row.itemIdAfter = res.data
        updateTransferOrderItem(row)
        this.materialLoading = false
      }).catch(() => {
        this.materialLoading = false
      })
    },
    handleWarehouseChange(row) {
      updateTransferOrderItem(row)
    }
  }
}
</script>
