<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="120px">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目经理" prop="managerName">
              <el-input v-model="queryParams.managerName" placeholder="请输入项目经理" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="当前里程碑" prop="milestonePlan">
              <el-input v-model="queryParams.milestonePlan" placeholder="请输入当前里程碑" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="部门负责人" prop="chargeName">
              <el-input v-model="queryParams.chargeName" placeholder="请输入部门负责人" clearable @keyup.enter="handleQuery" />
            </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-row :gutter="10" class="form-row">
              <el-col :span="12" v-show="false">
                <el-form-item label="周报ID" prop="reportId">
                  <el-input v-model="queryParams.reportId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="项目ID" prop="projectId">
                  <el-input v-model="queryParams.projectId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="项目经理ID" prop="managerId">
                  <el-input v-model="queryParams.managerId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="部门ID" prop="deptId">
                  <el-input v-model="queryParams.deptId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="部门负责人ID" prop="chargeId">
                  <el-input v-model="queryParams.chargeId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="分管副总ID" prop="deputyId">
                  <el-input v-model="queryParams.deputyId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="分管副总" prop="deputyName">
                  <el-input v-model="queryParams.deputyName" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="附件ID" prop="ossId">
                  <el-input v-model="queryParams.ossId" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="排序号" prop="sortOrder">
                  <el-input v-model="queryParams.sortOrder" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="激活标识" prop="activeFlag">
                  <el-input v-model="queryParams.activeFlag" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="false">
                <el-form-item label="周报说明" prop="informationNote">
                  <el-input v-model="queryParams.informationNote" placeholder="请点击右侧图标选择项目" />
                </el-form-item>
              </el-col>
            </el-row>
          </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:projectReport: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:projectReport: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:projectReport:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:projectReport:export']">导出</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="projectReportList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目周报ID" align="center" prop="reportId" width="100" v-if="columns[0].visible" />
        <el-table-column label="项目ID" align="center" prop="projectId" width="100" v-if="columns[1].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" width="150" v-if="columns[2].visible" />
        <el-table-column label="项目编码" align="center" prop="projectCode" width="150" v-if="columns[3].visible" />
        <el-table-column label="当前里程碑" align="center" prop="milestonePlan" width="100" v-if="columns[4].visible" />
        <el-table-column label="项目经理" align="center" prop="managerName" width="100" v-if="columns[5].visible" />
        <el-table-column label="部门名称" align="center" prop="deptName" width="150" v-if="columns[6].visible" />
        <el-table-column label="部门负责人" align="center" prop="chargeName" width="100" v-if="columns[7].visible" />
        <el-table-column label="分管副总" align="center" prop="deputyName" width="100" v-if="columns[8].visible" />
        <el-table-column label="周报情况说明" align="center" prop="informationNote" width="150" v-if="columns[9].visible" />
        <el-table-column label="排序号" align="center" prop="sortOrder" width="100" v-if="columns[10].visible" />
        <el-table-column label="附件ID" align="center" prop="ossId" width="100" v-if="columns[11].visible" />
        <el-table-column label="备注" align="center" prop="remark" width="150" v-if="columns[12].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="100" v-if="columns[13].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100" v-if="columns[14].visible" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="100" v-if="columns[15].visible" />
        <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.status !== '1'"
              :content="`为「${scope.row.projectName || '该项目'}」新增一条周报明细`"
              placement="top"
            >
              <el-button
                link
                type="primary"
                icon="DocumentAdd"
                @click="handleAddWeeklyDetail(scope.row)"
                v-hasPermi="['oa/erp:projectReport:add']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.status === '1'">
              <el-button
                link
                type="success"
                icon="Edit"
                @click="handleUpdateReport(scope.row)"
                v-hasPermi="['oa/erp:projectReport:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.status !== '1'">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/erp:projectReport:remove']"></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-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
        <el-form ref="projectReportFormRef" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="10" class="form-row">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="form.projectName" placeholder="请输入项目名称" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编码" prop="projectCode">
                <el-input v-model="form.projectCode" placeholder="请输入项目编码" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="form-row">
            <el-col :span="12">
              <el-form-item label="当前里程碑" prop="milestonePlan">
                <el-input v-model="form.milestonePlan" placeholder="请输入当前里程碑" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="deptId">
                <el-select
                  v-model="form.deptId"
                  placeholder="请选择部门"
                  clearable
                  filterable
                  :loading="loadingUsers"
                  @change="handleDeptChange"
                  :disabled="true"
                >
                  <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="form-row">
            <el-col :span="12">
              <el-form-item label="项目经理" prop="managerId">
                <el-select
                  v-model="form.managerId"
                  placeholder="请选择项目经理"
                  clearable
                  filterable
                  :disabled="true || !form.deptId"
                  @change="handleManagerChange"
                >
                  <el-option v-for="user in managerList" :key="user.nickName" :label="user.nickName" :value="user.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门负责人" prop="chargeId">
                <el-select
                  v-model="form.chargeId"
                  placeholder="请选择部门负责人"
                  clearable
                  filterable
                  :disabled="true || !form.deptId"
                  @change="handleChargeChange"
                >
                  <el-option v-for="user in chargeList" :key="user.nickName" :label="user.nickName" :value="user.userId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="form-row">
            <el-col :span="12">
              <el-form-item label="分管副总" prop="deputyId">
                <el-select
                  v-model="form.deputyId"
                  placeholder="请选择分管副总"
                  clearable
                  filterable
                  :disabled="true || !form.deptId"
                  @change="handleDeputyChange"
                >
                  <el-option v-for="user in deputyList" :key="user.nickName" :label="user.nickName" :value="user.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="form-row">
            <el-col :span="12">
              <el-form-item label="周报情况说明" prop="informationNote">
                <el-input v-model="form.informationNote" type="textarea" placeholder="请输入内容" />
              </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', 'jpg', 'jpeg', 'png']"
                  :disabled="false"
                  :isShowTip="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="false">
              <el-form-item label="激活标识" prop="activeFlag">
                <el-input v-model="form.activeFlag" placeholder="请输入激活标识" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="form-row" v-show="false">
            <el-col :span="12">
              <el-form-item label="项目ID" prop="projectId">
                <el-input v-model="form.projectId" placeholder="请输入项目ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目经理" prop="managerId">
                <el-input v-model="form.managerId" placeholder="请输入项目经理" />
              </el-form-item>
            </el-col>
          </el-row>
        </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>
    </el-card>
  </div>
</template>

<script setup name="ProjectReport" lang="ts">
import { ProjectReportVO, ProjectReportQuery, ProjectReportForm } from '@/api/oa/erp/projectReport/types';
import { listProjectReport, getProjectReport, delProjectReport, addProjectReport, updateProjectReport } from '@/api/oa/erp/projectReport';
import { allListDept } from '@/api/system/dept';
import { listUserByDeptId } from '@/api/system/user';
import FileUpload from '@/components/FileUpload/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const projectReportList = ref<ProjectReportVO[]>([]);
const route = useRoute();
const router = useRouter();
const buttonLoading = ref(false);
const loading = 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 projectReportFormRef = ref<ElFormInstance>();

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `项目周报ID`, visible: false },
  { key: 1, label: `项目ID`, visible: false },
  { 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 },
  { key: 8, label: `分管副总`, visible: true },
  { key: 9, label: `周报情况说明`, visible: true },
  { key: 10, label: `排序号`, visible: false },
  { key: 11, label: `附件ID`, visible: false },
  { key: 12, label: `备注`, visible: false },
  { key: 13, label: `激活标识`, visible: false },
  { key: 14, label: `创建时间`, visible: true },
  { key: 15, label: `更新时间`, visible: true }
]);
const initFormData: ProjectReportForm = {
  reportId: undefined,
  projectId: undefined,
  projectName: undefined,
  projectCode: undefined,
  milestonePlan: undefined,
  managerId: undefined,
  deptId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  informationNote: undefined,
  sortOrder: undefined,
  ossId: undefined,
  remark: undefined,
  activeFlag: undefined,
  deptName: undefined,
  managerName: undefined,
  chargeName: undefined,
  deputyName: undefined,
  status: undefined
};
const data = reactive<PageData<ProjectReportForm, ProjectReportQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reportId: undefined,
    projectId: undefined,
    projectName: undefined,
    projectCode: undefined,
    milestonePlan: undefined,
    managerId: undefined,
    deptId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    informationNote: undefined,
    sortOrder: undefined,
    ossId: undefined,
    activeFlag: undefined,
    deptName: undefined,
    managerName: undefined,
    chargeName: undefined,
    deputyName: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    projectCode: [{ required: true, message: '项目编码不能为空', trigger: 'blur' }]
  }
});

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

// 定义计算属性用于双向绑定
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 deptList = ref<any[]>([]);
const managerList = ref<any[]>([]);
const chargeList = ref<any[]>([]);
const deputyList = ref<any[]>([]);
const loadingUsers = ref(false);

// 获取部门列表
const getDeptList = async () => {
  try {
    const res = await allListDept();
    deptList.value = res.data || [];
  } catch (error) {
    console.error('获取部门列表失败:', error);
    deptList.value = [];
  }
};

// 根据部门ID获取所有用户
const getUsersByDept = async (deptId: number | string) => {
  if (!deptId) {
    managerList.value = [];
    chargeList.value = [];
    deputyList.value = [];
    return;
  }
  try {
    loadingUsers.value = true;
    // 获取当前部门的用户（用于项目经理和部门负责人）
    const currentDeptUsers = await listUserByDeptId(deptId);
    // 找到当前部门的信息，获取父部门ID
    const currentDept = deptList.value.find((dept) => String(dept.deptId) === String(deptId));
    if (currentDept) {
      // 当前部门的用户用于项目经理和部门负责人
      managerList.value = currentDeptUsers.data || [];
      chargeList.value = currentDeptUsers.data || [];
      // 如果有父部门，获取父部门的用户作为分管副总列表
      if (currentDept.parentId && currentDept.parentId !== '0') {
        const parentDeptUsers = await listUserByDeptId(currentDept.parentId);
        deputyList.value = parentDeptUsers.data || [];
      } else {
        // 如果没有父部门，则当前部门的用户也可作为分管副总
        deputyList.value = currentDeptUsers.data || [];
      }
      // 更新部门名称
      form.value.deptName = currentDept.deptName || currentDept.label;
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    managerList.value = [];
    chargeList.value = [];
    deputyList.value = [];
  } finally {
    loadingUsers.value = false;
  }
};
// 部门选择变化时触发
const handleDeptChange = async (deptId: number | string) => {
  // 清空之前选择的用户
  form.value.managerId = undefined;
  form.value.chargeId = undefined;
  form.value.deputyId = undefined;
  form.value.managerName = undefined;
  form.value.chargeName = undefined;
  form.value.deputyName = undefined;
  // 清空用户列表
  managerList.value = [];
  chargeList.value = [];
  deputyList.value = [];
  // 获取该部门的用户
  await getUsersByDept(deptId);
};
// 用户选择变化时更新对应名称
const handleManagerChange = (userId: number | string) => {
  const selectedUser = managerList.value.find((user) => String(user.userId) === String(userId));
  if (selectedUser) {
    form.value.managerName = selectedUser.nickName || selectedUser.label;
  }
};

const handleChargeChange = (userId: number | string) => {
  const selectedUser = chargeList.value.find((user) => String(user.userId) === String(userId));
  if (selectedUser) {
    form.value.chargeName = selectedUser.nickName || selectedUser.label;
  }
};

const handleDeputyChange = (userId: number | string) => {
  const selectedUser = deputyList.value.find((user) => String(user.userId) === String(userId));
  if (selectedUser) {
    form.value.deputyName = selectedUser.nickName || selectedUser.label;
  }
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 查询项目周报信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProjectReport(queryParams.value);
  projectReportList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 对话框表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  projectReportFormRef.value?.resetFields();
};
/** 对话框取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProjectReportVO[]) => {
  ids.value = selection.map((item) => item.reportId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 提交按钮 */
const submitForm = () => {
  projectReportFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.reportId) {
        await updateProjectReport(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProjectReport(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 跳转编辑页（与工时填报一致：仅传必要 query） */
function navigateToProjectReportEdit(query: Record<string, string | number | undefined>) {
  proxy.$tab.closePage(route);
  router.push({
    path: '/project/projectReport/edit',
    query: query as Record<string, any>
  });
}

/** 顶部「新增」：空白主表 */
const handleAdd = () => {
  reset();
  navigateToProjectReportEdit({
    type: 'add',
    pageNum: queryParams.value.pageNum
  });
};

/** 行内：在已有周报主表下新增一条明细 */
const handleAddWeeklyDetail = (row: ProjectReportVO) => {
  if (row?.reportId == null || row.reportId === '') {
    proxy?.$modal.msgWarning('当前行缺少周报主键，无法新增明细');
    return;
  }
  reset();
  navigateToProjectReportEdit({
    type: 'add',
    addMode: 'detail',
    reportId: row.reportId,
    pageNum: queryParams.value.pageNum
  });
};
/** 查看：按周报主键加载 */
const handleView = (row?: ProjectReportVO) => {
  if (!row?.reportId) return;
  reset();
  navigateToProjectReportEdit({
    type: 'view',
    reportId: row.reportId,
    pageNum: queryParams.value.pageNum
  });
};
/** 修改草稿：按周报主键加载 */
const handleUpdateReport = (row?: ProjectReportVO) => {
  if (!row?.reportId) return;
  reset();
  navigateToProjectReportEdit({
    type: 'update',
    reportId: row.reportId,
    pageNum: queryParams.value.pageNum
  });
};
/** 修改按钮操作 */
const handleUpdate = async (row?: ProjectReportVO) => {
  reset();
  // 打开遮罩层
  proxy?.$modal.loading('正在查询数据，请稍后...');

  const _reportId = row?.reportId || ids.value[0];
  const res = await getProjectReport(_reportId);

  // 重置表单
  form.value = { ...initFormData };
  Object.assign(form.value, res.data);

  // 获取部门对应的用户列表
  if (form.value.deptId) {
    await getUsersByDept(form.value.deptId);
  }
  // 关闭遮罩层
  proxy?.$modal.closeLoading();
  dialog.visible = true;
  dialog.title = '修改项目周报信息';
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProjectReportVO) => {
  const _reportIds = row?.reportId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目周报信息编号为"' + _reportIds + '"的数据项？').finally(() => (loading.value = false));
  await delProjectReport(_reportIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/erp/projectReport/export',
    {
      ...queryParams.value
    },
    `projectReport_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getDeptList();
});
</script>
