<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-row>
        <el-form ref="stepFormRef" :model="form" label-width="100px">
          <!-- 第一步 -->
          <h4 class="form-header h4" v-if="wfProcessActivityList.length > 0">
            {{wfProcessActivityList[0]?.processActivityName}}
          </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, index) in dmsBillsLubeInstanceActivityList" :key="activity.instanceActivityId">
            <div v-if="activity.processStepOrder != 1">
              <h4 class="form-header h4">{{activity.name || '流程节点'}}</h4>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="润滑级别">
                    <el-select
                      v-model="activity.lubeLevel"
                      placeholder="润滑级别"
                      :disabled="activity.processStepOrder != currentStepOrder">
                      <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="activity.processStepOrder != currentStepOrder"
                      placeholder="润滑组别">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="润滑负责人">
                    <el-input
                      v-model="activity.lubeSupervisor"
                      :disabled="activity.processStepOrder != currentStepOrder"
                      placeholder="润滑负责人">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="处理意见">
                    <el-input
                      v-model="activity.processHandleResolution"
                      :disabled="activity.processStepOrder != currentStepOrder"
                      placeholder="处理意见">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </template>

          <!-- 当前步骤表单 -->
          <div v-if="canSubmitNext && isUpdate">
            <h4 class="form-header h4" v-if="wfProcessActivityList.length > dmsBillsLubeInstanceActivityList.length">
              {{wfProcessActivityList[dmsBillsLubeInstanceActivityList.length]?.processActivityName}}
            </h4>
            <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="润滑组别">
                  <el-input v-model="nextStepForm.lubeGroup" placeholder="润滑组别"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="润滑负责人">
                  <el-input v-model="nextStepForm.lubeSupervisor" placeholder="润滑负责人"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="处理意见">
                  <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-col>
            </el-row>
          </div>
        </el-form>
      </el-row>
    </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>
  </div>
</template>

<script setup name="DmsBillsLubeInstanceActivity" lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, computed } from 'vue';
import { ElFormInstance } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import {
  listDmsBillsLubeInstanceActivity,
  addDmsBillsLubeInstanceActivity
} from '@/api/dms/dmsBillsLubeInstanceActivity';
import {
  DmsBillsLubeInstanceActivityVO,
  DmsBillsLubeInstanceActivityForm
} from '@/api/dms/dmsBillsLubeInstanceActivity/types';
import { listDmsBillsLubeInstance } from '@/api/dms/dmsBillsLubeInstance';
// import { listWfprocessactivity } from '@/api/system/common/wfprocessactivity';
// import { selectPlanLubeDetailByPlanLubeId } from '@/api/dms/dmsPlanLubeDetail';
// import { selectUserIdByDmsBillsLubeInstanceActivityId } from '@/api/dms/dmsBillsLubeInstanceActivity';
import { useUserStore } from '@/store/modules/user';

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

// 表单实例
const stepFormRef = ref<ElFormInstance>();

// 基础数据定义
const loading = ref(true);
const dmsBillsLubeInstanceActivityList = ref<DmsBillsLubeInstanceActivityVO[]>([]);
const wfProcessActivityList = ref<any[]>([]);
const billsInfo = ref<any>({});
const planLubeDetail = ref<any[]>([]);
const billsStatusCheck = ref('');
const isUpdate = ref(true);
const planLubeId = ref('');
const currentStepOrder = ref(0);
const lubeInstanceId = route.params.lubeInstanceId as string;

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

// 是否可以提交下一步
const canSubmitNext = computed(() => {
  return dmsBillsLubeInstanceActivityList.value.length < wfProcessActivityList.value.length;
});

// 表单数据
const form = reactive<DmsBillsLubeInstanceActivityForm>({
  instanceActivityId: undefined,
  lubeInstanceId: lubeInstanceId,
  wfDefinitionId: undefined,
  wfNodeId: undefined,
  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 nextStepForm = reactive<DmsBillsLubeInstanceActivityForm>({
  instanceActivityId: undefined,
  lubeInstanceId: lubeInstanceId,
  wfDefinitionId: undefined,
  wfNodeId: undefined,
  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 queryParams = reactive({
  pageNum: 1,
  pageSize: 50,
  lubeInstanceId: lubeInstanceId,
});

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

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

// 获取工单实例数据
const getDmsBillsLubeInstance = async () => {
  try {
    const res = await listDmsBillsLubeInstance({ lubeInstanceId });
    if (res.rows && res.rows.length > 0) {
      billsInfo.value = res.rows[0];
      planLubeId.value = res.rows[0].planLubeId;

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

      // 获取流程定义
      getWfprocessActivity(res.rows[0].wfProcessId || 106);

      // 获取润滑计划详情
      if (planLubeId.value) {
        getPlanLubeDetail();
      }
    }
  } catch (error) {
    console.error('获取工单实例数据失败', error);
  }
};

// 获取流程定义
const getWfprocessActivity = async (wfProcessId: number) => {
  try {
    // const res = await listWfprocessactivity({ wfProcessId });
    wfProcessActivityList.value = res.rows;

    // 更新实例节点名称
    if (dmsBillsLubeInstanceActivityList.value.length > 0) {
      dmsBillsLubeInstanceActivityList.value.forEach(activity => {
        const matchedProcess = wfProcessActivityList.value.find(
          process => process.processActivityOrder === activity.processStepOrder
        );
        if (matchedProcess) {
          activity.name = matchedProcess.processActivityName;
        }
      });
    }

    // 检查当前用户是否有权限处理
    checkUserPermission();
  } catch (error) {
    console.error('获取流程定义失败', error);
  }
};

// 获取润滑计划详情
const getPlanLubeDetail = async () => {
  try {
    const res = await selectPlanLubeDetailByPlanLubeId(planLubeId.value);
    planLubeDetail.value = res.rows;
  } catch (error) {
    console.error('获取润滑计划详情失败', error);
  } finally {
    loading.value = false;
  }
};

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

    // 填充第一步数据
    if (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
      });

      // 初始化下一步表单数据
      const lastActivity = res.rows[res.rows.length - 1];
      Object.assign(nextStepForm, {
        lubeGroup: lastActivity.lubeGroup,
        lubeSupervisor: lastActivity.lubeSupervisor,
        lubeLevel: lastActivity.lubeLevel,
        processStepOrder: res.rows.length + 1,
        processHandleResolution: null
      });

      currentStepOrder.value = res.rows.length + 1;
    }
  } catch (error) {
    console.error('获取工单实例节点数据失败', error);
  } finally {
    loading.value = false;
  }
};

// 检查当前用户是否有权限处理
const checkUserPermission = async () => {
  if (dmsBillsLubeInstanceActivityList.value.length === wfProcessActivityList.value.length) {
    try {
      const hasPermission = await selectUserIdByDmsBillsLubeInstanceActivityId(
        lubeInstanceId,
        userStore.userId
      );

      if (!hasPermission) {
        proxy?.$modal.alert("您没有权限处理此工单");
        // 关闭当前标签页
        proxy?.$store.dispatch("tagsView/delView", route);
        // 跳转到列表页
        router.replace({ path: "/dms/deviceLube/dmsBillsLubeInstance" });
      }
    } catch (error) {
      console.error('检查权限失败', error);
    }
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    if (!nextStepForm.processHandleResolution) {
      proxy?.$modal.msgError("请填写处理意见");
      return;
    }

    // 设置流程定义ID
    if (wfProcessActivityList.value.length > 0) {
      const currentProcess = wfProcessActivityList.value.find(
        process => process.processActivityOrder === nextStepOrder.value
      );
      if (currentProcess) {
        nextStepForm.processActivityId = currentProcess.processActivityId;
      }
    }

    // 设置其他字段
    nextStepForm.processStepOrder = nextStepOrder.value;
    nextStepForm.wfLength = wfProcessActivityList.value.length;

    // 提交
    await addDmsBillsLubeInstanceActivity(nextStepForm);
    proxy?.$modal.msgSuccess("提交成功");

    // 重新加载数据
    await getList();
  } catch (error) {
    console.error('提交失败', error);
    proxy?.$modal.msgError("提交失败");
  }
};
</script>

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