<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
      label-position="left"
    >
      <el-form-item label="任务单编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入任务单编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="下达日期" prop="orderDate">
        <el-date-picker
          v-model="queryParams.orderDate"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="交货日期" prop="deliveryDate">
        <el-date-picker
          v-model="queryParams.deliveryDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleQuery"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <!-- 状态Tabs -->
    <el-tabs v-model="activeStatusTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="" />
      <el-tab-pane label="已下达" name="2" />
      <el-tab-pane label="部分排产" name="7" />
      <el-tab-pane label="待生产" name="8" />
      <el-tab-pane label="生产中" name="9" />
      <el-tab-pane label="已完成" 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="任务单编码" align="center" prop="code" width="200px" sortable />
      <el-table-column label="下达日期" align="center" prop="orderDate" :formatter="dateFormatter2" sortable />
      <el-table-column
        label="交货日期"
        align="center"
        prop="deliveryDate"
        :formatter="deliveryDateFormatter"
        sortable
      />
      <el-table-column label="状态" 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="是否排产" 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="生产进度" 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="备注" align="center" prop="remark" />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 详情Tabs -->
  <ContentWrap v-if="currentRow && currentRow.id">
    <el-tabs v-model="activeTabName">
      <!-- 基础信息 -->
      <el-tab-pane label="基础信息" name="basicInfo">
        <ProductionReportBasicInfo :task-id="currentRow.id" :task-delivery-date="currentRow.deliveryDate" />
      </el-tab-pane>
      <!-- 关联计划 -->
      <el-tab-pane label="关联计划" name="relatedPlan">
        <ProductionReportRelatedPlan :task-id="currentRow.id" />
      </el-tab-pane>
      <!-- 质检信息 -->
      <el-tab-pane label="质检信息" name="qualityInfo">
        <ProductionReportQualityInfo :task-id="currentRow.id" />
      </el-tab-pane>
      <!-- 报工信息 -->
      <el-tab-pane label="报工信息" name="baogongInfo">
        <ProductionReportBaogongInfo :task-id="currentRow.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { TaskApi, TaskVO } from '@/api/mes/task'
import ProductionReportBasicInfo from './components/ProductionReportBasicInfo.vue'
import ProductionReportRelatedPlan from './components/ProductionReportRelatedPlan.vue'
import ProductionReportQualityInfo from './components/ProductionReportQualityInfo.vue'
import ProductionReportBaogongInfo from './components/ProductionReportBaogongInfo.vue'

/** 生产报表 列表 */
defineOptions({ name: 'ProductionReport' })

const message = useMessage() // 消息弹窗

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,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const activeTabName = ref('basicInfo') // 当前详情tab
const activeStatusTab = ref('') // 当前状态tab

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 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 currentRow = ref<TaskVO>({} as TaskVO) // 选中行
const handleCurrentChange = (row: TaskVO | null) => {
  if (row) {
    currentRow.value = row
    activeTabName.value = 'basicInfo'
  }
}

/** tab 切换 */
const handleTabClick = (tab: any) => {
  queryParams.status = tab.paneName === '' ? undefined : tab.paneName
  currentRow.value = {} as TaskVO
  queryParams.pageNo = 1
  getList()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</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>
