<template>
  <div class="app-container">
    <!-- 头部检修计划信息 -->
    <h4 class="form-header h4">保养计划信息</h4>
    <el-form label-width="120px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="保养计划编号" prop="planRepairId">
            <el-input v-model="planMaintIdCheck" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="保养负责人" prop="planRepairId">
            <el-input v-model="repairSupervisor" disabled />
          </el-form-item>
        </el-col>
<!--      <el-col :span="8" :offset="2">-->
<!--        <el-form-item label="登录账号" prop="deviceId">-->
<!--          <el-input  v-model="form.deviceId" disabled />-->
<!--        </el-form-item>-->
<!--      </el-col>-->
      </el-row>
    </el-form>
    <h4 class="form-header h4">详细信息</h4>

    <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="planRepairDetailId">
              <el-input v-model="queryParams.planRepairDetailId" placeholder="请输入主键标识" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划ID，关联dms_plan_repair的plan_maint_id" prop="planRepairId">
              <el-input v-model="queryParams.planRepairId" placeholder="请输入计划ID，关联dms_plan_repair的plan_maint_id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="检修计划明细类型(1设备 2设备类型)" prop="repairDetailTargetType">
              <el-select v-model="queryParams.repairDetailTargetType" placeholder="请选择检修计划明细类型(1设备 2设备类型)" clearable >
                <el-option v-for="dict in repair_detail_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="检修计划明细ID,根据检修计划明细类型关联对应表的主键" prop="repairDetailTargetId">
              <el-input v-model="queryParams.repairDetailTargetId" placeholder="请输入检修计划明细ID,根据检修计划明细类型关联对应表的主键" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="故障类别" prop="faultType">
              <el-select v-model="queryParams.faultType" placeholder="请选择故障类别" clearable >
                <el-option v-for="dict in fault_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="检修说明" prop="repairDesc">
              <el-input v-model="queryParams.repairDesc" placeholder="请输入检修说明" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="检修标准" prop="repairProtocol">
              <el-input v-model="queryParams.repairProtocol" placeholder="请输入检修标准" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="操作描述" prop="operationDescription">
              <el-input v-model="queryParams.operationDescription" 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="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dms:dmsPlanRepairDetail:add']">新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="addmembers"
          v-hasPermi="['dms:dmsRepairDetail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dms:dmsRepairDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dms:dmsRepairDetail:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dms:dmsPlanRepairDetail:export']">导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="dmsPlanRepairDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
  <!--    <el-table-column label="主键标识" align="center" prop="planRepairDetailId" v-if="columns[0].visible"/> -->
  <!--    <el-table-column label="计划ID，关联dms_plan_repair的plan_maint_id" align="center" prop="planRepairId" v-if="columns[2].visible"/> -->
  <!--    <el-table-column label="检修计划明细类型(1设备 2设备类型)" align="center" prop="repairDetailTargetType" v-if="columns[3].visible"/> -->
  <!--    <el-table-column label="检修计划明细ID,根据检修计划明细类型关联对应表的主键" align="center" prop="repairDetailTargetId" v-if="columns[4].visible"/> -->
        <el-table-column label="设备名称" align="center" prop="repairDetailTargetId" v-if="columns[4].visible">
          <template #default="scope">
            <template v-for="(machine, index) in machineList" :key="index">
              <span 
                v-if="scope.row.repairDetailTargetId == machine.machineId">
                {{ machine.machineName }}
              </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="故障类别" align="center" prop="faultType" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="fault_type" :value="scope.row.faultType"/>
          </template>
        </el-table-column>
        <el-table-column label="检修说明" align="center" prop="repairDesc" v-if="columns[6].visible"/>
        <el-table-column label="检修标准" align="center" prop="repairProtocol" v-if="columns[7].visible"/>
        <el-table-column label="操作描述" align="center" prop="operationDescription" v-if="columns[8].visible"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
  <!--        <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="addRepairDetaile(scope.row)"
              v-hasPermi="['dms:dmsRepairDetail:edit']"
            >确定/修改</el-button> -->
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dms:dmsPlanRepairDetail:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dms:dmsPlanRepairDetail:remove']">删除</el-button>
          </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="dmsPlanRepairDetailFormRef" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="主键标识" prop="planRepairDetailId">
          <el-input v-model="form.planRepairDetailId" placeholder="请输入主键标识" />
        </el-form-item>
        <el-form-item label="计划ID，关联dms_plan_repair的plan_maint_id" prop="planRepairId">
          <el-input v-model="form.planRepairId" placeholder="请输入计划ID，关联dms_plan_repair的plan_maint_id" />
        </el-form-item>
        <el-form-item label="检修计划明细类型(1设备 2设备类型)" prop="repairDetailTargetType">
          <el-select v-model="form.repairDetailTargetType" placeholder="请选择检修计划明细类型(1设备 2设备类型)">
            <el-option
                v-for="dict in repair_detail_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检修计划明细ID,根据检修计划明细类型关联对应表的主键" prop="repairDetailTargetId">
          <el-input v-model="form.repairDetailTargetId" placeholder="请输入检修计划明细ID,根据检修计划明细类型关联对应表的主键" />
        </el-form-item> -->
        <el-form-item label="巡检设备" prop="repairDetailTargetId">
          <el-select v-model="form.repairDetailTargetId" placeholder="请选择设备类型">
            <el-option
              v-for="item in machineList"
              :key="item.machineId"
              :label="item.machineName"
              :value="item.machineId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保养等级" prop="faultType">
          <el-select v-model="form.faultType" placeholder="请选择保养等级">
            <el-option
              v-for="dict in fault_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检修说明" prop="repairDesc">
          <el-input v-model="form.repairDesc" placeholder="请输入检修说明" />
        </el-form-item>
        <el-form-item label="检修标准" prop="repairProtocol">
          <el-input v-model="form.repairProtocol" placeholder="请输入检修标准" />
        </el-form-item>
        <el-form-item label="操作描述" prop="operationDescription">
          <el-input v-model="form.operationDescription" placeholder="请输入操作描述" />
        </el-form-item>
        <!-- 备注功能先注释，因为接口未支持 -->
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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="DmsPlanRepairDetail" lang="ts">
import { listDmsPlanRepairDetail, getDmsPlanRepairDetail, delDmsPlanRepairDetail, addDmsPlanRepairDetail, updateDmsPlanRepairDetail } from '@/api/dms/dmsPlanRepairDetail';
import { DmsPlanRepairDetailVO, DmsPlanRepairDetailQuery, DmsPlanRepairDetailForm } from '@/api/dms/dmsPlanRepairDetail/types';
import { getDmsPlanRepair } from '@/api/dms/dmsPlanRepair';
import { getDmsBaseMachineInfoList } from '@/api/dms/dmsBaseMachineInfo';
import { useRoute } from 'vue-router';
import { ComponentInternalInstance, getCurrentInstance, reactive, ref, toRefs, onMounted, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import DictTag from '@/components/DictTag/index.vue';
import { useDict } from '@/utils/dict';

// 获取路由参数
const route = useRoute();
const planMaintIdCheck = ref<string | number>('');
const repairType = ref<string>('');
const repairSupervisor = ref<string>('');
// 设备信息列表，替代原来的ledgerList
const machineList = ref<any[]>([]);
// 检修计划列表
const dmsRepairList = ref<any[]>([]);
// 保养部位列表
const stationList = ref<any[]>([]);
// 保养标准列表
const standardList = ref<any[]>([]);

// CRON表达式和时间限制相关字段
const cronExpression = ref<string>('');
const timeLimitDays = ref<number | undefined>(undefined);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 使用字典
const { fault_type } = useDict('fault_type');

const dmsPlanRepairDetailList = ref<DmsPlanRepairDetailVO[]>([]);
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<FormInstance>();
const dmsPlanRepairDetailFormRef = ref<FormInstance>();

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

// 列显隐信息
const columns = ref<FieldOption[]>([
        { key: 0, label: `主键标识`, visible: false },
        { key: 1, label: `租户编号`, visible: false },
        { key: 2, label: `计划ID，关联dms_plan_repair的plan_maint_id`, visible: false },
        { key: 3, label: `检修计划明细类型(1设备 2设备类型)`, visible: false },
        { key: 4, label: `检修计划明细ID,根据检修计划明细类型关联对应表的主键`, 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: DmsPlanRepairDetailForm = {
  planRepairDetailId: undefined,
  planRepairId: undefined,
  repairDetailTargetType: '1', // 默认为设备类型
  repairDetailTargetId: undefined,
  faultType: undefined,
  repairDesc: undefined,
  repairProtocol: undefined,
  operationDescription: undefined,
  // remark字段在接口未定义，暂时不使用
  // remark: undefined, 
}
const data = reactive<PageData<DmsPlanRepairDetailForm, DmsPlanRepairDetailQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planRepairDetailId: undefined,
    planRepairId: undefined,
    repairDetailTargetType: undefined,
    repairDetailTargetId: undefined,
    faultType: undefined,
    repairDesc: undefined,
    repairProtocol: undefined,
    operationDescription: undefined,
    params: {
    }
  },
  rules: {
    planRepairId: [
      { required: true, message: "计划ID不能为空", trigger: "blur" }
    ],
    repairDetailTargetId: [
      { required: true, message: "设备ID不能为空", trigger: "blur" }
    ],
    faultType: [
      { required: true, message: "保养等级不能为空", trigger: "blur" }
    ],
  }
});

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

/**
 * 初始化方法，获取路由参数设置相关查询条件
 */
const init = () => {
  // 从路由中获取计划ID
  const planMaintId = route.params.planMaintId;
  if (!planMaintId) return;
  
  // 转换为字符串或数字类型
  let finalId: string | number;
  if (typeof planMaintId === 'string') {
    // 尝试转为数字
    const numId = Number(planMaintId);
    finalId = isNaN(numId) ? planMaintId : numId;
  } else if (Array.isArray(planMaintId) && planMaintId.length > 0) {
    // 尝试从数组中取第一个元素并转为合适的类型
    const strId = String(planMaintId[0]);
    const numId = Number(strId);
    finalId = isNaN(numId) ? strId : numId;
  } else {
    // 无效的ID类型，使用默认值
    finalId = '';
    return;
  }
  
  // 设置本地变量和查询参数
  planMaintIdCheck.value = finalId;
  queryParams.value.planRepairId = finalId;
  
  // 加载数据
  getList();
  getPlanRepair();
  getDeviceMachine();
};

/** 
 * 查询检修计划信息，获取计划编号和负责人信息
 */
const getPlanRepair = async () => {
  if (!planMaintIdCheck.value) return;
  
  try {
    const res = await getDmsPlanRepair(planMaintIdCheck.value);
    if (res && res.data) {
      repairType.value = res.data.repairType;
      repairSupervisor.value = res.data.repairSupervisor;
    }
  } catch (error) {
    console.error('获取检修计划信息失败', error);
    proxy?.$modal.msgError("获取检修计划信息失败");
  }
};

/**
 * 查询设备信息列表 (替代原来的设备台账)
 */
const getDeviceMachine = async () => {
  try {
    const res = await getDmsBaseMachineInfoList(queryParams.value);
    if (res && res.data) {
      machineList.value = res.data;
    } else {
      // 后备方案：如果API调用没有返回数据
      machineList.value = [
        { machineId: '1', machineName: '设备1' },
        { machineId: '2', machineName: '设备2' },
        { machineId: '3', machineName: '设备3' }
      ];
    }
  } catch (error) {
    console.error('获取设备信息失败', error);
    proxy?.$modal.msgError("获取设备信息失败");
    
    // 发生错误时使用本地数据作为后备
    machineList.value = [
      { machineId: '1', machineName: '设备1' },
      { machineId: '2', machineName: '设备2' },
      { machineId: '3', machineName: '设备3' }
    ];
  }
};

/**
 * 查询检修计划明细列表
 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listDmsPlanRepairDetail(queryParams.value);
    dmsPlanRepairDetailList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取检修计划明细列表失败', error);
    proxy?.$modal.msgError("获取检修计划明细列表失败");
  } finally {
    loading.value = false;
  }
};

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

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

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

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

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

/**
 * 新增按钮操作
 */
const handleAdd = () => {
  reset();
  // 设置计划ID
  form.value.planRepairId = planMaintIdCheck.value;
  dialog.visible = true;
  dialog.title = "添加保养计划明细";
};

/**
 * 修改按钮操作
 */
const handleUpdate = async (row?: DmsPlanRepairDetailVO) => {
  reset();
  const _planRepairDetailId = row?.planRepairDetailId || ids.value[0];
  try {
    const res = await getDmsPlanRepairDetail(_planRepairDetailId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改保养计划明细";
  } catch (error) {
    console.error('获取检修计划明细详情失败', error);
    proxy?.$modal.msgError("获取保养计划明细详情失败");
  }
};

/**
 * 提交表单数据
 */
const submitForm = () => {
  dmsPlanRepairDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 设置计划ID为当前检修计划ID
        form.value.planRepairId = planMaintIdCheck.value;
        
        if (form.value.planRepairDetailId) {
          await updateDmsPlanRepairDetail(form.value);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addDmsPlanRepairDetail(form.value);
          proxy?.$modal.msgSuccess("新增成功");
        }
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('保存保养计划明细失败', error);
        proxy?.$modal.msgError("保存失败");
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/**
 * 删除按钮操作
 */
const handleDelete = async (row?: DmsPlanRepairDetailVO) => {
  // 确保_planRepairDetailIds是string类型
  const _planRepairDetailIds: string = row?.planRepairDetailId 
    ? String(row.planRepairDetailId) 
    : String(ids.value.join(','));
  
  try {
    await proxy?.$modal.confirm('是否确认删除保养计划明细编号为"' + _planRepairDetailIds + '"的数据项？');
    await delDmsPlanRepairDetail(_planRepairDetailIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (error) {
    console.error('删除保养计划明细失败', error);
  }
};

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

// 页面加载时初始化
onMounted(() => {
  init();
});
</script>
<style scoped>
.form-header {
  font-size: 16px;
  color: #606266;
  padding: 8px 15px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
}
</style>
