<template>
  <div class="p-2">
    <!-- 添加润滑计划信息头部展示 -->
    <el-card shadow="hover" class="mb-[10px]">
      <h4 class="mb-4 font-medium text-lg">润滑计划信息</h4>
      <el-form label-width="120px">
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="润滑计划编号">
              <el-input v-model="planLubeCode" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="mb-[10px]">
      <h4 class="mb-4 font-medium text-lg">详细信息</h4>

      <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:dmsPlanLubeDetail:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['dms:dmsPlanLubeDetail:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['dms:dmsPlanLubeDetail:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dms:dmsPlanLubeDetail: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="dmsPlanLubeDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备名称" align="center" prop="machineName">
        </el-table-column>
        <el-table-column label="润滑部位" align="center" prop="lubeStationName">
        </el-table-column>
        <el-table-column label="润滑标准" align="center" prop="lubeStandardCode">
        </el-table-column>
        <el-table-column label="操作描述" align="center" prop="operationDescription" />
        <el-table-column label="激活标识" align="center" prop="activeFlag">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <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:dmsPlanLubeDetail:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dms:dmsPlanLubeDetail: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="dmsPlanLubeDetailFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备名称" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择设备" filterable>
            <el-option
              v-for="item in deviceOptions"
              :key="item.machineId"
              :label="item.machineName"
              :value="item.machineId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="润滑部位" prop="lubeStationId">
          <el-select v-model="form.lubeStationId" placeholder="请选择润滑部位" filterable>
            <el-option
              v-for="item in stationList"
              :key="item.lubeStationId"
              :label="item.lubeStationName"
              :value="item.lubeStationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="润滑标准" prop="lubeStandardId">
          <el-select v-model="form.lubeStandardId" placeholder="请选择润滑标准" filterable>
            <el-option
              v-for="item in standardList"
              :key="item.lubeStandardId"
              :label="item.lubeProtocol"
              :value="item.lubeStandardId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作描述" prop="operationDescription">
          <el-input v-model="form.operationDescription" placeholder="请输入操作描述" />
        </el-form-item>
        <el-form-item label="激活标识" prop="activeFlag">
          <el-radio-group v-model="form.activeFlag">
            <el-radio
              v-for="dict in active_flag"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </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="DmsPlanLubeDetail" lang="ts">
import { listDmsPlanLubeDetail, getDmsPlanLubeDetail, delDmsPlanLubeDetail, addDmsPlanLubeDetail, updateDmsPlanLubeDetail } from '@/api/dms/dmsPlanLubeDetail';
import { DmsPlanLubeDetailVO, DmsPlanLubeDetailQuery, DmsPlanLubeDetailForm } from '@/api/dms/dmsPlanLubeDetail/types';
import { useRoute } from 'vue-router';
import { getDmsBaseMachineInfoList } from "@/api/dms/dmsBaseMachineInfo/index";
import { getDmsBaseLubeStationList } from "@/api/dms/dmsBaseLubeStation/index";
import { getDmsBaseLubeStandardList } from "@/api/dms/dmsBaseLubeStandard/index";

const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag } = toRefs<any>(proxy?.useDict('active_flag'));

const dmsPlanLubeDetailList = ref<DmsPlanLubeDetailVO[]>([]);
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 isUnmounted = ref(false);

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

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

// 列显隐信息
const columns = ref<FieldOption[]>([
        { key: 0, label: `主键标识`, visible: false },
        { key: 1, label: `租户编号`, visible: false },
        { key: 2, label: `计划`, visible: false },
        { 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: false },
        { key: 10, label: `创建人`, visible: false },
        { key: 11, label: `创建时间`, visible: false },
        { key: 12, label: `更新人`, visible: false },
        { key: 13, label: `更新时间`, visible: false },
]);

const initFormData: DmsPlanLubeDetailForm = {
  planLubeDetailId: undefined,
  planLubeId: undefined,
  deviceId: undefined,
  lubeStationId: undefined,
  lubeStandardId: undefined,
  operationDescription: undefined,
  activeFlag: undefined,
  remark: undefined,

}
const data = reactive<PageData<DmsPlanLubeDetailForm, DmsPlanLubeDetailQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planLubeDetailId: undefined,
    planLubeId: undefined,
    deviceId: undefined,
    lubeStationId: undefined,
    lubeStandardId: undefined,
    operationDescription: undefined,
    activeFlag: undefined,
    params: {
    }
  },
  rules: {
    activeFlag: [
      { required: true, message: "激活标识不能为空", trigger: "change" }
    ],
    deviceId: [
      { required: true, message: "设备名称不能为空", trigger: "change" }
    ],
    lubeStationId: [
      { required: true, message: "润滑部位不能为空", trigger: "change" }
    ],
    lubeStandardId: [
      { required: true, message: "润滑标准不能为空", trigger: "change" }
    ],
  }
});

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

/** 安全地执行异步操作，防止组件卸载后更新状态 */
const safeAsync = async <T>(asyncFn: () => Promise<T>, finallyFn?: () => void): Promise<T | undefined> => {
  try {
    if (isUnmounted.value) return undefined;
    return await asyncFn();
  } catch (error) {
    console.error('异步操作失败', error);
    throw error;
  } finally {
    if (!isUnmounted.value && finallyFn) {
      finallyFn();
    }
  }
};


const planLubeId = ref(route.params.planLubeId || '');
const planLubeCode = ref(route.params.planLubeCode || '');
/** 查询润滑计划明细列表 */
const getList = async () => {
  if (isUnmounted.value) return;
  loading.value = true;

  try {
    // 添加计划ID查询参数
    queryParams.value.planLubeId = planLubeId.value as string;
    console.log('查询参数:', queryParams.value);
    console.log(planLubeId.value, planLubeCode.value);
    const res = await listDmsPlanLubeDetail(queryParams.value);
    if (!isUnmounted.value) {
      dmsPlanLubeDetailList.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error('获取润滑计划明细列表失败', error);
  } finally {
    if (!isUnmounted.value) {
      loading.value = false;
    }
  }
}



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

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  // 设置计划ID
  form.value.planLubeId = planLubeId.value as string;
  dmsPlanLubeDetailFormRef.value?.resetFields();
}

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加润滑计划明细";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DmsPlanLubeDetailVO) => {
  if (isUnmounted.value) return;

  reset();
  const _planLubeDetailId = row?.planLubeDetailId || ids.value[0];

  await safeAsync(async () => {
    const res = await getDmsPlanLubeDetail(_planLubeDetailId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改润滑计划明细";
  });
}

/** 提交按钮 */
const submitForm = () => {
  if (isUnmounted.value) return;

  dmsPlanLubeDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      await safeAsync(async () => {
        if (form.value.planLubeDetailId) {
          await updateDmsPlanLubeDetail(form.value);
        } else {
          await addDmsPlanLubeDetail(form.value);
        }

        if (!isUnmounted.value) {
          proxy?.$modal.msgSuccess("操作成功");
          dialog.visible = false;
          await getList();
        }
      }, () => {
        buttonLoading.value = false;
      });
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DmsPlanLubeDetailVO) => {
  if (isUnmounted.value) return;

  const _planLubeDetailIds = row?.planLubeDetailId || ids.value;

  await safeAsync(async () => {
    await proxy?.$modal.confirm('是否确认删除润滑计划明细编号为"' + _planLubeDetailIds + '"的数据项？');
    await delDmsPlanLubeDetail(_planLubeDetailIds);

    if (!isUnmounted.value) {
      proxy?.$modal.msgSuccess("删除成功");
      await getList();
    }
  }, () => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
const handleExport = () => {
  if (isUnmounted.value) return;

  proxy?.download('dms/dmsPlanLubeDetail/export', {
    ...queryParams.value
  }, `dmsPlanLubeDetail_${new Date().getTime()}.xlsx`);
}


/** 获取设备列表 */
const deviceOptions = ref<any[]>([]);
const getDeviceOptions = async () => {
  await safeAsync(async () => {
    const res = await getDmsBaseMachineInfoList(null);
    deviceOptions.value = res.data || [];
  });
}

/** 获取润滑部位列表 */
const stationList = ref<any[]>([]);
const getLubeStations = async () => {
  await safeAsync(async () => {
    const res = await getDmsBaseLubeStationList(null);
    stationList.value = res.data || [];
  });
}

/** 获取润滑标准列表 */
const standardList = ref<any[]>([]);
const getLubeStandards = async () => {
  await safeAsync(async () => {
    const res = await getDmsBaseLubeStandardList(null);
    standardList.value = res.data || [];
  });
}

onMounted(() => {
  isUnmounted.value = false;
  getDeviceOptions();
  getLubeStations();
  getLubeStandards();
  getList();
});

// 在组件卸载时进行清理
onBeforeUnmount(() => {
  isUnmounted.value = true;
});
</script>
