<template>
  <div class='pending-tasks'>
    <el-table
      v-loading='loading'
      :data='taskList'
      border
      stripe
      style='width: 100%'
      @selection-change='handleSelectionChange'
    >
      <el-table-column type='selection' width='55' align='center' />
      <el-table-column label='工单号' prop='planCode' width='150' align='center' />
      <el-table-column label='产品编码' prop='materialCode' width='150' align='center' />
      <el-table-column label='产品名称' prop='materialName' width='200' align='center' show-overflow-tooltip />
      <el-table-column label='工序名称' prop='processName' width='150' align='center' />
      <el-table-column label='计划数量' prop='planAmount' width='100' align='center' />
      <el-table-column label='已报工数量' prop='completeAmount' width='100' align='center' />
      <el-table-column label='排产日期' prop='planBeginTime' width='150' align='center'>
        <template #default='scope'>
          <span>{{ parseTime(scope.row.planBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label='工单状态' prop='planStatus' width='100' align='center'>
        <template #default='scope'>
          <dict-tag :options='mes_plan_status' :value='scope.row.planStatus' />
        </template>
      </el-table-column>
      <el-table-column label='操作' width='120' align='center' fixed='right'>
        <template #default='scope'>
          <el-button
            link
            type='primary'
            @click='handleStart(scope.row)'
            :disabled='scope.row.planStatus === "2"'
          >
            开始
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show='total > 0'
      :total='total'
      v-model:page='queryParams.pageNum'
      v-model:limit='queryParams.pageSize'
      @pagination='getList'
    />
  </div>
</template>

<script setup name='PendingTasks' lang='ts'>
import { ref, onMounted, getCurrentInstance, toRefs } from 'vue';
import { listPlanInfo, startPlanInfo } from '@/api/mes/planInfo';
import { PlanInfoVO, PlanInfoQuery } from '@/api/mes/planInfo/types';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as any;
const { mes_plan_status } = toRefs<any>(proxy?.useDict('mes_plan_status'));

const props = defineProps<{
  workstationId?: string | number;
}>();

const emit = defineEmits(['issue']);

const loading = ref(false);
const taskList = ref<PlanInfoVO[]>([]);
const total = ref(0);
const selectedRows = ref<PlanInfoVO[]>([]);

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  planStatus: '1', // 已派工状态
  releaseType: '3' // 工位类型
});

// 获取待处理任务列表
const getList = async () => {
  loading.value = true;
  try {
    const query: any = {
      ...queryParams.value
    };
    // 如果有工位ID，添加到查询参数中
    if (props.workstationId) {
      query.releaseId = props.workstationId;
    }
    const res = await listPlanInfo(query as PlanInfoQuery);
    taskList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取待处理任务列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 选择变化
const handleSelectionChange = (selection: PlanInfoVO[]) => {
  selectedRows.value = selection;
};

// 开始工单
const handleStart = async (row?: PlanInfoVO) => {
  const targetRow = row || selectedRows.value[0];
  if (!targetRow) {
    proxy?.$modal.msgWarning('请选择要开始的工单！');
    return;
  }

  // 检查工单状态，已开始的工单不能再次开始
  if (targetRow.planStatus === '2') {
    proxy?.$modal.msgWarning('该工单已开始，不能重复开始！');
    return;
  }

  try {
    await proxy?.$modal.confirm(`是否开始工单 "${targetRow.planCode}"？`);
    loading.value = true;

    // 调用开始接口，更新工单状态为已开始
    await startPlanInfo(targetRow.planId);

    proxy?.$modal.msgSuccess('开始成功');
    emit('issue', targetRow.planCode);
    await getList();
  } catch (error: any) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('开始失败');
      console.error('开始工单失败:', error);
    }
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refresh = () => {
  getList();
};

defineExpose({
  refresh
});

onMounted(() => {
  getList();
});
</script>

<style scoped lang='scss'>
.pending-tasks {
  width: 100%;
  height: 100%;
}
</style>
