<script setup lang="ts">
import { ref } from "vue";
import searchConfig from "./config/search.summary";
import { columns } from "./config/content.summary";
import { usePermission } from "/@/hooks/core";
import { PageSearch } from "/@/components/PageSearch";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import apis from "./config/apis";
import { frontEndExport } from "/@/utils/export";
import { onMounted } from "vue";
import dayjs from "dayjs";
import { shallowRef } from "vue";

// 汇总权限:列表|导出
const pageName = "saleDepartment";
const { hasPermissionWithCode } = usePermission(pageName);

const loading = shallowRef(false);
const managers = ref<Record<string, string>[]>([]);
const salers = ref<Record<string, string>[]>([]);

async function handleExportAllReport() {
  const u1 = managers.value.map(({ manager, total_percentage }) => ({
    username: manager,
    total_percentage
  }));
  const u2 = salers.value.map(({ saler, total_percentage }) => ({
    username: saler,
    total_percentage
  }));
  const data = [...u1, ...u2];
  frontEndExport({
    columns,
    name: "销售部提成业绩汇总.xlsx",
    data
  });
}

async function requestData(params: any) {
  loading.value = true;
  const { data, code } = await apis.summary({ ...params, depart_type: "4" });
  loading.value = false;
  if (code !== 1) return;
  const { manager = [], sale = [] } = data || {};
  managers.value = manager;
  salers.value = sale;
}

const year_month = dayjs(new Date()).subtract(1, "month").format("YYYY-MM");
onMounted(() => requestData({ year_month }));
</script>

<template>
  <div>
    <PageSearch
      :lock-key="(['year_month'] as unknown as string)"
      :form-config="searchConfig"
      @reset-btn-click="requestData"
      @search-btn-click="requestData"
    />
    <div bg-white p-2 v-loading="loading">
      <div
        flex
        justify-end
        mb-2
        mr-2
        v-if="hasPermissionWithCode('9')"
        v-loading="loading"
      >
        <ElButton
          :icon="useRenderIcon('arrow-up-line') as unknown as string"
          v-if="hasPermissionWithCode('9')"
          @click="handleExportAllReport"
          type="primary"
          size="small"
          >导出
        </ElButton>
      </div>

      <div flex gap-5>
        <ElTable border size="small" :data="managers">
          <ElTableColumn prop="manager" label="业务经理" />
          <ElTableColumn prop="total_percentage" label="提成金额" />
        </ElTable>
      </div>
    </div>
  </div>
</template>
