<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="100px">
            <el-form-item label="人员" prop="userId">
              <el-select v-model="queryParams.userId" placeholder="请选择填报人" clearable filterable style="width: 200px">
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="queryParams.deptId" placeholder="请选择部门" clearable filterable style="width: 200px">
                <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="起始时间" prop="startTime">-->
            <!--              <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择起始时间" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="结束时间" prop="endTime">-->
            <!--              <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间" />-->
            <!--            </el-form-item>-->
            <el-form-item label="工时填报状态" prop="timesheetStatus">
              <el-select v-model="queryParams.timesheetStatus" placeholder="请选择工时填报状态" clearable>
                <el-option v-for="dict in timesheet_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:timesheetInfo: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:timesheetInfo: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:timesheetInfo:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:timesheetInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="DocumentAdd" @click="handleGenerateSummary" v-hasPermi="['oa/erp:timesheetSummary:add']"
              >生成月汇总工时</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="timesheetInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工时填报ID" align="center" prop="timesheetId" v-if="columns[0].visible" />
        <el-table-column label="工时填报编号" align="center" prop="timesheetCode" width="140" v-if="columns[2].visible" />
        <el-table-column label="人员" align="center" prop="nickName" v-if="columns[11].visible" />
        <el-table-column label="人员部门" align="center" prop="deptName" v-if="columns[12].visible" />
        <el-table-column label="人员ID" align="center" prop="userId" v-if="columns[3].visible" />
        <el-table-column label="部门ID" align="center" prop="deptId" v-if="columns[4].visible" />
        <el-table-column label="起始时间" align="center" prop="startTime" width="100" v-if="columns[5].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="100" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总工时" align="center" prop="totalHours" width="80" v-if="columns[7].visible" />
        <el-table-column label="部门工时" align="center" prop="deptHours" width="80" v-if="columns[8].visible" />
        <el-table-column label="项目工时" align="center" prop="projectHours" width="80" v-if="columns[9].visible" />
        <el-table-column label="工时填报状态" align="center" prop="timesheetStatus" v-if="columns[10].visible">
          <template #default="scope">
            <dict-tag :options="timesheet_status" :value="scope.row.timesheetStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[11].visible">
          <template #default="scope">
            <dict-tag :options="flow_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[12].visible" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.flowStatus === 'draft' || scope.row.flowStatus === 'back'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:timesheetInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.flowStatus !== 'draft'">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </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="generateDialog.title" v-model="generateDialog.visible" width="1000px" append-to-body>
      <el-form ref="generateFormRef" :model="generateForm" :rules="generateRules" label-width="100px" inline>
        <el-form-item label="汇总月份" prop="monthCode">
          <el-date-picker v-model="generateForm.monthCode" type="month" value-format="YYYYMM" placeholder="选择月份" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-select v-model="generateForm.deptId" placeholder="请选择部门" filterable>
            <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleGeneratePreview" :loading="generateLoading">汇总</el-button>
        </el-form-item>
      </el-form>

      <!-- 预览表格 -->
      <div v-if="summaryPreviewData" class="mt-4">
        <el-descriptions title="汇总统计" :column="4" border class="mb-4">
          <el-descriptions-item label="项目总工时">{{ summaryPreviewData.totalProjectHours }}</el-descriptions-item>
          <el-descriptions-item label="部门总工时">{{ summaryPreviewData.totalDeptHours }}</el-descriptions-item>
          <el-descriptions-item label="总工时">{{ summaryPreviewData.totalHours }}</el-descriptions-item>
          <el-descriptions-item label="总人数">{{ summaryPreviewData.staffCount }}</el-descriptions-item>
          <el-descriptions-item label="标准天数">{{ summaryPreviewData.standardDays }}</el-descriptions-item>
        </el-descriptions>

        <el-table :data="summaryPreviewData.summaryDetailList" border max-height="400">
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="人员" prop="staffName" align="center" />
          <el-table-column label="类型" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isProject === '1' ? 'success' : 'info'">
                {{ scope.row.isProject === '1' ? '项目' : '部门' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="项目号" prop="originalProjectCode" align="center" show-overflow-tooltip />
          <el-table-column label="项目名称" prop="originalProjectName" align="center" show-overflow-tooltip />
          <el-table-column label="工时" prop="originalHours" align="center" />
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitGenerateSummary" :loading="buttonLoading" :disabled="!summaryPreviewData">确 定</el-button>
          <el-button @click="generateDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TimesheetInfo" lang="ts">
import { listTimesheetInfo, getTimesheetInfo, delTimesheetInfo, addTimesheetInfo, updateTimesheetInfo } from '@/api/oa/erp/timesheetInfo';
import { TimesheetInfoVO, TimesheetInfoQuery, TimesheetInfoForm } from '@/api/oa/erp/timesheetInfo/types';
import { getUserList, listUser } from '@/api/system/user';
import { UserQuery, UserVO } from '@/api/system/user/types';
import { allListDept, listDept } from '@/api/system/dept';
import { DeptVO } from '@/api/system/dept/types';
import { generateTimesheetSummary, addTimesheetSummary as submitSummaryApi } from '@/api/oa/erp/timesheetSummary';
import { TimesheetSummaryVO } from '@/api/oa/erp/timesheetSummary/types';
import { useUserStore } from '@/store/modules/user';

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

const timesheetInfoList = ref<TimesheetInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const userList = ref<UserVO[]>([]);
const deptList = ref<DeptVO[]>([]);

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

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `工时填报ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `工时填报编号`, visible: true },
  { key: 3, label: `人员ID`, visible: false },
  { key: 4, label: `部门ID`, visible: false },
  { key: 5, label: `起始时间`, visible: true },
  { key: 6, label: `结束时间`, visible: true },
  { key: 7, label: `总工时`, visible: true },
  { key: 8, label: `部门工时`, visible: true },
  { key: 9, label: `项目工时`, visible: true },
  { key: 10, label: `工时填报状态`, visible: true },
  { key: 11, label: `流程状态`, visible: true },
  { key: 12, label: `备注`, visible: true },
  { key: 13, label: `删除标志`, visible: true },
  { key: 14, label: `创建部门`, visible: true },
  { key: 15, label: `创建者`, visible: true },
  { key: 16, label: `创建时间`, visible: true },
  { key: 17, label: `更新者`, visible: true },
  { key: 18, label: `更新时间`, visible: true },
  { key: 99, label: `人员`, visible: true },
  { key: 100, label: `人员部门`, visible: true }
]);

const initFormData: TimesheetInfoForm = {
  timesheetId: undefined,
  timesheetCode: undefined,
  userId: undefined,
  deptId: undefined,
  startTime: undefined,
  endTime: undefined,
  totalHours: undefined,
  deptHours: undefined,
  projectHours: undefined,
  timesheetStatus: undefined,
  flowStatus: undefined,
  remark: undefined
};
const data = reactive<PageData<TimesheetInfoForm, TimesheetInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    timesheetCode: undefined,
    userId: undefined,
    deptId: undefined,
    startTime: undefined,
    endTime: undefined,
    totalHours: undefined,
    deptHours: undefined,
    projectHours: undefined,
    timesheetStatus: undefined,
    flowStatus: undefined,
    params: {}
  },
  rules: {
    timesheetId: [{ required: true, message: '工时填报ID不能为空', trigger: 'blur' }],
    // timesheetCode: [{ required: true, message: '工时填报编号不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '人员ID不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '起始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
  }
});

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

/** 查询工时填报列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTimesheetInfo(queryParams.value);
  timesheetInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  timesheetInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TimesheetInfoVO[]) => {
  ids.value = selection.map((item) => item.timesheetId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$tab.closePage(route);
  router.push({
    path: '/timesheet/timesheetInfo/edit',
    query: { type: 'add' }
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TimesheetInfoVO) => {
  const _timesheetId = row?.timesheetId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/timesheet/timesheetInfo/edit',
    query: {
      id: _timesheetId,
      type: 'update'
    }
  });
};

/** 查看按钮操作 */
const handleView = async (row?: TimesheetInfoVO) => {
  const _timesheetId = row?.timesheetId;
  proxy.$tab.closePage(route);
  router.push({
    path: '/timesheet/timesheetInfo/edit',
    query: {
      id: _timesheetId,
      type: 'view'
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  timesheetInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.timesheetId) {
        await updateTimesheetInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTimesheetInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TimesheetInfoVO) => {
  const _timesheetIds = row?.timesheetId || ids.value;
  await proxy?.$modal.confirm('是否确认删除工时填报编号为"' + _timesheetIds + '"的数据项？').finally(() => (loading.value = false));
  await delTimesheetInfo(_timesheetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(async () => {
  // 加载用户列表
  const userRes = await getUserList({} as any);
  userList.value = userRes.data;
  // 加载部门列表
  const deptRes = await allListDept({ deptCategory: '03' } as any);
  deptList.value = deptRes.data;
  // 加载数据列表
  getList();
});

// 生成汇总弹窗数据
const generateDialog = reactive({
  visible: false,
  title: '生成月汇总工时'
});
const generateFormRef = ref<ElFormInstance>();
const generateLoading = ref(false);
const summaryPreviewData = ref<TimesheetSummaryVO | null>(null);

const generateForm = reactive({
  monthCode: '',
  deptId: userStore.deptId
});

const generateRules = {
  monthCode: [{ required: true, message: '请选择月份', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }]
};

const handleGenerateSummary = () => {
  generateForm.monthCode = '';
  generateForm.deptId = userStore.deptId;
  summaryPreviewData.value = null;
  generateDialog.visible = true;
};

const handleGeneratePreview = () => {
  generateFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      generateLoading.value = true;
      try {
        const res = await generateTimesheetSummary({
          monthCode: generateForm.monthCode,
          deptId: generateForm.deptId
        });
        summaryPreviewData.value = res.data;
      } finally {
        generateLoading.value = false;
      }
    }
  });
};

const calculateTotals = () => {
  if (!summaryPreviewData.value || !summaryPreviewData.value.summaryDetailList) return;

  let totalProject = 0;
  let totalDept = 0;

  summaryPreviewData.value.summaryDetailList.forEach((item) => {
    const hours = Number(item.adjustedHours) || 0;
    if (item.isProject === '1') {
      totalProject += hours;
    } else {
      totalDept += hours;
    }
  });

  summaryPreviewData.value.totalProjectHours = totalProject;
  summaryPreviewData.value.totalDeptHours = totalDept;
  summaryPreviewData.value.totalHours = totalProject + totalDept;
};

const submitGenerateSummary = async () => {
  if (!summaryPreviewData.value) return;

  buttonLoading.value = true;
  try {
    // 构造提交数据
    const submitData = {
      ...summaryPreviewData.value,
      summaryDetailList: summaryPreviewData.value.summaryDetailList
    };
    await submitSummaryApi(submitData as any);
    proxy?.$modal.msgSuccess('生成月汇总工时成功');
    generateDialog.visible = false;
  } finally {
    buttonLoading.value = false;
  }
};
</script>
