<template>
  <div>
    <el-table 
      v-loading="loading" 
      :data="list"
      border
      style="width: 100%; margin-bottom: 20px;"
    >
      <el-table-column label="产品" align="center">
        <template slot-scope="scope">
          <ProductInfo :product-id="scope.row.productId">
            <template #default="{ product }">
              {{ product.productName }}<span v-if="product.productCode">({{ product.productCode }})</span>
            </template>
          </ProductInfo>
        </template>
      </el-table-column>
      <el-table-column label="BOM" align="center">
        <template slot-scope="scope">
          <BomInfoMini item-type="product" :item-id="scope.row.productId" />
        </template>
      </el-table-column>
      <el-table-column label="产品数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleProcessTask(scope.row)">工序</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="工序" :visible.sync="processTaskDialogVisible" width="80%">
      <el-table 
        :data="processTaskList" 
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        
        <el-table-column 
          label="工序顺序" 
          prop="sequence" 
          align="center"
        >
          <template slot-scope="scope">
            <el-input 
              v-model="scope.row.sequence" 
              size="mini" 
              type="number"
              style="width: 80px;"
            />
          </template>
        </el-table-column>
        
        <el-table-column 
          label="工艺" 
          prop="processId" 
          align="center"
        >
          <template slot-scope="scope">
            <CraftSelect v-model="scope.row.processId" />
          </template>
        </el-table-column>
        
        <el-table-column 
          label="任务数量" 
          prop="taskQuantity" 
          align="center"
        >
          <template slot-scope="scope">
            <el-input 
              v-model="scope.row.taskQuantity" 
              size="mini" 
              type="number"
              style="width: 100px;"
            />
          </template>
        </el-table-column>
        
        <el-table-column 
          label="任务状态" 
          prop="taskStatus" 
          align="center"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.taskStatus" placeholder="请选择任务状态" size="mini">
              <el-option v-for="item in dict.type.process_task_status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDelete(scope.$index)">删除</el-button>
            <el-button type="text" size="small" @click="handleSave(scope.row)">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 新增按钮区域 -->
      <div style="margin-top: 15px; text-align: right;">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="handleAddProcessTask"
        >
          新增工序
        </el-button>
        <!-- <el-button 
          type="success" 
          style="margin-left: 10px;"
          @click="handleSaveProcessTasks"
        >
          保存所有工序
        </el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ProductSelect from '@/components/KLPService/ProductSelect';
import { ProductInfo } from '@/components/KLPService';
import BomInfoMini from '@/components/KLPService/Renderer/BomInfoMini.vue';
import { listProcessTask, addProcessTask, updateProcessTask } from '@/api/wms/processTask';
import CraftSelect from '@/components/KLPService/CraftSelect';

export default {
  name: "OrderDetailPanel",
  dicts: ['order_status', 'process_task_status'],
  props: {
    list: {
      type: Array,
      required: true
    },
    planId: {
      type: [String, Number, undefined],
      required: true
    }
  },
  components: {
    ProductSelect,
    ProductInfo,
    BomInfoMini,
    CraftSelect
  },
  data() {
    return {
      loading: false,
      orderDetailList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        orderId: this.orderId,
        productId: undefined,
        quantity: undefined,
        unit: undefined,
        // 排序参数
        orderByColumn: '',
        isAsc: 'asc'
      },
      processTaskDialogVisible: false,
      processTaskList: [],
      form: {},
      currentProductId: null,
      currentProductCount: 0,
    };
  },
  methods: {
    handleProcessTask(row) {
      this.processTaskDialogVisible = true;
      this.currentProductId = row.productId;
      this.currentProductCount = row.quantity;
      this.form = {
        productId: row.productId,
        planId: this.planId,
        // 重置排序参数
        orderByColumn: '',
        isAsc: 'asc'
      };
      this.getProcessTaskList();
    },
    
    // 获取工序任务列表
    getProcessTaskList() {
      this.loading = true;
      // 将排序参数添加到请求中
      const params = {
        ...this.form,
        orderByColumn: this.queryParams.orderByColumn,
        isAsc: this.queryParams.isAsc
      };
      
      listProcessTask(params).then(res => {
        this.processTaskList = res.rows || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    // 处理排序变化
    handleSortChange({ column, prop, order }) {
      if (order) {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
      } else {
        this.queryParams.orderByColumn = '';
        this.queryParams.isAsc = 'asc';
      }
      // 重新获取数据
      this.getProcessTaskList();
    },
    
    // 新增工序
    handleAddProcessTask() {
      const newSequence = 
      this.processTaskList.length >= 1 ?
        Math.max(...this.processTaskList.map(item => item.sequence || 0)) + 1 
        : 1;
      // 添加新的工序行
      this.processTaskList.push({
        id: null, // 新记录ID为空
        productId: this.currentProductId,
        planId: this.planId,
        processId: '',
        taskQuantity: this.currentProductCount,
        taskStatus: 'pending',
        sequence: newSequence
      });
    },
    
    // 删除工序
    handleDelete(index) {
      this.$confirm('确定要删除这条工序吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.processTaskList.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 保存所有工序
    handleSaveProcessTasks() {
      // 验证数据
      const invalidItems = this.processTaskList.filter(item => 
        !item.processId || !item.quantity || !item.taskStatus
      );
      
      if (invalidItems.length > 0) {
        this.$message.error('请完善所有工序的工艺、数量和状态信息');
        return;
      }
      
      this.loading = true;
      saveProcessTasks({
        productId: this.currentProductId,
        planId: this.planId,
        tasks: this.processTaskList
      }).then(res => {
        this.$message.success('保存成功');
        this.getProcessTaskList(); // 重新加载数据
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    // 查看工序详情
    handleSave(row) {
      if (row.taskId) {
        updateProcessTask(row).then(_ => {
          this.$message.success('保存成功')
        })
      } else {
        addProcessTask(row).then(_ => {
          this.$message.success('保存成功')
        })
      }
    }
  }
};
</script>

<style scoped>
::v-deep .el-table__header-wrapper th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table-column--sortable .el-table-header__sort {
  color: #606266;
}

::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

::v-deep .el-input--mini {
  width: 100px;
}
</style>
