<script setup lang="ts">
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { DICT_TYPE, realValue } from '@/utils/dict'
import dayjs from 'dayjs'
import { TableColumnCtx } from 'element-plus'

const { t } = useI18n()

interface ListItem {
  createTime: string
  deptName: string
  taskName: string
  constructionStatus: string
  relocationDays: number
  designInjection: number
  dailyGasInjection: number
  dailyWaterInjection: number
  dailyInjectGasTime: number
  dailyInjectWaterTime: number
  dailyPowerUsage: number
  dailyOilUsage: number
  gasElectricityRatio: number
  nonProductionRate: number
  accidentTime: number
  repairTime: number
  selfStopTime: number
  complexityTime: number
  relocationTime: number
  rectificationTime: number
  waitingStopTime: number
  winterBreakTime: number
  partyaDesign: number
  partyaPrepare: number
  partyaResource: number
  otherNptTime: number
  otherNptReason: string
  productionStatus: string
  contractName: string
  wellTotalGasInjection: number
  wellTotalWaterInjection: number
  wellTotalPower: number
  wellTotalFuel: number
  yearTotalGasInjection: number
  yearTotalWaterInjection: number
  yearTotalPower: number
  yearTotalFuel: number
  capacity: number
  techniqueNames: string
  transitTimeRate: string
}

const props = defineProps({
  list: {
    type: Array as PropType<ListItem[]>,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  total: {
    type: Number,
    default: 0
  },
  pageNo: {
    type: Number,
    default: 0
  },
  pageSize: {
    type: Number,
    default: 0
  },
  showAction: {
    type: Boolean,
    default: true
  },
  isIndex: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:pageNo', 'update:pageSize', 'sizeChange', 'currentChange'])

const { list, loading, total, pageNo, pageSize, showAction, isIndex } = toRefs(props)

const { ZmTable, ZmTableColumn } = useTableComponents<ListItem>()

const GAS_ELECTRICITY_RATIO_WARNING_THRESHOLD = 15

function unitformatter(
  _row: ListItem,
  _column: TableColumnCtx<ListItem>,
  cellValue: any,
  _index: number
) {
  if (cellValue === null || cellValue === undefined || cellValue == '') return ''
  const value = parseFloat(cellValue)
  return (value / 10000).toFixed(4)
}

const isGasElectricityRatioWarning = (value: unknown) => {
  const ratio = Number(value)

  return Number.isFinite(ratio) && ratio > GAS_ELECTRICITY_RATIO_WARNING_THRESHOLD
}

const cellStyle = ({ row, column }: { row: any; column: any }) => {
  if (column.property === 'transitTimeRate') {
    const ratio = Number(row?.transitTimeRate.replace('%', ''))
    if (ratio > 100.0) {
      return {
        color: 'red',
        fontWeight: 'bold',
        backgroundColor: 'var(--el-color-danger-light-9)'
      }
    }
  }

  if (
    column.property === 'gasElectricityRatio' &&
    isGasElectricityRatioWarning(row?.gasElectricityRatio)
  ) {
    return {
      color: 'var(--el-color-warning)',
      fontWeight: 'bold'
    }
  }

  return {}
}

function handleSizeChange(val: number) {
  emits('sizeChange', val)
}

function handleCurrentChange(val: number) {
  emits('currentChange', val)
}
</script>

<template>
  <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4">
    <div class="flex-1 relative">
      <el-auto-resizer class="absolute">
        <template #default="{ width, height }">
          <zm-table
            :data="list"
            :loading="loading"
            :width="width"
            :max-height="height"
            :height="height"
            show-border
            :cell-style="cellStyle">
            <zm-table-column
              v-if="isIndex"
              type="index"
              :label="t('monitor.serial')"
              :width="60"
              fixed="left" />
            <zm-table-column
              label="日期"
              prop="createTime"
              fixed="left"
              cover-formatter
              :real-value="(row: ListItem) => dayjs(row.createTime).format('YYYY-MM-DD')" />
            <zm-table-column label="施工队伍" prop="deptName" fixed="left" />
            <zm-table-column label="任务" prop="taskName" fixed="left" />
            <zm-table-column
              prop="constructionStatus"
              fixed="left"
              :label="t('project.status')"
              :real-value="
                (row: ListItem) =>
                  realValue(DICT_TYPE.PMS_PROJECT_TASK_SCHEDULE, row.constructionStatus ?? '')
              ">
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.PMS_PROJECT_TASK_SCHEDULE"
                  :value="scope.row.constructionStatus ?? ''" />
              </template>
            </zm-table-column>
            <zm-table-column prop="auditStatus" label="审批状态" v-if="!isIndex">
              <template #default="scope">
                <el-tag v-if="scope.row.auditStatus === 0" type="info">
                  {{ '待提交' }}
                </el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 10">
                  {{ '待审批' }}
                </el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 20" type="success">
                  {{ '审批通过' }}
                </el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 30" type="danger">
                  {{ '审批拒绝' }}
                </el-tag>
              </template>
            </zm-table-column>
            <zm-table-column label="施工区域" prop="location" />
            <zm-table-column label="施工工艺" prop="techniqueNames" />
            <zm-table-column label="设备号" prop="deviceNo" />
            <zm-table-column label="设计注气量(万方)" prop="designInjection" />
            <zm-table-column label="运行时效" prop="transitTimeRate" />
            <zm-table-column label="当日">
              <zm-table-column
                label="注气量(万方)"
                prop="dailyGasInjection"
                cover-formatter
                :real-value="unitformatter" />
              <zm-table-column label="注水量(方)" prop="dailyWaterInjection" />
              <zm-table-column label="注气时间(H)" prop="dailyInjectGasTime" />
              <zm-table-column label="注水时间(H)" prop="dailyInjectWaterTime" />
              <zm-table-column label="用电量(kWh)" prop="dailyPowerUsage" />
              <zm-table-column label="油耗(L)" prop="dailyOilUsage" />
              <zm-table-column label="气电比" prop="gasElectricityRatio" />
            </zm-table-column>
            <zm-table-column
              prop="nonProductionRate"
              label="非生产时效"
              cover-formatter
              :real-value="(row) => (Number(row.nonProductionRate ?? 0) * 100).toFixed(2) + '%'" />
            <zm-table-column label="非生产时间">
              <zm-table-column prop="accidentTime" label="工程质量" />
              <zm-table-column prop="repairTime" label="设备故障" />
              <zm-table-column prop="selfStopTime" label="设备保养" />
              <zm-table-column prop="complexityTime" label="技术受限" />
              <zm-table-column prop="relocationTime" label="生产配合" />
              <zm-table-column prop="rectificationTime" label="生产组织" />
              <zm-table-column prop="waitingStopTime" label="不可抗力" />
              <zm-table-column prop="winterBreakTime" label="待命" />
              <zm-table-column prop="partyaDesign" label="甲方设计" />
              <zm-table-column prop="partyaPrepare" label="甲方准备" />
              <zm-table-column prop="partyaResource" label="甲方资源" />
              <zm-table-column prop="otherNptTime" label="其它非生产时间" />
            </zm-table-column>
            <zm-table-column prop="otherNptReason" label="其他非生产时间原因" />
            <zm-table-column prop="productionStatus" label="生产动态" />
            <zm-table-column prop="contractName" label="项目" />
            <zm-table-column label="搬迁安装天数" prop="relocationDays" />
            <zm-table-column label="井累计" v-if="isIndex">
              <zm-table-column prop="wellTotalGasInjection" label="注气量(万方)" />
              <zm-table-column prop="wellTotalWaterInjection" label="注水量(方)" />
              <zm-table-column prop="wellTotalPower" label="用电量(MWh)" />
              <zm-table-column prop="wellTotalFuel" label="油耗(L)" />
            </zm-table-column>
            <zm-table-column label="年累计" v-if="isIndex">
              <zm-table-column prop="yearTotalGasInjection" label="注气量(万方)" />
              <zm-table-column prop="yearTotalWaterInjection" label="注水量(方)" />
              <zm-table-column prop="yearTotalPower" label="用电量(MWh)" />
              <zm-table-column prop="yearTotalFuel" label="油耗(L)" />
            </zm-table-column>
            <zm-table-column label="累计" v-if="!isIndex">
              <zm-table-column prop="totalGasInjection" label="注气量(万方)" />
              <zm-table-column prop="totalWaterInjection" label="注水量(方)" />
              <zm-table-column prop="cumulativeCompletion" label="完工井次" />
            </zm-table-column>
            <zm-table-column
              prop="capacity"
              label="产能(万方)"
              cover-formatter
              :action="!showAction"
              :real-value="unitformatter" />

            <zm-table-column label="操作" :width="120" fixed="right" action v-if="showAction">
              <template #default="scope">
                <slot name="action" :row="scope.row"></slot>
              </template>
            </zm-table-column>
          </zm-table>
        </template>
      </el-auto-resizer>
    </div>
    <div class="h-8 mt-2 flex items-center justify-end">
      <el-pagination
        size="default"
        v-show="total > 0"
        :current-page="pageNo"
        :page-size="pageSize"
        :background="true"
        :page-sizes="[10, 20, 30, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<style scoped></style>
