<script lang="ts" setup>
/**
 * @Name: PlanningSales.vue
 * @Description: 计划销售额录入
 * @Author: xinyan
 */

import {
  exportPlanSalesData,
  getDayTotalData,
  getMonthTotalData, getPlanSalesTotalData,
  getWeekTotalData
} from '/src/views/reportManage/dataCenter/api';
import { reactive, ref } from 'vue';
import dayjs from 'dayjs';
import Selector from '/src/views/reportManage/dataCenter/normalDisplay/components/Selector/index.vue';
import { ElMessage } from 'element-plus';
import { getPlanList } from '/src/views/reportManage/TaskManage/api';
import { planSalesColumns } from '/@/views/reportManage/dataCenter/utils/columns';

// 年份选择器
const currentYear = ref('');
// 筛选查询
const selectorRef = ref(null);
const taskIds = ref({});
const totalRow = ref([]);// 汇总数据

const gridOptions = reactive({
  border: 'inner',
  // showOverflow: true,
  height: 800,
  loading: false,
  round: true,
  editConfig: {
    trigger: 'manual',
    mode: 'row',
    showStatus: true,
    autoClear: false,
  },
  columnConfig: {
    resizable: true,
  },
  toolbarConfig: {
    custom: true,
    zoom: {
      iconIn: 'vxe-icon-fullscreen',
      iconOut: 'vxe-icon-minimize'
    },
    slots: {
      // buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  columns: planSalesColumns,
  data: [],
});

function setDefaultDate() {
  currentYear.value = dayjs().format('YYYY');
}

const disabledDate = (time: Date) => {
  const currentYear = new Date().getFullYear();
  const selectedYear = time.getFullYear();
  return selectedYear > currentYear + 1;
};

const gridEvents = {
  pageChange({ currentPage, pageSize }) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
    }
    getList();
  }
};


async function fetchTotalData(taskIds) {
  try {
    const resp = await getPlanSalesTotalData({
      year_date: currentYear.value,
      task_ids: taskIds,
    });
    totalRow.value = resp.data;
    totalRow.value.platformNumber = '汇总';
  } catch (error) {
    console.error('Error fetching total data:', error);
  }
}

async function getList() {
  try {
    gridOptions.loading = true;
    await fetchTotalData(taskIds.value);
    const response = await getPlanList({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      year_date: currentYear.value,
      task_ids: taskIds.value,
    });
    // gridOptions.data = response.data;
    gridOptions.data = [totalRow.value, ...response.data];
    gridOptions.pagerConfig.total = response.total;
  } catch (error) {
    console.error('Error fetching task data:', error);
  } finally {
    gridOptions.loading = false;
  }
}

async function handleExport() {
  try {
    gridOptions.loading = true;
    const response = await exportPlanSalesData({
      year_date: currentYear.value,
      task_ids: taskIds.value,
      include_sales: 1,
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '计划销售额数据.xlsx');
    document.body.appendChild(link);
    link.click();
    gridOptions.loading = false;
    ElMessage.success('导出数据成功');
  } catch (error) {
    console.error('导出数据失败:', error);
  }
}

function updateDataChange(newId) {
  if (selectorRef.value) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = 1;
    }
    taskIds.value = newId.value;
    getList();
  }
}

watch(currentYear, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    currentYear.value = dayjs(newVal).format('YYYY');
  }
});

const cellStyle = (row) => {
  if (row.$rowIndex === 0 && row.$columnIndex < 5) {
    return {
      position: 'sticky',
      top: 0,
      zIndex: 30,
      fontSize: '12px',
      fontWeight: '600',
    };
  }
  return {
    fontSize: '12px',
    fontWeight: '600',
    padding: 0,
  };
};

const headerCellStyle = () => {
  return {
    fontSize: '12px',
  };
};

const rowStyle = (row) => {
  if (row.$rowIndex === 0) {
    return {
      background: '#def6fe',
      position: 'sticky',
      top: 0,
      zIndex: 1,
    };
  }
  return {
    padding: 0,
    height: '50px',
  };
};

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

<template>
  <div class="px-3.5">
    <el-card body-style="padding: 10px" class="mb-3.5 mt-3.5">
      <div class="custom-card-style flex gap-1.5 justify-between my-1.5 mx-2"
           style="display: flex; align-items: center;height: 52px; ">
        <Selector ref="selectorRef" @update:updateData="updateDataChange" />
        <div class="demo-date-picker">
          <div class="block">
            <span class="demonstration">年份：</span>
            <el-date-picker
                v-model="currentYear"
                :disabled-date="disabledDate"
                placeholder="Pick a year"
                style="width: 150px"
                type="year"
                @change="getList"
            />
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="mt-3">
    <slot name="table-header"></slot>
      <vxe-grid ref="xGrid" :cell-style="cellStyle" :header-cell-style="headerCellStyle" :row-style="rowStyle"
                v-bind="gridOptions"
                v-on="gridEvents">
        <template #toolbar_tools>
          <div class="pr-2.5">
            <el-tooltip content="下载表格" placement="top">
              <vxe-button circle icon="vxe-icon-download" @click="handleExport"></vxe-button>
            </el-tooltip>
          </div>
        </template>
        <template #platformNumber_default="{ row }">
          <div class="font-semibold">{{ row.platformNumber }}</div>
        </template>
        <template #platformName_default="{ row }">
          <div class="font-semibold" style="color: #164285">{{ row.platformName }}</div>
        </template>
        <template #brandName_default="{ row }">
          {{ row.brandName }}
        </template>
      </vxe-grid>
    </el-card>
  </div>
</template>

<style scoped>
.demo-date-picker {
  display: flex;
  flex-direction: row-reverse;
}

.block {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  overflow: hidden;
  /* width: 100%; */
}

.demo-date-picker .demonstration {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  white-space: nowrap;
  margin-right: 2px;
}

:deep(.vxe-table--header .vxe-header--row th .vxe-cell,
.vxe-table--body .vxe-body--row td .vxe-cell) {
  padding-left: 5px !important;
  padding-right: 0 !important;
}

.el-card {
  border: none;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 0px 0px 12px rgba(51, 89, 181, 0.16);
}
</style>