<!-- 売上集計結果 -->
<template>
  <div class="app-container">
    <div class="csv-title">
      <el-button   @click="handleExportCSV" class="append-button">CSV出力</el-button>
    </div>
    <el-table v-show="initLoadingCompleted && aggregationType === AGGREGATION_TYPE.FC"  v-loading="listLoading" :border="true" :data="fcItemList">
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="FC" min-width="60"
                       prop="fcName"
      >
      </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="エリア" min-width="70"
                         prop="areaName"
                         width=""/>
        <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="売上合計" min-width="80"
                         prop="totalSales"
                         width=""/>
        <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="店舗数" min-width="60"
                         prop="storeCount"
                         width=""/>
        <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="平均売上" min-width="60"
                         prop="avgSales"
                         width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" :label="ratioLabel" min-width="40"
                       prop="prevRatio"
                       width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="FC内売上シェア" min-width="50"
                       prop="salesShare"
                       width=""/>
    </el-table>

    <el-table  v-show="initLoadingCompleted && aggregationType === AGGREGATION_TYPE.STORE"  v-loading="listLoading" :border="true" :data="storeItemList">
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="FC" min-width="60"
                       prop="fcName"
      >
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="エリア" min-width="70"
                       prop="areaName"
                       width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="売上合計" min-width="60"
                       prop="totalSales"
                       width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="店舗名" min-width="70"
                       prop="storeName"
                       width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="平均取引額" min-width="60"
                       prop="avgTransaction"
                       width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" :label="ratioLabel" min-width="40"
                       prop="prevRatio"
                       width=""/>
      <el-table-column :show-overflow-tooltip="true" align="left" header-align="center" label="FC内売上シェア" min-width="50"
                       prop="salesShare"
                       width=""/>
    </el-table>

    <pagination v-show="listTotalCnt>0"
                v-model:limit="queryParams.pageSize"
                v-model:page="queryParams.pageNum"
                :total="listTotalCnt"
                @pagination="getSearchList"/>
  </div>
</template>

<script name="purchaseSaleResults" setup>

import { purchaseSaleList} from "@/api/fcbi/purchaseSale.js"
import useSalesStore from '@/store/modules/sales.js';
import {download} from "@/utils/request.js";
import { AGGREGATION_TYPE, TARGET_PERIOD_TYPE } from '@/constants';
defineExpose({
  AGGREGATION_TYPE,
  TARGET_PERIOD_TYPE
});
// 認証項目のテーブルデータを格納するリアクティブ
const fcItemList = ref([]);
const storeItemList = ref([]);
// データ読み込み中のローディング状態を管理するリアクティブ
const listLoading = ref(false);
// 検索結果の総件数を格納するリアクティブ
const listTotalCnt = ref(0);
// 初期ロードが完了したかどうかを示すリアクティブ
const initLoadingCompleted = ref(false);
const SalesStore = useSalesStore();

const aggregationType = computed(() => {
  return SalesStore.salesData.aggregationType;
});

const ratioLabel = computed(() => {
  // 从存储中获取选择的类型（月指定/年度指定）
  const { releaseType } = SalesStore.salesData;
  // 返回对应的标题
  return releaseType === 'immediate' ? '前月比' : '前年度比';
});

/**
 * コンポーネントの状態を管理するリアクティブオブジェクト
 */
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    startYear: '',
    startMonth: '',
    annual: '',
    brandCode: [],
    regions: [],
    salesFlag: 0
  },
});

// リアクティブオブジェクトからプロパティを参照可能なオブジェクトに変換
const {queryParams} = toRefs(data);

onMounted(() => {
  const {
    startYear,
    startMonth,
    annual,
    brandCodes,
    regionCodes,
    salesFlag,
    aggregationType
  } = SalesStore.salesData;

  queryParams.value.startYear = startYear;
  queryParams.value.startMonth = startMonth;
  queryParams.value.annual = annual;
  queryParams.value.regionCodes = regionCodes;
  queryParams.value.brandCodes = brandCodes;
  queryParams.value.salesFlag = salesFlag;
  queryParams.value.aggregationType = aggregationType;
  getSearchList();
});

/**
 * 発注リストを検索する関数
 * APIを呼び出して検索条件に一致する発注データを取得する
 */
function getSearchList() {
  listLoading.value = true;
  const params = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    // 月指定参数（仅当月指定时有效）
    startYear: queryParams.value.startYear,
    startMonth: queryParams.value.startMonth,
    // 年度指定参数（仅当年度指定时有效）
    annual: queryParams.value.annual,
    // FC选择值
    brandCodes: queryParams.value.brandCodes,
    // エリア选择值
    regionCodes: queryParams.value.regionCodes,
    // 标志位（用于后端判断逻辑）
    salesFlag: queryParams.value.salesFlag
  };
  purchaseSaleList(params).then(response => {
    fcItemList.value = response.rows;
    storeItemList.value = response.rows;
    listTotalCnt.value = response.total;
    listLoading.value = false;
    initLoadingCompleted.value = true;
  });
}

function handleExportCSV() {

  const { salesFlag } = queryParams.value;
  let fileNamePrefix;
  switch (salesFlag) {
    case 1:
      fileNamePrefix = "monthly_fc_sales_by_current_region";
      break;
    case 2:
      fileNamePrefix = "monthly_fc_sales_by_parent_region";
      break;
    case 3:
      fileNamePrefix = "annual_fc_sales_by_current_region";
      break;
    case 4:
      fileNamePrefix = "annual_fc_sales_by_parent_region";
      break;
    case 5:
      fileNamePrefix = "monthly_store_sales_by_region";
      break;
    default:
      fileNamePrefix = "annual_store_sales_by_region";
  }
  const fileName = `${fileNamePrefix}_${new Date().getTime()}.csv`;

  const exportParams = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    // 月指定参数（仅当月指定时有效）
    startYear: queryParams.value.startYear,
    startMonth: queryParams.value.startMonth,
    // 年度指定参数（仅当年度指定时有效）
    annual: queryParams.value.annual,
    // FC选择值
    brandCodes: queryParams.value.brandCodes,
    // エリア选择值
    regionCodes: queryParams.value.regionCodes,
    // 标志位（用于后端判断逻辑）
    salesFlag: queryParams.value.salesFlag
  };
  download('system/purchase/sale/exportResultsCsv', exportParams, fileName);
}
</script>

<style>
.csv-title {
  font-size: 14px;
  color: #606266;
  margin: 0 0 15px 20px;
  padding-top: 10px;
  font-weight: 700;
}

.append-button{
  background-color: #FF0066;
  color: white;
  width: 200px;
}

/* 响应式样式 */
@media (max-width: 767px) {
  /* 手机设备 */
  .csv-title {
    margin-left: 10px;
    font-size: 13px;
  }
  .append-button {
    width: 120px;
    font-size: 12px;
    padding: 8px 0;
  }
  .el-table {
    font-size: 12px;
  }
  .el-table-column {
    min-width: 40px !important;
  }
}

@media (min-width: 768px) and (max-width: 1023px) {
  /* 平板设备 */
  .csv-title {
    margin-left: 15px;
  }
  .append-button {
    width: 160px;
  }
}

/* 电脑设备保持原有样式 */
@media (min-width: 1024px) {
  .csv-title {
    margin-left: 20px;
  }
  .append-button {
    width: 200px;
  }
}
</style>
