<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
      label-position="left"
    >
      <el-form-item :label="t('ProductionReport.Index.searchCodeLabel')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('ProductionReport.Index.searchCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionReport.Index.searchOrderDateLabel')" prop="orderDate">
        <el-date-picker
          v-model="queryParams.orderDate"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('ProductionReport.Index.startDatePlaceholder')"
          :end-placeholder="t('ProductionReport.Index.endDatePlaceholder')"
          :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('ProductionReport.Index.searchDeliveryDateLabel')" prop="deliveryDate">
        <el-date-picker
          v-model="queryParams.deliveryDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleQuery"
          type="daterange"
          :start-placeholder="t('ProductionReport.Index.startDatePlaceholder')"
          :end-placeholder="t('ProductionReport.Index.endDatePlaceholder')"
          :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('ProductionReport.Index.searchRemarkLabel')" prop="remark">
        <el-input
          v-model="queryParams.remark"
          :placeholder="t('ProductionReport.Index.searchRemarkPlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionReport.Index.searchCreateTimeLabel')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('ProductionReport.Index.startDatePlaceholder')"
          :end-placeholder="t('ProductionReport.Index.endDatePlaceholder')"
          :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" /> {{ t('ProductionReport.Index.buttonSearch') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('ProductionReport.Index.buttonReset') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('ProductionReport.Index.buttonExport') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-tabs v-model="activeStatusTab" @tab-click="handleTabClick">
      <el-tab-pane :label="t('ProductionReport.Index.tabAll')" name="" />
      <el-tab-pane :label="t('ProductionReport.Index.tabIssued')" name="2" />
      <el-tab-pane :label="t('ProductionReport.Index.tabPartialScheduled')" name="7" />
      <el-tab-pane :label="t('ProductionReport.Index.tabPendingProduction')" name="8" />
      <el-tab-pane :label="t('ProductionReport.Index.tabInProduction')" name="9" />
      <el-tab-pane :label="t('ProductionReport.Index.tabCompleted')" 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('ProductionReport.Index.tableCode')" align="center" prop="code" width="200px" sortable />
      <el-table-column :label="t('ProductionReport.Index.tableOrderDate')" align="center" prop="orderDate" :formatter="dateFormatter2" sortable />
      <el-table-column
        :label="t('ProductionReport.Index.tableDeliveryDate')"
        align="center"
        prop="deliveryDate"
        :formatter="deliveryDateFormatter"
        sortable
      />
      <el-table-column :label="t('ProductionReport.Index.tableStatus')" 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('ProductionReport.Index.tableIsScheduled')" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isScheduled ? 'success' : 'info'">{{ scope.row.isScheduled ? t('ProductionReport.Index.yes') : t('ProductionReport.Index.no') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionReport.Index.tableProductionProgress')" 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('ProductionReport.Index.tableRemark')" align="center" prop="remark" />
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <ContentWrap v-if="currentRow && currentRow.id">
    <el-tabs v-model="activeTabName">
      <el-tab-pane :label="t('ProductionReport.Index.detailTabBasicInfo')" name="basicInfo">
        <ProductionReportBasicInfo :task-id="currentRow.id" :task-delivery-date="currentRow.deliveryDate" />
      </el-tab-pane>
      <el-tab-pane :label="t('ProductionReport.Index.detailTabRelatedPlan')" name="relatedPlan">
        <ProductionReportRelatedPlan :task-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane :label="t('ProductionReport.Index.detailTabQualityInfo')" name="qualityInfo">
        <ProductionReportQualityInfo :task-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane :label="t('ProductionReport.Index.detailTabBaogongInfo')" 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'
import { useI18n } from '@/hooks/web/useI18n'

defineOptions({ name: 'ProductionReport' })

const { t } = useI18n()
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')
const activeStatusTab = 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 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, t('ProductionReport.Index.exportFilename') + '.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'
  }
}

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>
