<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" >

            <el-form-item label="统计日期" prop="statDate">
              <el-date-picker clearable
                v-model="queryParams.statDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择统计日期"
              />
            </el-form-item>

            <el-form-item label="车间名称" prop="workshopName">
              <el-input v-model="queryParams.workshopName" placeholder="请输入车间名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="班组名称" prop="classTeamName">
              <el-input v-model="queryParams.classTeamName" placeholder="请输入班组名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="班次名称" prop="shiftName">
              <el-input v-model="queryParams.shiftName" placeholder="请输入班次名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备名称" prop="machineName">
              <el-input v-model="queryParams.machineName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 汇总指标卡片 -->
    <el-row :gutter="12" class="mb8">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="kpi-title">总产量（件）</div>
          <div class="kpi-value">{{ Number(sumOutputQty ?? 0).toFixed(0) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="kpi-title">合计时长（小时）</div>
          <div class="kpi-value">{{ Number(sumTotalHours ?? 0).toFixed(2) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="kpi-title">平均开机率</div>
          <div class="kpi-value">{{ ((avgUptimeRate ?? 0) * 100).toFixed(1) }}%</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="kpi-title">平均综合效率</div>
          <div class="kpi-value">{{ ((avgOverallEfficiency ?? 0) * 100).toFixed(1) }}%</div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dms:dmsReportDeviceEfficiency:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['dms:dmsReportDeviceEfficiency:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['dms:dmsReportDeviceEfficiency:remove']">删除</el-button>
          </el-col>-->
<!--          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dms:dmsReportDeviceEfficiency:export']">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="dmsReportDeviceEfficiencyList" border stripe size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="统计日期" align="center" prop="statDate" width="180" v-if="columns[0].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.statDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="车间" prop="workshopName" show-overflow-tooltip v-if="columns[1].visible"/>
        <el-table-column label="班组" prop="classTeamName" show-overflow-tooltip v-if="columns[2].visible"/>
        <el-table-column label="班次" prop="shiftName" show-overflow-tooltip v-if="columns[3].visible"/>
        <el-table-column label="设备" prop="machineName" show-overflow-tooltip v-if="columns[4].visible"/>

        <el-table-column label="产量" align="right" prop="outputQty" width="110" v-if="columns[5].visible"/>
        <el-table-column label="标准机时" align="right" prop="processStdMachineHours" width="120" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.processStdMachineHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调试" align="right" prop="debugHours" width="110" v-if="columns[7].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.debugHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="运行" align="right" prop="runHours" width="110" v-if="columns[8].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.runHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="待机" align="right" prop="standbyHours" width="110" v-if="columns[9].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.standbyHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="故障" align="right" prop="faultHours" width="110" v-if="columns[10].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.faultHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关机" align="right" prop="shutdownHours" width="110" v-if="columns[11].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.shutdownHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产出机时" align="right" prop="outputMachineHours" width="120" v-if="columns[12].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.outputMachineHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合计时长" align="right" prop="totalHours" width="120" v-if="columns[13].visible">
          <template #default="scope">
            <span>{{ Number(scope.row.totalHours ?? 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开机率" align="center" prop="uptimeRate" width="120" v-if="columns[14].visible">
          <template #default="scope">
            <el-tag :type="(scope.row.uptimeRate ?? 0) >= 0.8 ? 'success' : (scope.row.uptimeRate ?? 0) >= 0.6 ? 'warning' : 'danger'">
              {{ ((scope.row.uptimeRate ?? 0) * 100).toFixed(1) }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="综合效率" align="center" prop="overallEfficiency" width="120" v-if="columns[15].visible">
          <template #default="scope">
            <el-tag :type="(scope.row.overallEfficiency ?? 0) >= 0.8 ? 'success' : (scope.row.overallEfficiency ?? 0) >= 0.6 ? 'warning' : 'danger'">
              {{ ((scope.row.overallEfficiency ?? 0) * 100).toFixed(1) }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="运行效率" align="center" prop="runtimeEfficiency" width="120" v-if="columns[16].visible">
          <template #default="scope">
            <el-tag :type="(scope.row.runtimeEfficiency ?? 0) >= 0.8 ? 'success' : (scope.row.runtimeEfficiency ?? 0) >= 0.6 ? 'warning' : 'danger'">
              {{ ((scope.row.runtimeEfficiency ?? 0) * 100).toFixed(1) }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[17].visible"/>
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dms:dmsReportDeviceEfficiency:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dms:dmsReportDeviceEfficiency:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改设备效率报对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dmsReportDeviceEfficiencyFormRef" :model="form" :rules="rules" label-width="120px">

        <el-form-item label="统计日期" prop="statDate">
          <el-date-picker clearable
            v-model="form.statDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择统计日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="车间名称" prop="workshopName">
          <el-input v-model="form.workshopName" placeholder="请输入车间名称" />
        </el-form-item>
        <el-form-item label="班组名称" prop="classTeamName">
          <el-input v-model="form.classTeamName" placeholder="请输入班组名称" />
        </el-form-item>
        <el-form-item label="班次名称" prop="shiftName">
          <el-input v-model="form.shiftName" placeholder="请输入班次名称" />
        </el-form-item>
        <el-form-item label="设备名称" prop="machineName">
          <el-input v-model="form.machineName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="产量" prop="outputQty">
          <el-input v-model="form.outputQty" placeholder="请输入产量" />
        </el-form-item>
        <el-form-item label="工序标准机时" prop="processStdMachineHours">
          <el-input v-model="form.processStdMachineHours" placeholder="请输入工序标准机时" />
        </el-form-item>
        <el-form-item label="调试时间" prop="debugHours">
          <el-input v-model="form.debugHours" placeholder="请输入调试时间" />
        </el-form-item>
        <el-form-item label="运行时长" prop="runHours">
          <el-input v-model="form.runHours" placeholder="请输入运行时长" />
        </el-form-item>
        <el-form-item label="待机时长" prop="standbyHours">
          <el-input v-model="form.standbyHours" placeholder="请输入待机时长" />
        </el-form-item>
        <el-form-item label="故障时长" prop="faultHours">
          <el-input v-model="form.faultHours" placeholder="请输入故障时长" />
        </el-form-item>
        <el-form-item label="关机时长" prop="shutdownHours">
          <el-input v-model="form.shutdownHours" placeholder="请输入关机时长" />
        </el-form-item>
        <el-form-item label="产出机时" prop="outputMachineHours">
          <el-input v-model="form.outputMachineHours" placeholder="请输入产出机时" />
        </el-form-item>
        <el-form-item label="合计时长" prop="totalHours">
          <el-input v-model="form.totalHours" placeholder="请输入合计时长" />
        </el-form-item>
        <el-form-item label="开机率 = (运行时长 + 调试时间) / 合计时长" prop="uptimeRate">
          <el-input v-model="form.uptimeRate" placeholder="请输入开机率 = (运行时长 + 调试时间) / 合计时长" />
        </el-form-item>
        <el-form-item label="综合效率 = 产出机时 / (运行+待机+故障+关机+调试)" prop="overallEfficiency">
          <el-input v-model="form.overallEfficiency" placeholder="请输入综合效率 = 产出机时 / (运行+待机+故障+关机+调试)" />
        </el-form-item>
        <el-form-item label="运行效率 = 产出机时 / 运行时长" prop="runtimeEfficiency">
          <el-input v-model="form.runtimeEfficiency" placeholder="请输入运行效率 = 产出机时 / 运行时长" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DmsReportDeviceEfficiency" lang="ts">
import { listDmsReportDeviceEfficiency, getDmsReportDeviceEfficiency, delDmsReportDeviceEfficiency, addDmsReportDeviceEfficiency, updateDmsReportDeviceEfficiency } from '@/api/dms/dmsReportDeviceEfficiency';
import { DmsReportDeviceEfficiencyVO, DmsReportDeviceEfficiencyQuery, DmsReportDeviceEfficiencyForm } from '@/api/dms/dmsReportDeviceEfficiency/types';
import { computed } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dmsReportDeviceEfficiencyList = ref<DmsReportDeviceEfficiencyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const dmsReportDeviceEfficiencyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
        { key: 0, label: `统计日期`, visible: true },
        { key: 1, label: `车间`, visible: true },
        { key: 2, label: `班组`, visible: true },
        { key: 3, label: `班次`, visible: true },
        { key: 4, label: `设备`, visible: true },
        { key: 5, label: `产量`, visible: true },
        { key: 6, label: `标准机时`, visible: true },
        { key: 7, label: `调试`, visible: true },
        { key: 8, label: `运行`, visible: true },
        { key: 9, label: `待机`, visible: true },
        { key: 10, label: `故障`, visible: true },
        { key: 11, label: `关机`, visible: true },
        { key: 12, label: `产出机时`, visible: true },
        { key: 13, label: `合计时长`, visible: true },
        { key: 14, label: `开机率`, visible: true },
        { key: 15, label: `综合效率`, visible: true },
        { key: 16, label: `运行效率`, visible: true },
        { key: 17, label: `备注`, visible: true },
]);

const initFormData: DmsReportDeviceEfficiencyForm = {
  reportId: undefined,
  statDate: undefined,
  workshopId: undefined,
  classTeamId: undefined,
  shiftId: undefined,
  machineId: undefined,
  workshopName: undefined,
  classTeamName: undefined,
  shiftName: undefined,
  machineName: undefined,
  outputQty: undefined,
  processStdMachineHours: undefined,
  debugHours: undefined,
  runHours: undefined,
  standbyHours: undefined,
  faultHours: undefined,
  shutdownHours: undefined,
  outputMachineHours: undefined,
  totalHours: undefined,
  uptimeRate: undefined,
  overallEfficiency: undefined,
  runtimeEfficiency: undefined,
  remark: undefined,
}
const data = reactive<PageData<DmsReportDeviceEfficiencyForm, DmsReportDeviceEfficiencyQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reportId: undefined,
    statDate: undefined,
    workshopId: undefined,
    classTeamId: undefined,
    shiftId: undefined,
    machineId: undefined,
    workshopName: undefined,
    classTeamName: undefined,
    shiftName: undefined,
    machineName: undefined,
    outputQty: undefined,
    processStdMachineHours: undefined,
    debugHours: undefined,
    runHours: undefined,
    standbyHours: undefined,
    faultHours: undefined,
    shutdownHours: undefined,
    outputMachineHours: undefined,
    totalHours: undefined,
    uptimeRate: undefined,
    overallEfficiency: undefined,
    runtimeEfficiency: undefined,
    params: {
    }
  },
  rules: {

    statDate: [
      { required: true, message: "统计日期不能为空", trigger: "blur" }
    ],

    workshopName: [
      { required: true, message: "车间名称不能为空", trigger: "blur" }
    ],
    classTeamName: [
      { required: true, message: "班组名称不能为空", trigger: "blur" }
    ],
    shiftName: [
      { required: true, message: "班次名称不能为空", trigger: "blur" }
    ],
    machineName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    outputQty: [
      { required: true, message: "产量不能为空", trigger: "blur" }
    ],
    processStdMachineHours: [
      { required: true, message: "工序标准机时不能为空", trigger: "blur" }
    ],
    debugHours: [
      { required: true, message: "调试时间不能为空", trigger: "blur" }
    ],
    runHours: [
      { required: true, message: "运行时长不能为空", trigger: "blur" }
    ],
    standbyHours: [
      { required: true, message: "待机时长不能为空", trigger: "blur" }
    ],
    faultHours: [
      { required: true, message: "故障时长不能为空", trigger: "blur" }
    ],
    shutdownHours: [
      { required: true, message: "关机时长不能为空", trigger: "blur" }
    ],
    outputMachineHours: [
      { required: true, message: "产出机时不能为空", trigger: "blur" }
    ],
    totalHours: [
      { required: true, message: "合计时长不能为空", trigger: "blur" }
    ],
    uptimeRate: [
      { required: true, message: "开机率 = (运行时长 + 调试时间) / 合计时长不能为空", trigger: "blur" }
    ],
    overallEfficiency: [
      { required: true, message: "综合效率 = 产出机时 / (运行+待机+故障+关机+调试)不能为空", trigger: "blur" }
    ],
    runtimeEfficiency: [
      { required: true, message: "运行效率 = 产出机时 / 运行时长不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 汇总指标（顶部KPI）
const sumOutputQty = computed(() => {
  try {
    return dmsReportDeviceEfficiencyList.value.reduce((sum, r) => sum + Number(r?.outputQty ?? 0), 0);
  } catch {
    return 0;
  }
});

const sumTotalHours = computed(() => {
  try {
    return dmsReportDeviceEfficiencyList.value.reduce((sum, r) => sum + Number(r?.totalHours ?? 0), 0);
  } catch {
    return 0;
  }
});

const avgUptimeRate = computed(() => {
  const rows = dmsReportDeviceEfficiencyList.value;
  if (!rows.length) return 0;
  let total = 0;
  let count = 0;
  for (const r of rows) {
    const v = Number(r?.uptimeRate ?? 0);
    if (!Number.isNaN(v)) {
      total += v;
      count += 1;
    }
  }
  return count ? total / count : 0;
});

const avgOverallEfficiency = computed(() => {
  const rows = dmsReportDeviceEfficiencyList.value;
  if (!rows.length) return 0;
  let total = 0;
  let count = 0;
  for (const r of rows) {
    const v = Number(r?.overallEfficiency ?? 0);
    if (!Number.isNaN(v)) {
      total += v;
      count += 1;
    }
  }
  return count ? total / count : 0;
});

/** 查询设备效率报列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDmsReportDeviceEfficiency(queryParams.value);
  dmsReportDeviceEfficiencyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  dmsReportDeviceEfficiencyFormRef.value?.resetFields();
}

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: DmsReportDeviceEfficiencyVO[]) => {
  ids.value = selection.map(item => item.reportId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加设备效率报";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DmsReportDeviceEfficiencyVO) => {
  reset();
  const _reportId = row?.reportId || ids.value[0]
  const res = await getDmsReportDeviceEfficiency(_reportId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备效率报";
}

/** 提交按钮 */
const submitForm = () => {
  dmsReportDeviceEfficiencyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.reportId) {
        await updateDmsReportDeviceEfficiency(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addDmsReportDeviceEfficiency(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DmsReportDeviceEfficiencyVO) => {
  const _reportIds = row?.reportId || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备效率报编号为"' + _reportIds + '"的数据项？').finally(() => loading.value = false);
  await delDmsReportDeviceEfficiency(_reportIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('dms/dmsReportDeviceEfficiency/export', {
    ...queryParams.value
  }, `dmsReportDeviceEfficiency_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.kpi-title {
  color: var(--el-text-color-secondary);
  font-size: 13px;
}
.kpi-value {
  margin-top: 6px;
  font-size: 22px;
  font-weight: 600;
  color: var(--el-color-primary);
}
</style>
