<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="auto"
      label-position="left">
      <el-form-item :label="t('ProductionPlan.TaskSummary.searchCodeLabel')" prop="code">
        <el-input
v-model="queryParams.code" :placeholder="t('ProductionPlan.TaskSummary.searchCodePlaceholder')"
          clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.TaskSummary.searchOrderLabel')" prop="orderDate">
        <el-date-picker
v-model="queryParams.orderDate" @change="handleQuery" value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange" :start-placeholder="t('ProductionPlan.TaskSummary.searchOrderStartPlaceholder')"
          :end-placeholder="t('ProductionPlan.TaskSummary.searchOrderEndPlaceholder')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.TaskSummary.searchDeliveryLabel')" prop="deliveryDate">
        <el-date-picker
v-model="queryParams.deliveryDate" value-format="YYYY-MM-DD HH:mm:ss" @change="handleQuery"
          type="daterange" :start-placeholder="t('ProductionPlan.TaskSummary.searchDeliveryStartPlaceholder')"
          :end-placeholder="t('ProductionPlan.TaskSummary.searchDeliveryEndPlaceholder')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.TaskSummary.searchRemarkLabel')" prop="remark" v-show="showAllFilters">
        <el-input
v-model="queryParams.remark" :placeholder="t('ProductionPlan.TaskSummary.searchRemarkPlaceholder')"
          clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.TaskSummary.searchCreateTimeLabel')" prop="createTime" v-show="showAllFilters">
        <el-date-picker
v-model="queryParams.createTime" @change="handleQuery" value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange" :start-placeholder="t('ProductionPlan.TaskSummary.searchCreateTimeStartPlaceholder')"
          :end-placeholder="t('ProductionPlan.TaskSummary.searchCreateTimeEndPlaceholder')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
    
      <el-form-item v-if="filterCount > 3">
        <el-button type="text" class="text-primary" @click="toggleFilters">
          <Icon :icon="showAllFilters ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-5px" />
          {{ showAllFilters ? t('FactoryModeling.FactoryStructure.collapseText') :
            t('FactoryModeling.FactoryStructure.expandText') }}
        </el-button>
      </el-form-item>
    
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('ProductionPlan.TaskSummary.buttonSearchText') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('ProductionPlan.TaskSummary.buttonResetText') }}
        </el-button>

        <el-button type="success" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['mes:task:export']">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('ProductionPlan.TaskSummary.buttonExportText') }}
        </el-button>
        <el-button type="primary" @click="openScheduleDialog">
          <Icon icon="ep:plus" class="mr-5px" /> 排产
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabAllLabel')" name="" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabIssuedLabel')" name="2" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabPartialSchedulingLabel')" name="7" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabPendingProductionLabel')" name="8" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabInProductionLabel')" name="9" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabCompletedLabel')" name="10" />
    </el-tabs>
    <el-table
v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" highlight-current-row
      @current-change="handleCurrentChange">
      <el-table-column
:label="t('ProductionPlan.TaskSummary.tableTaskCodeColumn')" align="center" prop="code"
        width="200px" sortable />
      <el-table-column
:label="t('ProductionPlan.TaskSummary.tableOrderDateColumn')" align="center" prop="orderDate"
        :formatter="dateFormatter2" sortable />
      <el-table-column
:label="t('ProductionPlan.TaskSummary.tableDeliveryDateColumn')" align="center"
        prop="deliveryDate" :formatter="deliveryDateFormatter" sortable />
      <el-table-column :label="t('ProductionPlan.TaskSummary.tableStatusColumn')" align="center" prop="status" sortable>
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_TASK_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.TaskSummary.tableScheduleCompletedColumn')" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isScheduled ? 'success' : 'info'">{{ scope.row.isScheduled ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.TaskSummary.tableProductionProgressColumn')" align="center" min-width="60px">
        <template #default="scope">
          <div class="production-progress-cell">
              <el-progress
                type="circle"
                :percentage="getProductionProgressPercent(scope.row)"
                :width="40"
                :stroke-width="4"
                :show-text="false"
                :color="getProductionProgressPercent(scope.row) === 100 ? '#67c23a' : undefined"
              />
              <span class="production-progress-text">{{ getProductionProgressPercent(scope.row) }}%</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.TaskSummary.tableRemarkColumn')" align="center" prop="remark" />

      <el-table-column :label="t('ProductionPlan.TaskSummary.tableOperateColumn')" align="center" min-width="200px">
        <template #default="scope">
          <el-button
link type="info" @click="openItemNeed(scope.row.code, scope.row.id)"
            v-hasPermi="['mes:task:query']">
            {{ t('ProductionPlan.TaskSummary.actionMaterialLabel') }}
          </el-button>
          <el-button link type="primary" @click="openPlan(scope.row.id)" v-hasPermi="['mes:plan:query']">
            {{ t('ProductionPlan.TaskSummary.actionViewPlanLabel') }}
          </el-button>
          <!-- <el-button link v-if="scope.row.status<5" type="success" @click="openTaskPlanForm(scope.row.id, scope.row.code)" v-hasPermi="['mes:task:plan']">
            排产
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs model-value="taskDetail">
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.detailTabSummaryLabel')" name="taskDetail">
        <TaskDetailList :task-id="currentRow.id" :task-delivery-date="currentRow.deliveryDate" @success="getList" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
  <!-- 物料列表 -->
  <ItemNeedIndex ref="formRef" @success="getList" />
  <!-- 排程弹窗 -->
  <TaskPlanForm ref="taskPlanFormRef" @success="getList" />
  <TaskScheduleDialog ref="taskScheduleDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { TaskApi, TaskVO } from '@/api/mes/task'
import TaskDetailList from './components/TaskDetailList.vue'
import ItemNeedIndex from "@/views/mes/bom/ItemNeedIndex.vue";
import TaskPlanForm from "@/views/mes/tasksummary/components/TaskPlan.vue";
import TaskScheduleDialog from '@/views/mes/tasksummary/components/TaskScheduleDialog.vue'

/** 生产任务单 列表 */
defineOptions({ name: 'TaskSummary' })

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

const loading = ref(true) // 列表的加载中
const list = ref<TaskVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  orderDate: [],
  deliveryDate: [],
  status: undefined,
  processInstanceId: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const showAllFilters = ref(false) // 是否显示所有筛选框
const filterCount = 4 // 筛选框数量

/** 切换筛选框展开/折叠 */
const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
}

const { push } = useRouter()
const taskScheduleDialogRef = ref()
const deliveryDateFormatter = (_row: any, _column: any, value: any) => {
  if (value) return dateFormatter2(_row, _column, value)
  return dateFormatter2(_row, _column, _row?.finishDate)
}
const getProductionProgressPercent = (row: any) => {
  const storedPlanNumber = Number(row?.storedPlanNumber ?? 0)
  const totalNumber = Number(row?.totalNumber ?? row?.number ?? 0)
  if (!Number.isFinite(storedPlanNumber) || !Number.isFinite(totalNumber) || totalNumber <= 0) return 0
  const rawPercent = (storedPlanNumber / totalNumber) * 100
  return Math.max(0, Math.min(100, Number(rawPercent.toFixed(2))))
}
const getProductionProgressText = (row: any) => {
  const storedPlanNumber = Number(row?.storedPlanNumber ?? 0)
  const totalNumber = Number(row?.totalNumber ?? row?.number ?? 0)
  if (!Number.isFinite(storedPlanNumber) || !Number.isFinite(totalNumber) || totalNumber <= 0) return '0/0'
  return `${storedPlanNumber}/${totalNumber}`
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getPlanTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskApi.exportTask(queryParams)
    download.excel(data, '生产任务单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const openScheduleDialog = () => {
  taskScheduleDialogRef.value?.open()
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
}

/** 初始化 **/
onMounted(() => {
  getList()
})
/** 跳转生产计划页面**/
const openPlan = (taskId: number) => {
  // 跳转页面并设置请求参数，使用 `query` 属性
  //const productId = null;
  //push({ name: 'TaskToPlan', params: { taskId, productId} })
  push('/mes/plan?taskId=' + taskId)
}
/** 物料需求 */
const formRef = ref()
const openItemNeed = (taskCode: string, taskId: number) => {
  formRef.value.open("task", "任务单-" + taskCode, taskId)
}

/** 添加/修改操作 */
const taskPlanFormRef = ref()
const openTaskPlanForm = (taskId: number, taskCode: string) => {
  taskPlanFormRef.value.open(taskCode, taskId)
}
/** tab 切换 */
let activeName = ''
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.status = tab.paneName
  currentRow.value = {}
  handleQuery()
}
</script>

<style scoped>
.production-progress-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.production-progress-cell :deep(.el-progress-circle) {
  display: flex;
  align-items: center;
  justify-content: center;
}

.production-progress-text {
  font-size: 12px;
  white-space: nowrap;
}
</style>
