<template>
  <div class="p-2">
    <el-card shadow="never" style="margin-top: 0">
      <!-- 审批按钮组件 -->
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.projectChangeId"
        :status="form.flowStatus"
        :pageType="routeParams.type"
        :mode="false"
      />
    </el-card>

    <el-card shadow="never" style="margin-top: 0">
      <el-form ref="projectChangeFormRef" :model="form" :disabled="!isFormEditable" :rules="rules" label-width="140px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectId">
              <el-input v-if="showProjectSelect" v-model="form.projectName" placeholder="请选择项目" readonly>
                <template #suffix>
                  <el-icon style="cursor: pointer" @click="openProjectSelect">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-input v-else v-model="form.projectName" disabled placeholder="项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目变更编号" prop="projectChangeCode">
              <el-input v-model="form.projectChangeCode" placeholder="由系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号">
              <el-input v-model="form.projectCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类别">
              <el-select v-model="form.projectCategory" disabled style="width: 100%">
                <el-option v-for="dict in project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理">
              <el-input v-model="form.projectManagerName" disabled placeholder="项目经理" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门负责人">
              <el-input v-model="form.deptHeadName" disabled placeholder="部门负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分管副总">
              <el-input v-model="form.responsibleVpName" disabled placeholder="分管副总" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变更次数">
              <el-input-number v-model="form.changeNumber" disabled :controls="false" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请变更日期" prop="applyChangeDate">
              <el-date-picker
                v-model="form.applyChangeDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择申请变更日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="变更类型" prop="changeType">
              <el-checkbox-group v-model="changeTypeList" :validate-event="false">
                <el-checkbox v-for="dict in change_type" :key="dict.value" :value="dict.value">{{ dict.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">预算变更</el-divider>
        <el-row :gutter="20" class="mb-2">
          <el-col :span="8">
            <el-form-item label="当前合同额">
              <el-input-number v-model="form.contractAmount" :precision="2" :disabled="!isFormEditable" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前合同净额">
              <el-input-number v-model="form.contractNetAmount" :precision="2" :disabled="!isFormEditable" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 预算变更表格：预算行从项目预算中自动带出，不允许新增删除，只能修改变更后预算等字段 -->
        <el-table :data="form.budgetList" border stripe max-height="400">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="科目名称" width="200" align="center">
            <template #default="scope">
              <!-- 科目名称从项目预算带出，只读显示 -->
              <span>{{ scope.row.subjectName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变更前预算" width="150" align="center">
            <template #default="scope">
              <!-- 变更前预算从项目预算带出，只读显示（已在数据加载时转换为数字类型） -->
              <span>{{ scope.row.budgetBefore?.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变更后预算" width="150" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.budgetAfter" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="已使用金额" width="150" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.amountUsed" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="费用调整原因" min-width="200" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.adjustmentReason" placeholder="请输入费用调整原因" />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="left">进度变更（项目里程碑/关键节点）</el-divider>
        <el-table :data="form.progressList" border stripe max-height="400">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="项目阶段" width="120" align="center">
            <template #default="scope">
              <dict-tag :options="project_phases" :value="scope.row.projectPhases" />
            </template>
          </el-table-column>
          <el-table-column label="里程碑名称" width="150" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.milestoneName" placeholder="请输入里程碑名称" />
            </template>
          </el-table-column>
          <el-table-column label="原计划时间起" width="160" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.originalStart" type="date" value-format="YYYY-MM-DD" disabled style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="原计划时间止" width="160" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.originalEnd" type="date" value-format="YYYY-MM-DD" disabled style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="变更后时间起" width="160" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.changedStart" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="变更后时间止" width="160" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.changedEnd" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="完成程度" width="120" align="center">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.completionDegree"
                :min="0"
                :max="100"
                :precision="0"
                controls-position="right"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="left">项目当前情况说明</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="当前情况" prop="currentStatus">
              <el-input v-model="form.currentStatus" type="textarea" :rows="3" placeholder="请输入当前情况" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="变更原因" prop="changeReason">
              <el-input v-model="form.changeReason" type="textarea" :rows="3" placeholder="请输入变更原因" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="后续工作" prop="followUpWork">
              <el-input v-model="form.followUpWork" 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" />
    <!-- 项目选择弹窗 -->
    <ProjectSelect ref="projectSelectRef" :multiple="false" @confirm-call-back="projectInfoSelectCallBack" />
  </div>
</template>

<script setup lang="ts" name="ErpProjectChangeEdit">
import { useRoute, useRouter } from 'vue-router';
import {
  addErpProjectChange,
  getErpProjectChange,
  prepareProjectChangeWithInfo,
  submitProjectChangeAndFlowStart,
  updateErpProjectChange
} from '@/api/oa/erp/erpProjectChange';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import type { ErpProjectChangeForm } from '@/api/oa/erp/erpProjectChange/types';
// import approvalButton from '@/components/Workflow/approvalButton.vue';
// import SubmitVerify from '@/components/Workflow/SubmitVerify.vue';
// import ApprovalRecord from '@/components/Workflow/ApprovalRecord.vue';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import ProjectSelect from '@/components/ProjectSelect/index.vue';
import type { ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';
import { FlowCodeEnum } from '@/enums/OAEnum';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { project_category, change_type, project_phases } = toRefs<any>(proxy?.useDict('project_category', 'change_type', 'project_phases'));
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const refreshFlagKey = 'erpProjectChangeListShouldRefresh';

/** 通知列表页刷新 */
const notifyListRefresh = () => {
  sessionStorage.setItem(refreshFlagKey, Date.now().toString());
};

const projectChangeFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const changeTypeList = ref<string[]>([]);
// 路由参数（与项目信息保持一致）
const routeParams = ref<Record<string, any>>({});
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const taskVariables = ref<Record<string, any>>({});

// 标记是否已经生成过项目变更编号
// 设计思路：
// 1. 新增模式：后端在首次保存或提交流程时生成 projectChangeCode，此时 isCodeGenerated 为 false
// 2. 编辑模式：如果从后端加载到已有的 projectChangeCode，则认为编号已经生成，不允许前端再次生成
// 3. 当前页面暂未提供“生成项目变更编号”按钮，但预留该标志位，未来可用于控制按钮禁用状态
const isCodeGenerated = ref(false);

// 计算属性：判断是否为只读模式（与项目信息保持一致）
const isViewMode = computed(() => routeParams.value.type === 'view' || routeParams.value.type === 'approval');
// 计算属性：判断表单是否可编辑（草稿状态且非查看/审批模式）
const isFormEditable = computed(() => {
  if (isViewMode.value) {
    return false;
  }
  // 只有草稿状态才能编辑
  return form.value.projectChangeStatus === '1';
});

const formatToday = () => (proxy?.parseTime ? proxy.parseTime(new Date(), '{y}-{m}-{d}') : new Date().toISOString().slice(0, 10));

const toDateOnly = (time?: string) => {
  if (!time) {
    return undefined;
  }
  const formatted = proxy?.parseTime ? proxy.parseTime(time, '{y}-{m}-{d}') : new Date(time).toISOString().slice(0, 10);
  return formatted === null ? undefined : formatted;
};

const getDefaultForm = (): ErpProjectChangeForm => ({
  projectChangeId: undefined,
  projectChangeCode: '',
  projectId: undefined,
  projectCode: '',
  projectName: '',
  projectCategory: '',
  changeType: '',
  changeNumber: undefined,
  projectManagerId: undefined,
  projectManagerName: '',
  deptHeadId: undefined,
  deptHeadName: '',
  responsibleVpId: undefined,
  responsibleVpName: '',
  applyChangeDate: formatToday(),
  contractAmount: 0,
  contractNetAmount: 0,
  currentStatus: '',
  changeReason: '',
  followUpWork: '',
  projectChangeStatus: '1',
  flowStatus: 'draft',
  activeFlag: '1',
  budgetList: [],
  progressList: []
});

watch(
  changeTypeList,
  (val) => {
    form.value.changeType = val.join(',');
  },
  { deep: true }
);

const form = ref<ErpProjectChangeForm>({
  ...getDefaultForm()
});

// 添加项目选择功能（仅在新增且无projectId参数时显示）
const projectSelectRef = ref<InstanceType<typeof ProjectSelect>>();
const showProjectSelect = computed(() => {
  return routeParams.value.type === 'add' && !routeParams.value.projectId;
});

/** 打开项目选择弹窗 */
const openProjectSelect = () => {
  projectSelectRef.value?.open();
};

/** 项目选择回调，自动填充项目相关信息 */
const projectInfoSelectCallBack = async (data: ProjectInfoVO[]) => {
  if (data && data.length > 0) {
    const project = data[0];
    form.value.projectId = project.projectId;
    form.value.projectName = project.projectName || '';
    form.value.projectCode = project.projectCode || '';
    // 调用 handleProjectChange 填充其他关联字段
    await handleProjectChange(project.projectId as string | number);
  }
};

// 项目选择变化时自动带出项目信息
const handleProjectChange = async (projectId: string | number) => {
  if (!projectId) return;

  try {
    const res = await prepareProjectChangeWithInfo(projectId);
    if (res.code === 200) {
      // 保留已填写的变更信息，只更新项目相关信息
      // 注意：budgetList 和 progressList 应从后端获取，不应保留前端空数组
      const changeData = {
        changeType: form.value.changeType,
        currentStatus: form.value.currentStatus,
        changeReason: form.value.changeReason,
        followUpWork: form.value.followUpWork
      };

      Object.assign(form.value, res.data, changeData);
      // 确保使用后端返回的预算和进度列表，并转换数字类型字段
      form.value.budgetList = (res.data.budgetList ?? []).map((item: any) => ({
        ...item,
        budgetBefore: Number(item.budgetBefore || 0),
        budgetAfter: Number(item.budgetAfter || 0),
        amountUsed: Number(item.amountUsed || 0)
      }));
      form.value.progressList = (res.data.progressList ?? []).map((item: any) => ({
        ...item,
        completionDegree: Number(item.completionDegree || 0)
      }));

      // 处理变更类型（多选）
      if (form.value.changeType) {
        changeTypeList.value = form.value.changeType.split(',');
      }
    }
  } catch (error) {
    console.error('加载项目信息失败:', error);
    ElMessage.error('加载项目信息失败');
  }
};

const resetFormState = async () => {
  form.value = { ...getDefaultForm() };
  changeTypeList.value = [];
  // 重置为“未生成编号”状态，防止上一次编辑的值残留
  isCodeGenerated.value = false;
  await nextTick();
  projectChangeFormRef.value?.clearValidate?.();
};

const rules = reactive({
  projectId: [{ required: true, message: '项目不能为空', trigger: 'change' }],
  applyChangeDate: [{ required: true, message: '申请变更时间不能为空', trigger: 'change' }],
  changeType: [{ required: true, message: '变更类型不能为空', trigger: 'change' }]
});

const loadProjectDataByProjectId = async (projectId: string | number) => {
  if (!projectId) return;

  try {
    const res = await prepareProjectChangeWithInfo(projectId);
    if (res.data) {
      Object.assign(form.value, res.data);
      const dateOnly = toDateOnly(form.value.applyChangeDate);
      form.value.applyChangeDate = dateOnly ?? formatToday();
      // 转换数字类型字段，确保el-input-number组件正常工作
      form.value.budgetList = (res.data.budgetList ?? []).map((item: any) => ({
        ...item,
        budgetBefore: Number(item.budgetBefore || 0),
        budgetAfter: Number(item.budgetAfter || 0),
        amountUsed: Number(item.amountUsed || 0)
      }));
      form.value.progressList = (res.data.progressList ?? []).map((item: any) => ({
        ...item,
        completionDegree: Number(item.completionDegree || 0)
      }));
      // 处理变更类型多选
      if (form.value.changeType) {
        changeTypeList.value = form.value.changeType.split(',');
      }
    }
  } catch (error) {
    proxy?.$modal.msgError('加载项目信息失败');
    console.error(error);
  }
};

// 预算行不允许新增删除，数据从项目预算中自动带出
// handleAddBudget 和 handleDeleteBudget 方法已移除

/** 提交按钮（与项目信息保持一致的处理方式） */
const submitForm = (status: string, mode: boolean) => {
  projectChangeFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    buttonLoading.value = true;

    try {
      // 权限校验：只有项目经理才能提交（超级管理员跳过校验）
      if (!form.value.projectManagerId) {
        proxy?.$modal.msgError('请先选择项目');
        buttonLoading.value = false;
        return;
      }
      const isSuperAdmin = userStore.roles.includes('admin') || userStore.roles.includes('superadmin');
      if (!isSuperAdmin && status === 'submit' && userStore.userId !== form.value.projectManagerId) {
        proxy?.$modal.msgError('只有项目经理才能提交项目变更申请');
        buttonLoading.value = false;
        return;
      }

      form.value.changeType = changeTypeList.value.join(',');

      // 提交审批（与项目信息保持一致）
      if (status !== 'draft') {
        form.value.flowCode = FlowCodeEnum.PROJECT_PLAN_CHANGE_CODE; //OAEP
        form.value.variables = {
          projectId: form.value.projectId,
          projectName: form.value.projectName,
          projectCode: form.value.projectCode,
          projectManagerId: form.value.projectManagerId,
          deptHeadId: form.value.deptHeadId,
          changeType: form.value.changeType,
          projectChangeCode: form.value.projectChangeCode
        };
        // 流程实例业务扩展字段
        form.value.bizExt = {
          businessTitle: form.value.projectName,
          businessCode: form.value.projectChangeCode
        };
        form.value.projectChangeStatus = '2';
        form.value.flowStatus = 'waiting';
        await submitProjectChangeAndFlowStart(form.value);
        proxy?.$modal.msgSuccess('操作成功');
        notifyListRefresh();
        proxy?.$tab.closePage();
        router.go(-1);
      } else {
        // 暂存
        form.value.projectChangeStatus = '1';
        form.value.flowStatus = 'draft';
        if (form.value.projectChangeId) {
          await updateErpProjectChange(form.value);
        } else {
          await addErpProjectChange(form.value);
        }
        proxy?.$modal.msgSuccess('暂存成功');
        notifyListRefresh();
        proxy?.$tab.closePage();
        router.go(-1);
      }
    } finally {
      buttonLoading.value = false;
    }
  });
};

const approvalVerifyOpen = async () => {
  const taskId = routeParams.value.taskId as string | undefined;
  await submitVerifyRef.value?.openDialog(taskId);
};

const handleApprovalRecord = () => {
  if (form.value.projectChangeId) {
    approvalRecordRef.value?.init(form.value.projectChangeId);
  }
};

const submitCallback = async () => {
  // 审批完成后的回调也保持与提交/暂存一致：退出当前编辑页
  proxy?.$tab.closePage();
  router.go(-1);
};

// 加载锁，防止 onMounted 和 route watch 竞态导致数据被清空
const isDataLoading = ref(false);

const loadFormData = async () => {
  // 防止并发加载：若上一次加载仍在进行中，直接跳过本次调用
  if (isDataLoading.value) return;
  isDataLoading.value = true;

  try {
    await resetFormState();
    // 获取路由参数（与项目信息保持一致）
    routeParams.value = route.query;
    buttonLoading.value = false;

    const id = routeParams.value.id as string;
    const projectId = routeParams.value.projectId as string;

    // 判断是否为查看/审批/编辑模式（与项目信息保持一致）
    if (id && id !== '0' && (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval')) {
      try {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const res = await getErpProjectChange(id);
        if (res.data) {
          Object.assign(form.value, res.data);
          const dateOnly = toDateOnly(form.value.applyChangeDate);
          form.value.applyChangeDate = dateOnly ?? formatToday();
          form.value.budgetList = (res.data.budgetList ?? []).map((item: any) => ({
            ...item,
            budgetBefore: Number(item.budgetBefore || 0),
            budgetAfter: Number(item.budgetAfter || 0),
            amountUsed: Number(item.amountUsed || 0)
          }));
          form.value.progressList = (res.data.progressList ?? []).map((item: any) => ({
            ...item,
            completionDegree: Number(item.completionDegree || 0)
          }));
          isCodeGenerated.value = !!form.value.projectChangeCode;
          if (res.data.changeType) {
            changeTypeList.value = res.data.changeType.split(',');
          }
        }
        proxy?.$modal.closeLoading();
      } catch (error) {
        proxy?.$modal.closeLoading();
        proxy?.$modal.msgError('加载变更申请数据失败');
        console.error(error);
      }
    } else if (projectId) {
      // 新增模式：根据项目ID加载项目计划信息
      await loadProjectDataByProjectId(projectId);
    } else if (!showProjectSelect.value) {
      proxy?.$modal.msgError('缺少必要的参数：项目ID或变更申请ID');
    }
  } finally {
    isDataLoading.value = false;
  }
};

watch(
  () => route.fullPath,
  () => {
    // 只有当路由还在当前编辑页时才重新加载数据，避免跳转到其他页面时触发报错
    if (route.path.includes('erpProjectChange/edit')) {
      loadFormData();
    }
  }
);

onMounted(async () => {
  await loadFormData();
});
</script>

<style scoped lang="scss">
.card-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}
</style>
