<!-- eslint-disable prettier/prettier -->
<script setup lang="ts">
import { shallowRef, ref, watch, reactive } from "vue";
import wanyuConfig from "./config/wanyu.config";
import wanyuCompletionConfig from "./config/wanyuCompletion.config";
import wanyuTypeConfig from "./config/wanyuType.config";
import createCompanyConfig,{ columns } from "./config/company.config";

import {
  addition,
  division,
  multiplication,
  unit2TenThousand,
  formatNumber
} from "/@/utils/calc";

const PageName = "grossMargin";

const controlDisplayFn = (num) => isTenThound.value ? unit2TenThousand(num) : formatNumber(num);


wanyuCompletionConfig.columns[1].cellRenderer =  ({ row }) =>controlDisplayFn(row.dayinfo.sale_total)
wanyuCompletionConfig.columns[1].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.dayinfo.sale_total) : formatNumber(row.dayinfo.sale_total);
wanyuCompletionConfig.columns[2].children[0].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.total_tips) : formatNumber(row.total_tips);
wanyuCompletionConfig.columns[2].children[1].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.monthinfo.monthNetSales) : formatNumber(row.monthinfo.monthNetSales);

wanyuConfig.columns[1].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.dayinfo.sale_total) : formatNumber(row.dayinfo.sale_total);
wanyuConfig.columns[2].children[0].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.total_tips) : formatNumber(row.total_tips);
wanyuConfig.columns[2].children[1].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.monthinfo.monthNetSales) : formatNumber(row.monthinfo.monthNetSales);

wanyuTypeConfig.columns[2].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.day) : formatNumber(row.day);
wanyuTypeConfig.columns[3].cellRenderer =  ({ row }) => isTenThound.value ? unit2TenThousand(row.month) : formatNumber(row.month);

columns[1].cellRenderer = ({ row }) => isTenThound.value ? unit2TenThousand(row.dayinfo.sale_total) : formatNumber(row.dayinfo.sale_total);
columns[2].cellRenderer = ({ row }) => isTenThound.value ? unit2TenThousand(row.monthinfo.msale_total) : formatNumber(row.monthinfo.msale_total);

const companies = [
  { companyNo: "GS2302231125079621", companyName: "北京百辰荣达国际科贸有限公司" },
  { companyNo: "GS2302231323386950", companyName: "北京泓源广诚国际商贸有限公司" },
  { companyNo: "GS2304031312553746", companyName: "北京锦兴弘昌科技有限公司" },
  { companyNo: "GS2302231124114965", companyName: "北京普润心堂商贸有限公司" },
  { companyNo: "GS2203161855277894", companyName: "北京万宇恒通国际科贸有限公司" }
];

const daytime = shallowRef("");
const isTenThound = shallowRef(true);

const wanyuCompletionReportRef = ref<any>(null);
const wanyuTypeReportRef = ref<any>(null);
const wanyuReportRef = ref<any>(null);
const dashboardRef = ref<any[]>([]);

const transformTime = function () {
  let time = new Date();
  let y = time.getFullYear();
  let M = time.getMonth() + 1;
  let d = time.getDate();
  return y + "-" + (M < 10 ? "0" + M : M) + "-" + (d < 10 ? "0" + d : d);
};

const initalTotal = {
  total_tips: 0,
  sale_total: 0,
  completionRate: 0
};

const platformDimensionTotal = reactive({
  wanyu:{...initalTotal},
  wanyuCompletion:{...initalTotal}
})

const companyDimensionTotal = reactive(companies.reduce((prev,{companyNo}) => ({
  ...prev,
  [companyNo]:{...initalTotal}
}),{}))

const getPlatformReportResult = function (data: Record<string, any>[] = [], property:string) {
  platformDimensionTotal[property] = data.reduce((prev, current) => {
    const total_tips = addition(prev.total_tips, current.total_tips);
    const sale_total = addition(prev.sale_total, current.monthinfo.monthNetSales);
    const completionRate = multiplication(division(sale_total, total_tips),100);
    return { total_tips, sale_total, completionRate };
  }, initalTotal);
};

const getCompanyReportResult = function (data: Record<string, any>[] = [], companyNo:string) {
  companyDimensionTotal[companyNo] = data.reduce((prev, current) => {
    const total_tips = Number(current.total_tips)
    const sale_total = addition(prev.sale_total,current.monthinfo.msale_total)
    const completionRate = multiplication(division(sale_total,total_tips) || 0, 100)
    return { total_tips, sale_total, completionRate };
  }, initalTotal);
};


watch(
  () => daytime.value,
  daytime => {
    [wanyuReportRef.value,
      wanyuCompletionReportRef.value,
      wanyuTypeReportRef.value,
      ...dashboardRef.value].forEach(dashboard => {
      if (!dashboard) return;
      const contentRef = dashboard.getContent();
      if (!contentRef) return;
      contentRef.value.getPageData({ daytime });
    });
  }
);
daytime.value = transformTime();

</script>

<template>
  <PageAuth :pageName="PageName">    
    <div class="bg-white">
      <div w-full flex justify-end p-2 items-center>
        <!-- 
          <ElButton class="mr-[10px]" type="primary" @click="() => isTenThound = !isTenThound;">
            显示{{ isTenThound ? '元' : '万元' }}
          </ElButton> 
        -->

        <p class="mr-[5px]" style="font-weight:700">显示单位:</p>
        <ElSwitch
          class="mr-[15px]"
          v-model="isTenThound"
          size="large"
          active-text="万元"
          inactive-text="元"
        />
        <ElDatePicker
          v-model="daytime"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          type="date"
          placeholder="选择日期"
          :disabledDate="time => time.getTime() > Date.now()"
        />
      </div>

      <div class="ml-[15px]">
        <h2 style="font-size: 20px; font-weight: 700; margin-bottom: 10px">
          整体搞了
            {{ 
            isTenThound ? unit2TenThousand(platformDimensionTotal.wanyuCompletion.sale_total)  : (formatNumber(platformDimensionTotal.wanyuCompletion.sale_total))
            }} 
            元（万宇平台+业务公司供应商端）
        </h2>
      </div>
      <div class="mx-[12px] mb-[-15px]">
        <ElTable
          border
          size="small"
          :data="[platformDimensionTotal.wanyuCompletion]"
        >
          <ElTableColumn label="月指标">
            <template #="{ row }">{{ isTenThound ? unit2TenThousand(row.total_tips) : formatNumber(row.total_tips) }}</template>
          </ElTableColumn>
          <ElTableColumn label="完成额">
            <template #="{ row }">{{ isTenThound ? unit2TenThousand(row.sale_total) : formatNumber(row.sale_total) }}</template>
          </ElTableColumn>
          <ElTableColumn label="完成率">
            <template #="{ row }">{{ Number(row.completionRate).toFixed(2) + "%"  }}</template>
          </ElTableColumn>
        </ElTable>
      </div>

      <PageContainer
        ref="wanyuCompletionReportRef"
        :contentConfig="wanyuCompletionConfig"
        :events="{content: { handleResult: data => getPlatformReportResult(data, 'wanyuCompletion') }}"
      />

      <h2
        style="font-size: 20px; font-weight: 700; margin-bottom: 10px; margin-left: 15px; "
      >
        平台维度
      </h2>

      <ElRow style="overflow: hidden">
        <ElCol :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <p class="ml-[15px]" style="line-height: 42px">
            北京万宇恒通国际科贸有限公司
          </p>
          <div class="mx-[12px] mb-[-15px]">
            <ElTable border size="small" :data="[platformDimensionTotal.wanyu]">
              <ElTableColumn label="月指标">
                <template #="{ row }">{{
                  isTenThound ? unit2TenThousand(row.total_tips) : formatNumber(row.total_tips)
                }}</template>
              </ElTableColumn>
              <ElTableColumn label="完成额">
                <template #="{ row }">{{
                  isTenThound ? unit2TenThousand(row.sale_total) : formatNumber(row.sale_total)
                }}</template>
              </ElTableColumn>
              <ElTableColumn label="完成率">
                <template #="{ row }">{{
                  Number(row.completionRate).toFixed(2) + "%"
                }}</template>
              </ElTableColumn>
            </ElTable>
          </div>
          <PageContainer
            ref="wanyuReportRef"
            :contentConfig="wanyuConfig"
            :events="{
              content: {
                handleResult: data => getPlatformReportResult(data, 'wanyu')
              }
            }"
          />
        </ElCol>

        <ElCol :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <PageContainer
            ref="wanyuTypeReportRef"
            :contentConfig="wanyuTypeConfig"
          />
        </ElCol>
      </ElRow>

      <h2
        style="
          font-size: 20px;
          font-weight: 700;
          margin-bottom: 10px;
          margin-left: 15px;
        "
      >
        公司维度
      </h2>
      <ElRow style="overflow: hidden">
        <ElCol
          :xs="24"
          :sm="24"
          :md="12"
          :lg="12"
          :xl="12"
          v-for="(company, index) in companies"
          :key="company.companyNo"
        >
          <div class="ml-15px" style="line-height: 32px">
            {{ index + 1 }}.{{ company.companyName || "--" }}
          </div>
          <div class="mx-[12px] mb-[-15px]">
            <ElTable
              border
              size="small"
              :data="[companyDimensionTotal[company.companyNo]]"
            >
              <ElTableColumn label="月指标">
                <template #="{ row }">
                  {{isTenThound ? unit2TenThousand(row.total_tips) : formatNumber(row.total_tips)}}
                </template>
              </ElTableColumn>
              <ElTableColumn label="完成额">
                <template #="{ row }">
                  {{isTenThound ? unit2TenThousand(row.sale_total) : formatNumber(row.sale_total)}}
                </template>
              </ElTableColumn>
              <ElTableColumn label="完成率">
                <template #="{ row }">{{
                  Number(row.completionRate).toFixed(2) + "%"
                }}</template>
              </ElTableColumn>
            </ElTable>
          </div>

          <PageContainer
            ref="dashboardRef"
            :contentConfig="createCompanyConfig(company.companyNo)"
            :events="{
              content: {
                handleResult: data =>
                  getCompanyReportResult(data, company.companyNo)
              }
            }"
          />
        </ElCol>
      </ElRow>
    </div>
  </PageAuth>
</template>
