<template>
  <div class="p-2">
    <!-- 工单信息区域 -->
    <h4 class="form-header h4">工单信息</h4>
    <el-card shadow="never" class="mb-[10px]">
      <el-form label-width="120px">
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="工单编号">
              <el-input v-model="billsInfo.billsLubeCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="工单状态">
              <el-input v-model="billsStatusCheck" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="申请人">
              <el-input v-model="billsInfo.createBy" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="申请时间">
              <el-input v-model="billsInfo.createTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="2">
            <el-form-item label="备注">
              <el-input v-model="billsInfo.remark" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 流程步骤展示区域 -->
    <el-card shadow="never" class="mb-[10px]">
      <el-form ref="stepFormRef" :model="form" label-width="100px">
        <!-- 第一步 -->
        <h4 class="form-header h4" v-if="dmsBillsLubeInstanceActivityList.length > 0">已处理节点：步骤1（要求参数）</h4>
        <el-row v-if="dmsBillsLubeInstanceActivityList.length > 0">
          <el-col :span="8">
            <el-form-item label="润滑级别" prop="lubeLevel">
              <el-select v-model="form.lubeLevel" placeholder="润滑级别" disabled>
                <el-option
                  v-for="dict in lube_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="润滑组别" prop="lubeGroup">
              <el-input v-model="form.lubeGroup" placeholder="请输入润滑组别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="润滑负责人" prop="lubeSupervisor">
              <el-input v-model="form.lubeSupervisor" placeholder="请输入润滑负责人" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 中间步骤 (已处理的后续节点) -->
        <template v-for="(activity) in dmsBillsLubeInstanceActivityList" :key="activity.instanceActivityId">
          <div v-if="activity.processStepOrder && activity.processStepOrder > 1">
            <h4 class="form-header h4">{{ `已处理节点：步骤${activity.processStepOrder}（实际参数）` }}</h4>
            <el-row>
              <el-col :span="8">
                <el-form-item label="润滑级别">
                  <el-select
                    v-model="activity.lubeLevel"
                    placeholder="润滑级别"
                    disabled>
                    <el-option
                      v-for="dict in lube_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="润滑组别">
                  <el-input
                    v-model="activity.lubeGroup"
                    disabled
                    placeholder="润滑组别">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="润滑负责人">
                  <el-input
                    v-model="activity.lubeSupervisor"
                    disabled
                    placeholder="润滑负责人">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="处理意见">
                  <el-input
                    v-model="activity.processHandleResolution"
                    disabled
                    placeholder="处理意见">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>

        <!-- 当前步骤表单 (用于提交新节点) -->
        <div v-if="isUpdate">
          <h4 class="form-header h4">当前处理节点：步骤{{ nextStepOrder }}{{ nextStepOrder === 2 ? '（实际参数）' : '' }}</h4>
          <el-form ref="nextStepFormRef" :model="nextStepForm" :rules="nextStepFormRules" label-width="100px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="润滑级别" prop="lubeLevel">
                  <el-select v-model="nextStepForm.lubeLevel" placeholder="润滑级别">
                    <el-option
                      v-for="dict in lube_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="润滑组别" prop="lubeGroup">
                  <el-input v-model="nextStepForm.lubeGroup" placeholder="润滑组别"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="润滑负责人" prop="lubeSupervisor">
                  <el-input v-model="nextStepForm.lubeSupervisor" placeholder="润滑负责人"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="nextStepOrder > 1">
                <el-form-item label="处理意见" prop="processHandleResolution">
                  <el-input v-model="nextStepForm.processHandleResolution" placeholder="处理意见"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" class="text-center mt-4">
                <el-button type="primary" @click="submitForm">提 交</el-button>
                <el-button v-if="billsInfo && billsInfo.lubeInstanceId !== null && billsInfo.status !== 'draft'" type='primary'
                           @click='handleApprovalRecord'>
                  流程进度
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-form>
    </el-card>

    <!-- 润滑计划详情区域 -->
    <el-card shadow="never">
      <h4 class="form-header h4 text-center">润滑计划详细信息</h4>
      <el-table v-loading="loading" :data="planLubeDetail">
        <el-table-column label="计划ID" align="center" prop="planLubeId" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="润滑部位" align="center" prop="lubeStationName" />
        <el-table-column label="润滑标准" align="center" prop="lubeStandardCode" />
        <el-table-column label="操作描述" align="center" prop="operationDescription" />
      </el-table>
    </el-card>

    <!-- 提交组件 -->
    <submitVerify ref='submitVerifyRef' :task-variables="taskVariables as any" @submit-callback='submitCallback' />
    <!-- 审批记录 -->
    <approvalRecord ref='approvalRecordRef' />
  </div>
</template>

<script setup name="DmsBillsLubeInstanceActivity" lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'; // 引入 FormInstance 和 FormRules 类型
import {
  listDmsBillsLubeInstanceActivity,
  addDmsBillsLubeInstanceActivity
} from '@/api/dms/dmsBillsLubeInstanceActivity';
import {
  DmsBillsLubeInstanceActivityVO,
  DmsBillsLubeInstanceActivityForm
} from '@/api/dms/dmsBillsLubeInstanceActivity/types';
import { getDmsBillsLubeInstance } from '@/api/dms/dmsBillsLubeInstance';
import { getDmsPlanLubeDetail } from '@/api/dms/dmsPlanLubeDetail';
import {DmsPlanLubeDetailVO} from "@/api/dms/dmsPlanLubeDetail/types";
// 引入工作流相关组件和API
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { lube_level, process_handle_status } = toRefs<any>(proxy?.useDict('lube_level', 'process_handle_status'));
const route = useRoute();

// 表单实例
const stepFormRef = ref<FormInstance>(); // 主表单 ref
const nextStepFormRef = ref<FormInstance>(); // 下一步表单 ref

// 工作流相关
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const taskVariables = ref<any>({});
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: 'Lube01',
  variables: {}
});

// 基础数据定义
const loading = ref(true);
const dmsBillsLubeInstanceActivityList = ref<DmsBillsLubeInstanceActivityVO[]>([]);
const billsInfo = ref<any>({}); // 工单主体信息
const planLubeDetail = ref<DmsPlanLubeDetailVO[]>([]);
const billsStatusCheck = ref(''); // 工单状态显示文本
const isUpdate = ref(true); // 控制是否显示提交表单区域
const planLubeId = ref(''); // 润滑计划ID，从工单信息中获取
const lubeInstanceId = route.params.lubeInstanceId as string; // 类型断言
const buttonLoading = ref(false);

// 计算下一步序号
const nextStepOrder = computed(() => {
  return dmsBillsLubeInstanceActivityList.value.length + 1;
});

// 表单数据 (用于展示第一个已处理节点的信息)
const form = reactive<Partial<DmsBillsLubeInstanceActivityForm>>({
  lubeGroup: undefined,
  lubeSupervisor: undefined,
  lubeLevel: undefined,
  remark: undefined,
});

// 下一步表单 (用于提交新的节点)
const nextStepForm = reactive<DmsBillsLubeInstanceActivityForm>({
  instanceActivityId: undefined,
  lubeInstanceId: lubeInstanceId,
  lubeGroup: undefined,
  lubeSupervisor: undefined,
  lubeLevel: undefined,
  processHandleResolution: undefined,
  processHandleStatus: undefined,
  processStepOrder: undefined,
  startTime: undefined,
  endTime: undefined,
  handleUserId: undefined,
  handleBy: undefined,
  handleTime: undefined,
  transferUserId: undefined,
  attr1: undefined,
  remark: undefined,
});

// 下一步表单校验规则
const nextStepFormRules = reactive<FormRules>({
  lubeLevel: [{ required: true, message: "润滑级别不能为空", trigger: "change" }],
  lubeGroup: [{ required: true, message: "润滑组别不能为空", trigger: "blur" }],
  lubeSupervisor: [{ required: true, message: "润滑负责人不能为空", trigger: "blur" }],
  // 处理意见仅在第二步及以后验证
  processHandleResolution: [{ required: nextStepOrder.value > 1, message: "处理意见不能为空", trigger: "blur" }],
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 50,
  lubeInstanceId: lubeInstanceId,
});

// 初始化数据
onMounted(() => {
  // 判断当前页面是查看还是编辑
  if(route.name === 'childDmsBillsLubeInstanceActivity') {
    isUpdate.value = true;
  } else if(route.name === 'selectChildDmsBillsLubeInstanceActivity') {
    isUpdate.value = false;
  }

  // 加载工单实例数据
  dmsBillsLubeInstance();
  // 加载工单实例节点数据
  getList();
});

// 获取工单实例数据
const dmsBillsLubeInstance = async () => {

    // const res = await listDmsBillsLubeInstance(queryParams);
    //billsInfo.value = res.rows[0];
    const _lubeInstanceId = lubeInstanceId;
    const res = await getDmsBillsLubeInstance(_lubeInstanceId);
    billsInfo.value = res.data;

      // 确保 planLubeId 是字符串类型
      // const lubeIdFromServer = res.rows[0].planLubeId;
      const lubeIdFromServer = res.data.planLubeId;
      planLubeId.value = typeof lubeIdFromServer === 'number' ? String(lubeIdFromServer) : lubeIdFromServer;

      // 设置工单状态显示文本
      if (lube_level.value && billsInfo.value.lubeStatus !== undefined) {
        const statusItem = lube_level.value.find((item: any) => String(item.value) === String(billsInfo.value.lubeStatus));
        billsStatusCheck.value = statusItem ? statusItem.label : '未知状态';
      } else {
        billsStatusCheck.value = '未知状态';
      }

      // 获取润滑计划详情
      if (planLubeId.value) {
        getPlanLubeDetailData();
      }
};

// 获取润滑计划详情
const getPlanLubeDetailData = async () => {
  if (!planLubeId.value) return;
  loading.value = true;
  try {
    const res = await getDmsPlanLubeDetail(planLubeId.value);
    planLubeDetail.value = res && res.rows ? [res.rows] : [];
  } catch (error) {
    console.error('获取润滑计划详情失败', error);
    proxy?.$modal.msgError("获取润滑计划详情失败");
  }
};

// 获取工单实例节点数据
const getList = async () => {
  loading.value = true;
  try {
    const res = await listDmsBillsLubeInstanceActivity(queryParams);
    dmsBillsLubeInstanceActivityList.value = res.rows;

    // 填充第一步数据 (用于表单展示)
    if (res.rows && res.rows.length > 0) {
      Object.assign(form, {
        lubeGroup: res.rows[0].lubeGroup,
        lubeSupervisor: res.rows[0].lubeSupervisor,
        lubeLevel: res.rows[0].lubeLevel,
        remark: res.rows[0].remark
      });

      // 根据步骤数初始化下一步表单数据
      if (nextStepOrder.value === 2) {
        // 第二步，复制第一步的润滑组别和润滑负责人
        Object.assign(nextStepForm, {
          lubeGroup: res.rows[0].lubeGroup,
          lubeSupervisor: res.rows[0].lubeSupervisor,
          lubeLevel: res.rows[0].lubeLevel,
          processHandleResolution: null, // 第二步需要填写处理意见
          remark: ''
        });
      } else if (nextStepOrder.value > 2) {
        // 第三步及以后，使用最后一个节点的数据
        const lastActivity = res.rows[res.rows.length - 1];
        Object.assign(nextStepForm, {
          lubeGroup: lastActivity.lubeGroup,
          lubeSupervisor: lastActivity.lubeSupervisor,
          lubeLevel: lastActivity.lubeLevel,
          processHandleResolution: null, // 清空处理意见
          remark: ''
        });
      }
    } else {
      // 如果没有已处理节点，则 nextStepForm 全新初始化
      Object.assign(nextStepForm, {
        lubeGroup: undefined,
        lubeSupervisor: undefined,
        lubeLevel: undefined,
        processHandleResolution: null,
        remark: ''
      });
    }

    // 更新表单校验规则
    nextStepFormRules.processHandleResolution = [{
      required: nextStepOrder.value > 1,
      message: "处理意见不能为空",
      trigger: "blur"
    }];

  } catch (error) {
    console.error('获取工单实例节点数据失败', error);
    proxy?.$modal.msgError("获取工单实例节点数据失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!nextStepFormRef.value) return;
  await nextStepFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        buttonLoading.value = true;
        // 设置流程步骤顺序
        nextStepForm.processStepOrder = nextStepOrder.value;
        nextStepForm.lubeInstanceId = lubeInstanceId;

        // 在第一步时不需要处理意见
        if (nextStepOrder.value === 1) {
          nextStepForm.processHandleResolution = null;
        }

        // 提交
        const res = await addDmsBillsLubeInstanceActivity(nextStepForm);

        // 启动工作流
        await handleStartWorkFlow(res.data);

      } catch (error) {
        console.error('提交失败', error);
        proxy?.$modal.msgError("提交失败，请检查数据或联系管理员");
        buttonLoading.value = false;
      }
    } else {
      proxy?.$modal.msgError("表单校验失败，请检查输入项");
    }
  });
};

// 启动工作流
const handleStartWorkFlow = async (data: any) => {
  try {
    submitFormData.value.businessId = lubeInstanceId;
    //流程变量
    taskVariables.value = {
      entity: data
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};

// 审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(lubeInstanceId);
};

// 提交回调
const submitCallback = async () => {
  await getList(); // 刷新列表获取最新节点
  proxy?.$modal.msgSuccess("操作成功");
};
</script>

<style scoped>
.form-header {
  font-size: 15px;
  color: #409eff;
  border-bottom: 1px solid #ddd;
  margin: 8px 0 15px;
  padding-bottom: 10px;
}
</style>
