<template>
  <div class="app-container">
    <!-- <el-tabs v-model="orderType" @tab-click="getTableData">
      <el-tab-pane label="收款" name="1"></el-tab-pane>
      <el-tab-pane label="销量" name="2"></el-tab-pane>
    </el-tabs> -->
    <div class="head-container">
      <el-form :model="query" inline label-position="left">
        <div class="u-flex gap-10" style="flex-wrap: wrap;">
          <el-radio-group v-model="timeValue" @change="timeChange">
            <!-- <el-radio-button value="">全部</el-radio-button> -->
            <el-radio-button value="today">今天</el-radio-button>
            <el-radio-button value="yesterday">昨天</el-radio-button>
            <el-radio-button value="last_7_days">最近7天</el-radio-button>
            <el-radio-button value="last_30_days">最近30天</el-radio-button>
            <el-radio-button value="this_week">本周</el-radio-button>
            <el-radio-button value="this_month">本月</el-radio-button>
            <el-radio-button value="custom">自定义</el-radio-button>
          </el-radio-group>
          <div v-if="timeValue == 'custom'">
            <el-date-picker v-model="query.createdAt" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
          </div>
          <div>
            <el-select v-model="shopId" v-if="isHeadShop == 1 && loginType == 0" placeholder="选择分店"
              style="width: 200px; margin-right: 10px">
              <el-option v-for="item in branchList" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
            </el-select>
          </div>
          <div style="display: flex;">
            <el-button type="primary" @click="getTableData">查询</el-button>
            <el-button @click="resetHandle">重置</el-button>
            <el-button icon="download" v-loading="downloadLoading" @click="downloadHandle">
              <span v-if="!downloadLoading">导出Excel</span>
              <span v-else>下载中...</span>
            </el-button>
            <importData :type="8" @close="getTableData" />
          </div>
        </div>
      </el-form>
    </div>
    <!-- <div class="head-container">
      <div class="collect_wrap">
        <div class="item" v-for="item in payCountList" :key="item.id">
          <div class="icon_wrap" style="--bg-color:#C978EE">
            <i class="icon" :class="item.icon"></i>
          </div>
          <div class="info">
            <div class="m">
              <template v-if="item.isAmount == 1">￥</template>
{{ item.payAmount }}
</div>
<div class="t">{{ item.payType }}</div>
</div>
</div>
</div>
</div> -->
    <div class="head-container">
      <el-table :data="tableData.data" v-loading="tableData.loading" v-if="orderType == 1">
        <el-table-column type="index" width="50"></el-table-column>
        <!-- <el-table-column label="序号" prop="id"></el-table-column> -->
        <!-- <el-table-column label="区域id" prop="areaId"></el-table-column> -->
        <el-table-column label="区域名称" prop="areaName"></el-table-column>
        <!-- <el-table-column label="门店id" prop="shopId"></el-table-column> -->
        <!-- <el-table-column label="台桌Id" prop="tableId"></el-table-column> -->
        <el-table-column label="台桌号" prop="tableName"></el-table-column>
        <el-table-column label="订单数量" prop="orderCount" sortable>
          <template v-slot="scope">
            <div class="cursor-pointer" @click="toTableOrderList(scope.row)">
              {{ scope.row.orderCount }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="orderAmount" sortable></el-table-column>
      </el-table>
      <!-- <el-table :data="tableData.data" v-loading="tableData.loading" v-if="orderType == 2">
        <el-table-column label="商品名称" prop="productName"></el-table-column>
        <el-table-column label="商品分类" prop="cateName"></el-table-column>
        <el-table-column label="商品描述" prop="productSkuName"></el-table-column>
        <el-table-column label="销量" prop="salesNum"></el-table-column>
        <el-table-column label="退单量" prop="refNum"></el-table-column>
        <el-table-column label="销售金额" prop="salesAmount">
          <template v-slot="scope">
            ￥{{ scope.row.salesAmount }}
          </template>
        </el-table-column>
        <el-table-column label="退款金额" prop="refAmount">
          <template v-slot="scope">
            ￥{{ scope.row.refAmount }}
          </template>
        </el-table-column>
      </el-table> -->
    </div>
    <div class="head-container">
      <el-pagination :total="tableData.total" :current-page="tableData.page" :page-size="tableData.size"
        @current-change="paginationChange" @size-change="sizeChange"
        layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import importData from "@/components/importData/index.vue";
import tableSummaryApi from "@/api/order/table-summary";
import ShopApi from "@/api/account/shop";
import dayjs from "dayjs";
import { downloadFile } from "@/utils/index";
import { formatDateRange } from './utils/index.js'

export default {
  components: { importData },
  data() {
    return {
      timeValue: "today",
      resetQuery: null,
      orderType: "1",
      categorys: [],
      query: {
        createdAt: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
        proName: "",
        cateId: "",
      },
      tableData: {
        totalList: [],
        data: [],
        page: 1,
        size: 10,
        loading: false,
        total: 0,
      },
      downloadLoading: false,
      payCountList: "",
      payCountTotal: 0,
      shopId: null,
      branchList: [],
      isHeadShop: JSON.parse(localStorage.getItem("userInfo")).isHeadShop,
      loginType: localStorage.getItem("loginType"),
      shopInfo: JSON.parse(localStorage.getItem("userInfo"))
    };
  },
  filters: {
    timeFilter(time) {
      return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
    },
  },
  mounted() {
    let shopInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (shopInfo.isHeadShop) {
      this.shopId = shopInfo.id
    } else {
      this.shopId = localStorage.getItem('shopId')
    }

    this.resetQuery = { ...this.query };
    this.getTableData();
    this.geiShopList();
  },
  methods: {
    /**
    * 获取分店列表
    */
    async geiShopList() {
      if (this.shopInfo.isHeadShop) {
        let res = await ShopApi.getBranchList()
        this.branchList = res;
        this.shopId = res[0].shopId
      } else {
        this.shopId = this.shopInfo.id
      }
    },
    //携带table id跳转到订单列表页面
    toTableOrderList(data) {
      // console.log(data)
      this.$router.push({
        path: "/order/index",
        query: {
          tableCode: data.tableCode,
          tableName: data.tableName,
        },
      });
    },
    // 导出Excel
    async downloadHandle() {
      try {
        this.downloadLoading = true;
        if (this.query.createdAt[1]) {
          this.query.createdAt.splice(1, 1, this.query.createdAt[1].replace("00:00:00", "23:59:59"))
        }
        const file = await tableSummaryApi.export({
          beginDate: this.query.createdAt[0],
          endDate: this.query.createdAt[1],
          shopId: this.shopId,
          rangeType: this.timeValue,
        });
        downloadFile(file, "数据", "xlsx");
        this.downloadLoading = false;
      } catch (error) {
        this.downloadLoading = false;
        console.log(error);
      }
    },
    // 重置查询
    resetHandle() {
      this.timeValue = "today";
      this.query = { ...this.resetQuery };
      this.page = 1;
      this.getTableData();
    },
    // 分页大小改变
    sizeChange(e) {
      this.tableData.page = 1
      this.tableData.size = e;
      this.getTableData();
    },
    // 分页回调
    paginationChange(e) {
      this.tableData.page = e;
      this.tableData.data = this.tableData.totalList[this.tableData.page - 1] || [];
      // this.getTableData();
    },
    async getTableData() {
      this.tableData.loading = true;
      try {
        // if (this.query.createdAt[1]) {
        //   this.query.createdAt.splice(1, 1, this.query.createdAt[1].replace("00:00:00", "23:59:59"))
        // }
        const res = await tableSummaryApi.list({
          // page: this.tableData.page,
          // size: this.tableData.size,
          rangeType: this.timeValue,
          // rangeType: 'custom',
          beginDate: this.query.createdAt[0],
          endDate: this.query.createdAt[1],
          // beginDate: '2026-01-26',
          // endDate: '2026-01-26',
          shopId: this.shopId
        });
        this.tableData.loading = false;
        this.tableData.totalList = _.chunk(res, this.tableData.size);
        this.tableData.data = this.tableData.totalList[this.tableData.page - 1] || [];
        this.tableData.total = res.length;
      } catch (error) {
        console.log(error);
      }
    },
    // 切换时间
    timeChange(e) {
      this.query.createdAt = formatDateRange(e)
    },
  },
};
</script>

<style scoped lang="scss">
.cursor-pointer {
  cursor: pointer;
  color: #1890ff;
  transition: all 0.3s;
}

.cursor-pointer:hover {
  opacity: 0.7;
}

.collect_wrap {
  display: flex;
  gap: 14px;

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    padding: 20px;

    .icon_wrap {
      $size: 34px;
      $border: 6px;
      width: $size;
      height: $size;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--bg-color);
      border-radius: 50%;
      position: relative;

      &::after {
        content: "";
        width: $size + $border;
        height: $size + $border;
        border-radius: 50%;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: var(--bg-color);
        opacity: 0.3;
      }

      .icon {
        font-size: 16px;
        color: #fff;
      }

      .img {
        width: 20px;
        height: 20px;
      }
    }

    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 10px;

      .m {
        font-weight: bold;
      }

      .t {
        font-size: 12px;
        color: #999;
        padding-top: 4px;
      }
    }
  }
}

.refund {
  color: #ff9731;
  font-weight: bold;
}

.table_order_info {
  .order_no {
    color: #999;
  }

  .type {
    color: #e6a23c;
  }
}

.goods_info {
  .row {
    display: flex;

    &:not(:first-child) {
      margin-top: 10px;
    }

    .cover {
      width: 40px;
      height: 40px;
    }

    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 10px;

      .sku {
        color: #999;
      }
    }
  }
}
</style>
