<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
            <el-form-item label="分配单编号" prop="allocCode">
              <el-input v-model="queryParams.allocCode" placeholder="请输入分配单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="月份" prop="monthCode">
              <el-date-picker
                v-model="queryParams.monthCode"
                type="month"
                value-format="YYYYMM"
                format="YYYY-MM"
                clearable
                placeholder="请选择月份"
                @change="handleQueryMonthChange"
              />
            </el-form-item>
            <el-form-item label="预投项目" prop="projectId">
              <el-select v-model="queryParams.projectId" filterable clearable placeholder="请选择预投项目" class="project-select">
                <el-option
                  v-for="project in querySourceProjectOptions"
                  :key="project.projectId"
                  :label="projectLabel(project)"
                  :value="project.projectId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="分配状态" prop="allocStatus">
              <el-select v-model="queryParams.allocStatus" placeholder="请选择分配状态" clearable>
                <el-option v-for="dict in alloc_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/erp:timesheetPreAlloc:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:timesheetPreAlloc:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['oa/erp:timesheetPreAlloc:remove']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:timesheetPreAlloc:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="timesheetPreAllocList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分配单编号" align="center" prop="allocCode" width="180" v-if="columns[0].visible" />
        <el-table-column label="月份" align="center" prop="monthCode" width="100" v-if="columns[1].visible" />
        <el-table-column label="来源预投项目" align="center" min-width="260" v-if="columns[2].visible">
          <template #default="scope">
            <div class="project-cell">
              <span>{{ scope.row.projectCode }}</span>
              <span>{{ scope.row.projectName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="来源工时" align="center" prop="sourceTotalHours" width="110" v-if="columns[3].visible">
          <template #default="scope">{{ formatHours(scope.row.sourceTotalHours) }}</template>
        </el-table-column>
        <el-table-column label="已分配工时" align="center" prop="allocatedTotalHours" width="120" v-if="columns[4].visible">
          <template #default="scope">{{ formatHours(scope.row.allocatedTotalHours) }}</template>
        </el-table-column>
        <el-table-column label="涉及人数" align="center" prop="staffCount" width="100" v-if="columns[5].visible" />
        <el-table-column label="分配状态" align="center" prop="allocStatus" width="110" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="alloc_status" :value="scope.row.allocStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="160" show-overflow-tooltip v-if="columns[7].visible" />
        <el-table-column label="操作" align="center" fixed="right" width="110" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:timesheetPreAlloc:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/erp:timesheetPreAlloc:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="960px" append-to-body>
      <el-form ref="timesheetPreAllocFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="月份" prop="monthCode">
              <el-date-picker
                v-model="form.monthCode"
                type="month"
                value-format="YYYYMM"
                format="YYYY-MM"
                clearable
                :disabled="Boolean(form.allocId)"
                placeholder="请选择月份"
                @change="handleMonthChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="预投项目" prop="projectId">
              <el-select
                v-model="form.projectId"
                filterable
                clearable
                :disabled="Boolean(form.allocId)"
                placeholder="请选择来源预投项目"
                class="full-width"
                @change="loadAllocDetails"
              >
                <el-option
                  v-for="project in sourceProjectOptions"
                  :key="project.projectId"
                  :label="projectLabel(project)"
                  :value="project.projectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <dict-tag :options="alloc_status" :value="currentAllocStatus" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="summary-strip">
          <div class="summary-item">
            <span>来源预投工时</span>
            <strong>{{ formatHours(sourceTotalHours) }}</strong>
          </div>
          <div class="summary-item">
            <span>已分配工时</span>
            <strong>{{ formatHours(allocatedTotalHours) }}</strong>
          </div>
          <div class="summary-item">
            <span>未分配工时</span>
            <strong :class="{ 'hour-warn': remainingTotalHours < 0 }">{{ formatHours(remainingTotalHours) }}</strong>
          </div>
          <div class="summary-item">
            <span>涉及人数</span>
            <strong>{{ staffCount }}</strong>
          </div>
        </div>

        <div v-loading="detailLoading" class="alloc-section">
          <div class="target-toolbar">
            <span>分配去向</span>
            <el-button type="primary" link icon="Plus" @click="addTarget">添加去向</el-button>
          </div>
          <el-table border :data="form.allocItems || []" class="alloc-table" empty-text="请选择月份和预投项目后添加去向">
            <el-table-column label="目标物流/备件项目" min-width="420">
              <template #default="scope">
                <el-select v-model="scope.row.targetProjectId" filterable placeholder="请选择目标项目" class="full-width">
                  <el-option
                    v-for="project in targetProjectOptions"
                    :key="project.projectId"
                    :label="projectLabel(project)"
                    :value="project.projectId"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="分配工时" align="center" width="180">
              <template #default="scope">
                <el-input-number v-model="scope.row.allocHours" :precision="2" :step="0.5" :min="0" controls-position="right" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80">
              <template #default="scope">
                <el-button link type="danger" icon="Delete" @click="removeTarget(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item label="备注" prop="remark" class="mt-4">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TimesheetPreAlloc" lang="ts">
import {
  listTimesheetPreAlloc,
  getTimesheetPreAlloc,
  delTimesheetPreAlloc,
  addTimesheetPreAlloc,
  updateTimesheetPreAlloc,
  getAllocDetails,
  listAvailableSourceProjects
} from '@/api/oa/erp/timesheetPreAlloc';
import {
  TimesheetPreAllocVO,
  TimesheetPreAllocQuery,
  TimesheetPreAllocForm,
  PreAllocTarget,
  PreAllocDetailVO
} from '@/api/oa/erp/timesheetPreAlloc/types';
import { getErpProjectInfoList } from '@/api/oa/erp/projectInfo';

interface ProjectOption {
  projectId: string;
  projectCode?: string;
  projectName?: string;
  projectCategory?: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { alloc_status } = toRefs<any>(proxy?.useDict('alloc_status'));

const timesheetPreAllocList = ref<TimesheetPreAllocVO[]>([]);
const selectedRows = ref<TimesheetPreAllocVO[]>([]);
const querySourceProjectOptions = ref<ProjectOption[]>([]);
const sourceProjectOptions = ref<ProjectOption[]>([]);
const targetProjectOptions = ref<ProjectOption[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const detailLoading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const timesheetPreAllocFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const columns = ref<FieldOption[]>([
  { key: 0, label: `分配单编号`, visible: true },
  { key: 1, label: `月份`, visible: true },
  { key: 2, label: `来源预投项目`, visible: true },
  { key: 3, label: `来源工时`, visible: true },
  { key: 4, label: `已分配工时`, visible: true },
  { key: 5, label: `涉及人数`, visible: true },
  { key: 6, label: `分配状态`, visible: true },
  { key: 7, label: `备注`, visible: true }
]);

const getCurrentMonthCode = () => {
  const now = new Date();
  return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`;
};

const initFormData = (): TimesheetPreAllocForm => ({
  allocId: undefined,
  monthCode: getCurrentMonthCode(),
  projectId: undefined,
  sourceTotalHours: 0,
  allocatedTotalHours: 0,
  staffCount: 0,
  allocStatus: '0',
  remark: undefined,
  allocItems: []
});

const data = reactive<PageData<TimesheetPreAllocForm, TimesheetPreAllocQuery>>({
  form: initFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    allocCode: undefined,
    monthCode: undefined,
    projectId: undefined,
    allocStatus: undefined,
    params: {}
  },
  rules: {
    monthCode: [{ required: true, message: '月份不能为空', trigger: 'change' }],
    projectId: [{ required: true, message: '来源预投项目不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const normalizeProject = (project: any): ProjectOption => ({
  projectId: String(project.projectId),
  projectCode: project.projectCode,
  projectName: project.projectName,
  projectCategory: project.projectCategory
});

const projectLabel = (project: ProjectOption) => {
  const code = project.projectCode || '';
  const name = project.projectName || '';
  return code ? `${code} ${name}` : name;
};

const toNumber = (value?: number | string | null) => {
  const num = Number(value ?? 0);
  return Number.isFinite(num) ? num : 0;
};

const formatHours = (value?: number | string | null) => toNumber(value).toFixed(2);

const normalizeTarget = (item: PreAllocTarget): PreAllocTarget => ({
  targetProjectId: item.targetProjectId ? String(item.targetProjectId) : undefined,
  targetProjectCode: item.targetProjectCode,
  targetProjectName: item.targetProjectName,
  allocHours: toNumber(item.allocHours)
});

const sourceTotalHours = computed(() => toNumber(form.value.sourceTotalHours));
const allocatedTotalHours = computed(() => (form.value.allocItems || []).reduce((sum, item) => sum + toNumber(item.allocHours), 0));
const remainingTotalHours = computed(() => sourceTotalHours.value - allocatedTotalHours.value);
const staffCount = computed(() => toNumber(form.value.staffCount));
const currentAllocStatus = computed(() => {
  if (allocatedTotalHours.value <= 0) {
    return '0';
  }
  return allocatedTotalHours.value < sourceTotalHours.value ? '1' : '2';
});

const loadTargetProjectOptions = async () => {
  if (targetProjectOptions.value.length > 0) {
    return;
  }
  const [logisticsRes, spareRes]: any[] = await Promise.all([
    getErpProjectInfoList({ projectCategory: '1' }),
    getErpProjectInfoList({ projectCategory: '2' })
  ]);
  const merged = [...(logisticsRes.data || []), ...(spareRes.data || [])].map(normalizeProject);
  const uniqueMap = new Map<string, ProjectOption>();
  merged.forEach((project) => uniqueMap.set(project.projectId, project));
  targetProjectOptions.value = Array.from(uniqueMap.values());
};

const loadAllPreProjectOptions = async () => {
  const res: any = await getErpProjectInfoList({ projectCategory: '4' });
  querySourceProjectOptions.value = (res.data || []).map(normalizeProject);
};

const loadQuerySourceProjectOptions = async (monthCode?: string) => {
  if (!monthCode) {
    await loadAllPreProjectOptions();
    return;
  }
  const res: any = await listAvailableSourceProjects({ monthCode });
  querySourceProjectOptions.value = (res.data || []).map(normalizeProject);
};

const loadSourceProjectOptions = async (monthCode?: string) => {
  if (!monthCode) {
    sourceProjectOptions.value = [];
    return;
  }
  const res: any = await listAvailableSourceProjects({ monthCode });
  sourceProjectOptions.value = (res.data || []).map(normalizeProject);
};

const appendMissingTargetOptions = (items: PreAllocTarget[]) => {
  items.forEach((item) => {
    const targetProjectId = item.targetProjectId ? String(item.targetProjectId) : undefined;
    if (targetProjectId && !targetProjectOptions.value.some((project) => project.projectId === targetProjectId)) {
      targetProjectOptions.value.push({
        projectId: targetProjectId,
        projectCode: item.targetProjectCode,
        projectName: item.targetProjectName
      });
    }
  });
};

const applyDetailToForm = (detail: PreAllocDetailVO) => {
  const sourceProjectId = detail.projectId ? String(detail.projectId) : undefined;
  if (sourceProjectId && !sourceProjectOptions.value.some((project) => project.projectId === sourceProjectId)) {
    sourceProjectOptions.value.push({
      projectId: sourceProjectId,
      projectCode: detail.projectCode,
      projectName: detail.projectName,
      projectCategory: '4'
    });
  }

  const allocItems = (detail.allocItems || []).map(normalizeTarget);
  appendMissingTargetOptions(allocItems);

  form.value.allocId = detail.allocId;
  form.value.allocCode = detail.allocCode;
  form.value.monthCode = detail.monthCode;
  form.value.standardMonthId = detail.standardMonthId;
  form.value.projectId = sourceProjectId;
  form.value.projectCode = detail.projectCode;
  form.value.projectName = detail.projectName;
  form.value.sourceTotalHours = toNumber(detail.sourceTotalHours);
  form.value.allocatedTotalHours = toNumber(detail.allocatedTotalHours);
  form.value.staffCount = detail.staffCount;
  form.value.allocStatus = detail.allocStatus;
  form.value.remark = detail.remark;
  form.value.allocItems = allocItems;
};

const resetSourceTotals = () => {
  form.value.sourceTotalHours = 0;
  form.value.allocatedTotalHours = 0;
  form.value.staffCount = 0;
  form.value.allocStatus = '0';
  form.value.allocItems = [];
};

const loadAllocDetails = async () => {
  if (!form.value.monthCode || !form.value.projectId) {
    resetSourceTotals();
    return;
  }
  detailLoading.value = true;
  try {
    const res: any = await getAllocDetails({
      monthCode: form.value.monthCode,
      projectId: form.value.projectId
    });
    applyDetailToForm(res.data);
  } finally {
    detailLoading.value = false;
  }
};

const handleMonthChange = async () => {
  form.value.projectId = undefined;
  form.value.projectCode = undefined;
  form.value.projectName = undefined;
  resetSourceTotals();
  await loadSourceProjectOptions(form.value.monthCode);
};

const handleQueryMonthChange = async () => {
  queryParams.value.projectId = undefined;
  await loadQuerySourceProjectOptions(queryParams.value.monthCode);
};

const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams.value,
      projectId: queryParams.value.projectId || undefined
    };
    const res: any = await listTimesheetPreAlloc(params);
    timesheetPreAllocList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = initFormData();
  timesheetPreAllocFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = async () => {
  queryFormRef.value?.resetFields();
  await loadQuerySourceProjectOptions();
  handleQuery();
};

const handleSelectionChange = (selection: TimesheetPreAllocVO[]) => {
  selectedRows.value = selection;
  ids.value = selection.map((item) => item.allocId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = async () => {
  reset();
  await loadTargetProjectOptions();
  await loadSourceProjectOptions(form.value.monthCode);
  dialog.visible = true;
  dialog.title = '预投工时分配';
};

const handleUpdate = async (row?: TimesheetPreAllocVO) => {
  reset();
  await loadTargetProjectOptions();
  const allocId = row?.allocId || ids.value[0];
  const res: any = await getTimesheetPreAlloc(allocId);
  await loadSourceProjectOptions(res.data?.monthCode);
  applyDetailToForm(res.data);
  dialog.visible = true;
  dialog.title = '预投工时分配';
};

const addTarget = () => {
  if (!form.value.allocItems) {
    form.value.allocItems = [];
  }
  form.value.allocItems.push({ targetProjectId: undefined, allocHours: 0 });
};

const removeTarget = (index: number) => {
  form.value.allocItems?.splice(index, 1);
};

const validateAllocation = () => {
  if (sourceTotalHours.value <= 0) {
    proxy?.$modal.msgError('本月该预投项目没有可分配工时');
    return false;
  }
  const usedTargets = new Set<string>();
  for (const item of form.value.allocItems || []) {
    if (!item.targetProjectId) {
      proxy?.$modal.msgError('存在未选择目标项目的分配行');
      return false;
    }
    const targetProjectId = String(item.targetProjectId);
    if (usedTargets.has(targetProjectId)) {
      proxy?.$modal.msgError('同一张分配单不能重复选择同一目标项目');
      return false;
    }
    usedTargets.add(targetProjectId);
    if (toNumber(item.allocHours) <= 0) {
      proxy?.$modal.msgError('分配工时必须大于0');
      return false;
    }
  }
  if (allocatedTotalHours.value - sourceTotalHours.value > 0.000001) {
    proxy?.$modal.msgError('分配工时合计不能超过来源预投工时');
    return false;
  }
  return true;
};

const buildSubmitPayload = (): TimesheetPreAllocForm => ({
  allocId: form.value.allocId,
  monthCode: form.value.monthCode,
  projectId: form.value.projectId,
  sourceTotalHours: sourceTotalHours.value,
  allocatedTotalHours: allocatedTotalHours.value,
  staffCount: staffCount.value,
  allocStatus: currentAllocStatus.value,
  remark: form.value.remark,
  allocItems: (form.value.allocItems || []).map((item) => ({
    targetProjectId: item.targetProjectId,
    allocHours: toNumber(item.allocHours)
  }))
});

const submitForm = () => {
  timesheetPreAllocFormRef.value?.validate(async (valid: boolean) => {
    if (!valid || !validateAllocation()) {
      return;
    }
    buttonLoading.value = true;
    const payload = buildSubmitPayload();
    try {
      if (payload.allocId) {
        await updateTimesheetPreAlloc(payload);
      } else {
        await addTimesheetPreAlloc(payload);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: TimesheetPreAllocVO) => {
  const allocIds = row?.allocId || ids.value;
  await proxy?.$modal.confirm(`是否确认删除预投工时分配编号为"${allocIds}"的数据项？`).finally(() => (loading.value = false));
  await delTimesheetPreAlloc(allocIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    'oa/erp/timesheetPreAlloc/export',
    {
      ...queryParams.value,
      // 如果选中了数据，则只导出选中的数据
      allocIds: ids.value.length > 0 ? ids.value.join(',') : undefined
    },
    `timesheetPreAlloc_${new Date().getTime()}.xlsx`
  );
};

onMounted(async () => {
  await Promise.all([loadTargetProjectOptions(), loadQuerySourceProjectOptions()]);
  await getList();
});
</script>

<style scoped>
.project-select {
  width: 260px;
}

.full-width {
  width: 100%;
}

.project-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
  line-height: 1.35;
}

.summary-strip {
  display: grid;
  grid-template-columns: repeat(4, minmax(120px, 1fr));
  gap: 10px;
  margin: 4px 0 12px;
}

.summary-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 36px;
  padding: 6px 10px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  background: var(--el-fill-color-lighter);
}

.summary-item span {
  color: var(--el-text-color-secondary);
}

.summary-item strong {
  font-size: 16px;
}

.alloc-section {
  min-height: 120px;
}

.target-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-weight: 600;
}

.alloc-table {
  width: 100%;
}

.hour-warn {
  color: var(--el-color-danger);
  font-weight: 600;
}

@media (max-width: 900px) {
  .summary-strip {
    grid-template-columns: repeat(2, minmax(120px, 1fr));
  }
}
</style>
