<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="timesheetCode">
              <el-input v-model="queryParams.timesheetCode" placeholder="请输入工时填报编号" clearable @keyup.enter="handleQuery" />
            </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>
          <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="nickName" v-if="columns[11].visible" />
        <el-table-column label="人员部门" align="center" prop="deptName" v-if="columns[12].visible" />
        <el-table-column label="工时填报编号" align="center" prop="timesheetCode" v-if="columns[2].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>
  </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';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
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 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
    },
    `timesheetInfo_${new Date().getTime()}.xlsx`
  );
};

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