<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
      v-if="props.showCreateButton"
      type="primary"
      plain
      @click="openForm('create')"
      v-hasPermi="['mes:task:create']"
    >
      <Icon icon="ep:plus" class="mr-5px" /> {{ t('ProductionPlan.Task.detailListCreateButtonText') }}
    </el-button>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column :label="t('ProductionPlan.Task.detailListProductCodeColumn')"  prop="barCode" sortable />
      <el-table-column :label="t('ProductionPlan.Task.detailListProductNameColumn')"  prop="productName" sortable/>
     <el-table-column :label="t('ProductionPlan.Task.detailListUnitColumn')" align="center" prop="unitName"  sortable />
       <el-table-column :label="t('ProductionPlan.Task.detailListNumberColumn')" align="center" prop="number" />
      <el-table-column :label="t('ProductionPlan.Task.detailListPlanNumberColumn')" align="center" prop="planNumber" />
<!--      <el-table-column :label="t('ProductionPlan.Task.detailListPackageSizeColumn')" align="center" prop="packageSize" />-->
      <el-table-column :label="t('ProductionPlan.Task.detailListFinishDateColumn')" align="center" prop="finishDate" :formatter="dateFormatter2" sortable />
      <!-- <el-table-column label="项目名称" align="center" prop="projectName"  sortable /> -->
      <el-table-column :label="t('ProductionPlan.Task.detailListTechRequirementsColumn')" align="center" prop="techRequirements" />

      <el-table-column :label="t('ProductionPlan.Task.detailListOperateColumn')" align="center" width="300px">
        <template #default="scope">
          <el-button
            link
            @click="openFormView('detail', scope.row.id)"
          >
            {{ t('ProductionPlan.Task.detailListViewActionText') }}
          </el-button>
          <el-button
            link
            type="info"
            @click="openItemNeed(scope.row.productName, scope.row.productId, scope.row.number)"
          >
            {{ t('ProductionPlan.Task.detailListMaterialActionText') }}
          </el-button>
          <!-- <el-button
            link
            type="warning"
            @click="addPlanForm(scope.row.taskId,scope.row.id, scope.row.productId, scope.row.number-scope.row.planNumber)"
            v-hasPermi="['mes:plan:create']"
          >
            新增计划
          </el-button> -->
          <!-- <el-button
            v-if="props.taskStatus>1"
            link
            type="success"
            @click="openTaskPlanForm(scope.row.taskId,scope.row.id, scope.row.productId, scope.row.productName, scope.row.number, scope.row.planNumber)"
            v-hasPermi="['mes:plan:create']"
          >
            排产
          </el-button> -->
          <el-button
            v-if="![2,7,8,9,10].includes(props.taskStatus)"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:task:update']"
          >
            {{ t('ProductionPlan.Task.detailListEditActionText') }}
          </el-button>
          <el-button
            v-if="![2,7,8,9,10].includes(props.taskStatus)"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['mes:task:delete']"
          >
            {{ t('ProductionPlan.Task.detailListDeleteActionText') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
    <!-- 表单弹窗：添加/修改 -->
    <TaskDetailForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：添加/修改 -->
   <TaskDetailView ref="formViewRef" @success="getList"/>

  <!-- 物料列表 -->
  <ItemNeedIndex ref="itemNeedFormRef" @success="getList" />
  <!-- 排程弹窗 -->
  <TaskPlanForm ref="taskPlanFormRef" @success="getList" />
  <!-- 新增计划表单弹窗：添加 -->
  <PlanForm ref="planFormRef" @success="getList" />
</template>
<script setup lang="ts">
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import { TaskApi } from '@/api/mes/task'
import TaskDetailForm from './TaskDetailForm.vue'
import TaskDetailView from './TaskDetailView.vue'
import ItemNeedIndex from "@/views/mes/bom/ItemNeedIndex.vue";
import TaskPlanForm from "@/views/mes/task/components/PlanPlan.vue";
import PlanForm from "@/views/mes/plan/PlanForm.vue";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = withDefaults(defineProps<{
  taskId?: number // task ID（主表的关联字段）
  taskStatus?: number
  showCreateButton?: boolean
}>(), {
  showCreateButton: true
})
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  taskId: undefined as unknown
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getTaskDetailPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.taskId,
  (val: number) => {
    if (!val) {
      list.value = []
      total.value = 0
      return
    }
    queryParams.taskId = val
    handleQuery()
  },
  { immediate: true, deep: true }
)

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (!props.taskId) {
    message.error(t('ProductionPlan.Task.selectTaskTip'))
    return
  }
  formRef.value.open(type, id, props.taskId)
}
/** 详情操作 */
const formViewRef = ref()
const openFormView = (type: string, id?: number) => {
  if (!props.taskId) {
    message.error('请选择一个生产任务单')
    return
  }
  formViewRef.value.open(type, id)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TaskApi.deleteTaskDetail(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

//单个计划的物料需求
/** 物料需求 */
const itemNeedFormRef = ref()
const openItemNeed = (productName:string, productId: number, number:number) => {
  number = number>0 ? number : 0;
  itemNeedFormRef.value.open("product",productName, productId, number)
}
/** 添加/修改操作 */
const planFormRef = ref()
const addPlanForm = (taskId: number,taskDetailId: number, productId: number, number?: number) => {
  if (!props.taskId) {
    message.error(t('ProductionPlan.Task.selectTaskTip'))
    return
  }
  planFormRef.value.open("create",null,taskId, productId, number, taskDetailId)
}

/** 单个计划排产 */
const taskPlanFormRef = ref()
const openTaskPlanForm = (taskId:number, taskDetailId: number, productId: number,
                          productName:String, num:number, planNumber:number) => {
  taskPlanFormRef.value.open(taskId,taskDetailId,productId, productName, num, planNumber )
}

</script>
