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

    <el-card shadow="never" style="margin-top: 0">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货确认编号" prop="receivingCode">
              <el-input v-model="form.receivingCode" placeholder="由系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请选择项目" readonly :disabled="routeParams.type !== 'add'">
                <template #suffix>
                  <el-icon v-if="routeParams.type === 'add'" style="cursor: pointer" @click="openProjectSelect">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="managerId">
              <el-input v-model="form.projectManagerName" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="到货日期" prop="arrivalDate">
              <el-date-picker
                v-model="form.arrivalDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择到货日期"
                :disabled="formDisabled"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否全部到货" prop="isAllReceiving">
              <el-radio-group v-model="form.isAllReceiving" :disabled="formDisabled">
                <el-radio v-for="dict in is_all_receiving" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货单附件" prop="ossId">
              <FileUpload
                v-model="ossIdString"
                :limit="5"
                :fileSize="20"
                :fileType="['doc', 'docx', 'pdf', 'xls', 'xlsx', 'png', 'jpg', 'jpeg']"
                :disabled="formDisabled"
                :isShowTip="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门负责人" prop="chargeId">
              <el-input v-model="form.chargeName" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分管副总" prop="deputyId">
              <el-input v-model="form.deputyName" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="确认该项目达到客户收货节点，可以进行发货款收取（如设计）。"
                :disabled="formDisabled"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <ApprovalRecord ref="approvalRecordRef" />
    <SubmitVerify ref="submitVerifyRef" @submit-callback="submitCallback" />
    <!-- 项目选择弹窗 -->
    <ProjectSelect ref="projectSelectRef" :multiple="false" @confirm-call-back="projectInfoSelectCallBack" />
  </div>
</template>

<script setup lang="ts" name="ProjectReceivingEdit">
import ApprovalButton from '@/components/Process/approvalButton.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import FileUpload from '@/components/FileUpload/index.vue';
import ProjectSelect from '@/components/ProjectSelect/index.vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import type { ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';
import {
  addProjectReceiving,
  getProjectReceiving,
  prepareProjectReceivingByProjectId,
  submitProjectReceivingAndFlowStart,
  updateProjectReceiving
} from '@/api/oa/erp/projectReceiving';
import type { ProjectReceivingForm } from '@/api/oa/erp/projectReceiving/types';
import { FlowCodeEnum } from '@/enums/OAEnum';
import SubmitVerify from '@/components/Process/submitVerify.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

const { wf_business_status, receiving_status, is_all_receiving } = toRefs<any>(
  proxy?.useDict('wf_business_status', 'receiving_status', 'is_all_receiving')
);

// 路由参数（与项目信息保持一致）
const routeParams = ref<Record<string, any>>({});

const userStore = useUserStore();
const refreshFlagKey = 'projectReceivingListShouldRefresh';

/** 通知列表页刷新 */
const notifyListRefresh = () => {
  sessionStorage.setItem(refreshFlagKey, Date.now().toString());
};
const isSuperAdmin = computed(() => {
  const roles = userStore.roles || [];
  return roles.includes('admin') || roles.includes('superadmin');
});

const buttonLoading = ref(false);
const formRef = ref<ElFormInstance>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();

const projectSelectRef = ref<InstanceType<typeof ProjectSelect>>();

const initFormData: ProjectReceivingForm = {
  receivingId: undefined,
  projectId: undefined,
  projectCode: undefined,
  projectName: undefined,
  managerId: undefined,
  projectManagerName: undefined,
  arrivalDate: undefined,
  ossId: undefined,
  chargeId: undefined,
  chargeName: undefined as any,
  deputyId: undefined,
  deputyName: undefined as any,
  remark: undefined,
  isAllReceiving: undefined,
  receivingStatus: '1',
  flowStatus: 'draft' as any,
  flowCode: FlowCodeEnum.PROJECT_RECEIVING_CODE,
  variables: {},
  bizExt: {}
};

const form = ref<ProjectReceivingForm>({ ...initFormData });

const rules = {
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  projectCode: [{ required: true, message: '项目号不能为空', trigger: 'blur' }],
  arrivalDate: [{ required: true, message: '到货日期不能为空', trigger: 'change' }]
} as any;

const ossIdString = computed({
  get() {
    const v = form.value.ossId as any;
    return v === undefined || v === null ? '' : String(v);
  },
  set(val: string) {
    form.value.ossId = val || (undefined as any);
  }
});

/** 打开项目选择弹窗 */
const openProjectSelect = () => {
  if (routeParams.value.type !== 'add') return;
  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 || '';
    // 调用 onProjectChange 填充其他关联字段
    await onProjectChange(project.projectId);
  }
};

const setNowIfAdd = () => {
  const d = new Date();
  const s = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
  form.value.arrivalDate = s as any;
};

const onProjectChange = async (val: any) => {
  if (!val) return;
  const { data } = await prepareProjectReceivingByProjectId(val);
  Object.assign(form.value, data);
  form.value.projectId = val as any;
  applyLeaderFromManager();
};

const applyLeaderFromManager = () => {};

const loadDetail = async () => {
  if (!routeParams.value.id) return;
  const res = await getProjectReceiving(routeParams.value.id);
  console.log('[projectReceiving] 后端返回数据:', res.data);
  console.log('[projectReceiving] 后端返回ossId:', res.data?.ossId);
  Object.assign(form.value, res.data);
  console.log('[projectReceiving] 赋值后form.ossId:', form.value.ossId);
  console.log('[projectReceiving] ossIdString计算属性值:', ossIdString.value);
};

const submitForm = (status: string, mode: boolean) => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    // 前端权限校验：只有项目经理才能暂存或提交（超级管理员除外）
    if (!form.value.managerId) {
      proxy?.$modal.msgError('请先选择项目');
      buttonLoading.value = false;
      return;
    }
    if (!isSuperAdmin.value && userStore.userId !== form.value.managerId) {
      proxy?.$modal.msgError('只有项目经理才能提交或暂存项目收货确认');
      buttonLoading.value = false;
      return;
    }
    buttonLoading.value = true;
    try {
      // 提交审批（与项目信息保持一致）
      if (status !== 'draft') {
        // 提交流程：设置业务状态为审批中，流程状态为 waiting
        form.value.receivingStatus = '2';
        form.value.flowStatus = 'waiting' as any;
        form.value.flowCode = FlowCodeEnum.PROJECT_RECEIVING_CODE; //OAPR
        form.value.variables = {
          projectId: form.value.projectId,
          projectCode: form.value.projectCode,
          projectName: form.value.projectName,
          managerId: form.value.managerId,
          managerName: form.value.projectManagerName,
          chargeId: form.value.chargeId,
          deputyId: form.value.deputyId
        };
        form.value.bizExt = {
          businessCode: form.value.receivingCode,
          businessTitle: form.value.projectName
        };
        await submitProjectReceivingAndFlowStart(form.value);
        proxy?.$modal.msgSuccess('操作成功');
        notifyListRefresh();
        proxy?.$tab.closePage();
        router.go(-1);
      } else {
        // 暂存：显式设置流程状态为 draft
        form.value.flowStatus = 'draft' as any;
        form.value.receivingStatus = '1'; // 业务状态：暂存

        if (form.value.receivingId) {
          await updateProjectReceiving(form.value);
        } else {
          await addProjectReceiving(form.value);
        }
        proxy?.$modal.msgSuccess('暂存成功');
        notifyListRefresh();
        proxy?.$tab.closePage();
        router.go(-1);
      }
    } finally {
      buttonLoading.value = false;
    }
  });
};

const submitCallback = async () => {
  await proxy?.$tab.closePage(route);
  router.go(-1);
};

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

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

// 表单禁用逻辑（与项目信息保持一致，且只有草稿状态可编辑）
const formDisabled = computed(() => {
  if (routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
    return true;
  }
  // 仅草稿状态（receivingStatus === '1'）允许编辑，其余状态只读
  if (!form.value.receivingStatus) {
    return false;
  }
  return form.value.receivingStatus !== '1';
});

const loadFormData = async () => {
  // 获取路由参数（与项目信息保持一致）
  routeParams.value = route.query;
  // 重置表单
  form.value = { ...initFormData };

  await loadDetail();

  if (routeParams.value.type === 'add') {
    setNowIfAdd();
    // 如果传递了projectId参数，自动加载项目信息
    const projectId = routeParams.value.projectId;
    if (projectId) {
      await onProjectChange(projectId);
    }
  }
};

watch(
  () => route.fullPath,
  () => {
    loadFormData();
  }
);

onMounted(async () => {
  proxy?.$modal.loading('正在加载数据，请稍后...');
  try {
    await loadFormData();
  } finally {
    proxy?.$modal.closeLoading();
  }
});
</script>

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