<template>
  <div class="p-2">
    <!-- 操作按钮区域 -->
    <el-card shadow="never">
      <div style="display: flex; justify-content: space-between">
        <div>
          <el-button 
            v-if="submitButtonShow" 
            :loading="buttonLoading" 
            type="info" 
            @click="submitForm('draft')">
            暂存
          </el-button>
          <el-button 
            v-if="submitButtonShow" 
            :loading="buttonLoading" 
            type="primary" 
            @click="submitForm('submit')">
            提交
          </el-button>
          <el-button 
            v-if="approvalButtonShow" 
            :loading="buttonLoading" 
            type="primary" 
            @click="approvalVerifyOpen">
            {{ currentStepName }}
          </el-button>
          <el-button 
            v-if="workOrder?.wfDefinitionId" 
            type="primary" 
            @click="handleApprovalRecord">
            流程进度
          </el-button>
        </div>
        <div>
          <el-button @click="goBack()">返回</el-button>
        </div>
      </div>
    </el-card>

    <!-- 工单基本信息区域 -->
    <el-card shadow="never" class="mb-[10px]">
      <h4 class="form-header">工单基本信息</h4>
      <el-form label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单编号">
              <el-input v-model="workOrder.billsMaintCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工单状态">
              <el-input v-model="workOrderStatusText" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人">
              <el-input v-model="workOrder.createBy" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 当前步骤处理区域 -->
    <el-card shadow="never">
      <h4 class="form-header">{{ currentStepTitle }}</h4>
      <el-form 
        ref="processFormRef" 
        v-loading="loading" 
        :disabled="routeParams.type === 'view'" 
        :model="form" 
        :rules="rules" 
        label-width="120px">
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="保养级别" prop="maintLevel">
              <el-select v-model="form.maintLevel" placeholder="请选择保养级别">
                <el-option 
                  v-for="dict in maint_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="maintGroup">
              <el-input v-model="form.maintGroup" placeholder="请输入保养组别" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保养负责人" prop="maintSupervisor">
              <el-input v-model="form.maintSupervisor" placeholder="请输入保养负责人" />
            </el-form-item>
          </el-col>
          
          <!-- 处理意见：除第一步外都需要 -->
          <el-col :span="24" v-if="needProcessResolution">
            <el-form-item label="处理意见" prop="processHandleResolution">
              <el-input 
                v-model="form.processHandleResolution" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入处理意见" />
                </el-form-item>
              </el-col>
            </el-row>
      </el-form>
    </el-card>

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

<script setup name="DmsMaintInstanceActivity" lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import {
  addDmsMaintInstanceActivity,
  getDmsMaintInstanceActivityList
} from '@/api/dms/dmsMaintInstanceActivity';
import {
  DmsMaintInstanceActivityForm
} from '@/api/dms/dmsMaintInstanceActivity/types';
import { getDmsBillsMaintInstance } from '@/api/dms/dmsBillsMaintInstance';
import { pageByTaskWait } from '@/api/workflow/task';
import { getCurrentDateTime } from '@/utils/dateUtils';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { maint_level } = toRefs<any>(proxy?.useDict('maint_level'));
const route = useRoute();
const router = useRouter();

// 基础数据
const loading = ref(true);
const buttonLoading = ref(false);
const routeParams = ref<Record<string, any>>({});
const workOrder = ref<any>({});
const workOrderStatusText = ref('');

// 表单引用
const processFormRef = ref<FormInstance>();
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

// 当前任务信息
const currentTask = ref<any>(null);
const taskVariables = ref<any>({});

// 表单数据
const initFormData = {
  maintInstanceId: undefined,
  maintLevel: undefined,
  maintGroup: undefined,
  maintSupervisor: undefined,
  processHandleResolution: undefined
};

const form = reactive<Partial<DmsMaintInstanceActivityForm>>({ ...initFormData });

// 表单验证规则
const rules = reactive<FormRules>({
  maintLevel: [{ required: true, message: "保养级别不能为空", trigger: "change" }],
  maintGroup: [{ required: true, message: "保养组别不能为空", trigger: "blur" }],
  maintSupervisor: [{ required: true, message: "保养负责人不能为空", trigger: "blur" }],
  processHandleResolution: [{ required: false, message: "处理意见不能为空", trigger: "blur" }]
});

// 计算属性
const approvalButtonShow = computed(() => {
  return routeParams.value.type === 'approval' && currentTask.value;
});

const currentStepName = computed(() => {
  if (!currentTask.value) return '处理';
  return currentTask.value.nodeName || '处理';
});

const currentStepTitle = computed(() => {
  if (!currentTask.value) return '工单处理';
  return `当前节点：${currentTask.value.nodeName || '工单处理'}`;
});

const needProcessResolution = computed(() => {
  return routeParams.value.type === 'approval';
});

// 新增：提交按钮显示控制逻辑
const submitButtonShow = computed(() => {
  return (
    routeParams.value.type === 'add' ||
    (routeParams.value.type === 'update' &&
      workOrder.value.maintStatus &&
      (workOrder.value.maintStatus === 'draft' || workOrder.value.maintStatus === 'cancel' || workOrder.value.maintStatus === 'back'))
  );
});

// 初始化
onMounted(async () => {
  routeParams.value = route.query;
  loading.value = true;
  
  try {
    // 获取工单信息
    await loadWorkOrderInfo();
    
    // 获取当前任务信息
    if (routeParams.value.type === 'approval') {
      await loadCurrentTask();
    }
    
    // 初始化表单数据
    initializeFormData();
    
  } catch (error) {
    console.error('初始化失败:', error);
    proxy?.$modal.msgError('加载数据失败');
  } finally {
    loading.value = false;
  }
});

// 加载工单信息
const loadWorkOrderInfo = async () => {
  const businessId = routeParams.value.id;
  if (!businessId) {
    proxy?.$modal.msgError('缺少工单ID参数');
    return;
  }
  
  const res = await getDmsBillsMaintInstance(businessId);
  workOrder.value = res.data;
  
  // 设置状态显示文本
  if (maint_level.value && workOrder.value.maintStatus !== undefined) {
    const statusItem = maint_level.value.find((item: any) => String(item.value) === String(workOrder.value.maintStatus));
    workOrderStatusText.value = statusItem ? statusItem.label : '未知状态';
    } else {
    workOrderStatusText.value = '未知状态';
  }
};

// 加载当前任务信息
const loadCurrentTask = async () => {
  try {
    const businessId = routeParams.value.id;
    const taskId = routeParams.value.taskId;
    
    // 通过taskId或businessId获取当前任务
    const taskRes = await pageByTaskWait({
      pageNum: 1,
      pageSize: 10,
      flowCode: 'Maint01' // 保养流程代码
    });
    
    const tasks = taskRes.rows.filter(task => 
      task.businessId === businessId || task.id === taskId
    );
    
    if (tasks.length > 0) {
      currentTask.value = tasks[0];
      
      // 动态设置处理意见校验规则
      if (needProcessResolution.value) {
        rules.processHandleResolution = [
          { required: true, message: '处理意见不能为空', trigger: 'blur' }
        ];
      }
    }
  } catch (error) {
    console.error('获取任务信息失败:', error);
  }
};

// 初始化表单数据
const initializeFormData = () => {
  // 基础信息从工单获取
  form.maintInstanceId = workOrder.value.maintInstanceId;
  form.maintLevel = workOrder.value.maintLevel;
  form.maintGroup = workOrder.value.maintGroup;
  form.maintSupervisor = workOrder.value.maintSupervisor;
};

// 新增：提交表单方法
const submitForm = async (status: string) => {
  if (!processFormRef.value) return;
  
  try {
    const valid = await processFormRef.value.validate();
    if (valid) {
      buttonLoading.value = true;
      
      if (status === 'draft') {
        // 暂存逻辑
        await addDmsMaintInstanceActivity({
          maintInstanceId: form.maintInstanceId,
          maintLevel: form.maintLevel,
          maintGroup: form.maintGroup,
          maintSupervisor: form.maintSupervisor,
          processHandleResolution: form.processHandleResolution || '',
          handleTime: getCurrentDateTime()
        });
        
        proxy?.$modal.msgSuccess('暂存成功');
        goBack();
      } else {
        // 提交逻辑
        // 准备任务变量
        taskVariables.value = { 
          entity: {
            maintInstanceId: form.maintInstanceId,
            maintLevel: form.maintLevel,
            maintGroup: form.maintGroup,
            maintSupervisor: form.maintSupervisor,
            processHandleResolution: form.processHandleResolution || ''
          }
        };
        
        // 启动工作流或继续处理
        if (routeParams.value.taskId) {
          submitVerifyRef.value?.openDialog(routeParams.value.taskId);
        } else {
          // 处理新建状态的提交
          proxy?.$modal.msgSuccess('提交成功');
          goBack();
        }
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    proxy?.$modal.msgError('提交失败');
  } finally {
    buttonLoading.value = false;
  }
};

// 审批处理
const approvalVerifyOpen = async () => {
  if (!processFormRef.value) return;
  
  try {
    const valid = await processFormRef.value.validate();
    if (valid) {
      // 准备任务变量
      taskVariables.value = {
        entity: {
          maintInstanceId: form.maintInstanceId,
          maintLevel: form.maintLevel,
          maintGroup: form.maintGroup,
          maintSupervisor: form.maintSupervisor,
          processHandleResolution: form.processHandleResolution || ''
        }
      };
      
      // 直接使用传入的taskId进行审批
      submitVerifyRef.value?.openDialog(routeParams.value.taskId);
    }
  } catch (error) {
    proxy?.$modal.msgError('表单验证失败，请检查输入项');
  }
};

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

// 提交回调
const submitCallback = async () => {
  try {
    // 保存工单实例活动记录
    await addDmsMaintInstanceActivity({
      maintInstanceId: form.maintInstanceId,
      maintLevel: form.maintLevel,
      maintGroup: form.maintGroup,
      maintSupervisor: form.maintSupervisor,
      processHandleResolution: form.processHandleResolution || '',
      handleTime: getCurrentDateTime()
    });
    
    proxy?.$modal.msgSuccess(`${currentStepName.value}完成`);
    
    // 关闭页面返回
    goBack();
  } catch (error) {
    console.error('保存业务数据失败:', error);
    proxy?.$modal.msgError('保存业务数据失败');
  }
};

// 返回
const goBack = () => {
  proxy?.$tab.closePage(proxy?.$route);
  router.go(-1);
};
</script>

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