<template>
  <div class="dashboard-container" ref="dashboardContainerRef" v-loading="isLoading">
    <!-- 顶部的地区和店铺筛选 -->
    <div class="total-search">
      <div class="wrapper">
        <el-form ref="topSearchFormRef" inline :model="topSearchForm">
          <el-form-item label="代理商">
            <el-select :popper-append-to-body="false" @change="handleChangeTopSelect('agents')" v-model="topSearchForm.agents" class="select" placeholder="请选择代理商">
              <el-option
                style="height: auto !important; line-height: 1.1; padding: 5px 15px; margin: 2px 0"
                v-for="(item, index) in selectOptions.agents"
                :key="`${item.shopAddress}:${index}`"
                :label="item.shopName"
                :value="`${item.shopAddress}:${index}`"
              >
                <div style="font-size: 14px; font-weight: bold; margin-bottom: 7px; color: black">{{ item.shopName }}</div>
                <div style="height: auto !important; line-height: 1.1; margin: 2px 0">{{ item.shopAddress }}</div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="加盟商">
            <el-select @change="handleChangeTopSelect('franchise')" v-model="topSearchForm.franchise" class="select" placeholder="请选择加盟商">
              <el-option
                style="height: auto !important; line-height: 1.1; padding: 5px 15px; margin: 2px 0"
                v-for="(item, index) in selectOptions.franchise"
                :key="`${item.shopAddress}:${index}`"
                :label="item.shopName"
                :value="`${item.shopAddress}:${index}`"
              >
                <div style="font-size: 14px; font-weight: bold; margin-bottom: 7px; color: black">{{ item.shopName }}</div>
                <div style="height: auto !important; line-height: 1.1; margin: 2px 0">{{ item.shopAddress }}</div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商家">
            <el-select @change="handleChangeTopSelect('shop')" class="select" v-model="topSearchForm.shop" placeholder="请选择商家">
              <el-option v-for="(item, index) in selectOptions.shopList" :key="`${item.shopName}:${index}`" :label="item.shopName" :value="`${item.shopName}:${index}`"></el-option>
            </el-select>
          </el-form-item>

          <el-button class="btn" type="primary" size="default" @click="getHomeData">筛选</el-button>
          <el-button class="btn" size="default" @click="handleResetForm">重置</el-button>
        </el-form>
      </div>
    </div>

    <!-- 统计区域 -->
    <!-- <StatisticsPanel :filters="['address']" title="统计区" @change="handleStatisticsAreaFilterChnage"> -->
    <StatisticsPanel title="统计区" @change="handleStatisticsAreaFilterChnage">
      <div ref="statisticalAreaRef" class="statistics-container">
        <StatisticsSection
          @change="handleFilterChange"
          class="statistics-container-item"
          style="flex-basis: calc((100% - 32px) / 3)"
          :style="{
            margin: [1, 4].includes(index) ? '0 16px' : '',
            'margin-bottom': index <= 2 ? '16px' : 0
          }"
          v-for="(item, index) in statisticalArea"
          :key="item.label + index"
          :meta="item"
          :itemData="statisticalRegionData[item.itemData]"
        ></StatisticsSection>
      </div>
    </StatisticsPanel>

    <!-- 消费画像，财务统计 -->
    <div class="section">
      <StatisticsPanel class="consumer-profile-wrapper" title="消费画像">
        <!-- <template #button>
          <el-button type="text">
            消费画像
            <i class="el-icon-arrow-right el-icon--right"></i>
          </el-button>
        </template> -->
        <div class="consumer-profile-container">
          <TrendPanel class="item" v-for="item in consumerProfile" :key="item.label" :label="item.label" :value="memberConsumptionStatistics[item.field]" :style="item.itemStyles"></TrendPanel>
        </div>
      </StatisticsPanel>
      <!-- <StatisticsPanel class="financial-statistics-wrapper" title="财务统计" :filters="['date']" @change="handleFinancialStatisticsFilterChange"> -->
      <StatisticsPanel class="financial-statistics-wrapper" title="财务统计" @change="handleFinancialStatisticsFilterChange">
        <div class="financial-statistics-container">
          <TrendPanel class="item" v-for="item in financialStatistics" :key="item.label" :label="item.label" :value="financeStatistics[item.field]" :style="item.itemStyles"></TrendPanel>
        </div>
      </StatisticsPanel>
    </div>

    <!-- 图表区 -->
    <div class="charts-container">
      <div class="left">
        <!-- <StatisticsPanel :filters="['address', 'sourceChannel']" title="分析图" @change="handleAnalysisChartFilterChange"> -->
        <StatisticsPanel title="分析图" @change="handleAnalysisChartFilterChange">
          <template #button>
            <button @click="currentAnalysisTab = 1" :class="{ active: currentAnalysisTab === 1 }" class="analysis-chart-btn">交易额</button>
            <button @click="currentAnalysisTab = 2" :class="{ active: currentAnalysisTab === 2 }" class="analysis-chart-btn">订单量</button>
            <button @click="currentAnalysisTab = 3" :class="{ active: currentAnalysisTab === 3 }" class="analysis-chart-btn">会员量</button>
          </template>
          <AnalysisChart ref="analysisChartRef" :chartData="diagramsData"></AnalysisChart>
        </StatisticsPanel>

        <div class="left-footer">
          <!-- <StatisticsPanel style="width: 50%" :filters="['address']" title="物流统计" @change="handlelLogisticsStatisticsChartFilterChange"> -->
          <StatisticsPanel style="width: 50%" title="物流统计" @change="handlelLogisticsStatisticsChartFilterChange">
            <LogisticsStatisticsChart :chartData="logisticsStatistics" ref="lLogisticsStatisticsChartRef"></LogisticsStatisticsChart>
          </StatisticsPanel>
          <StatisticsPanel style="width: 50%" title="商品排名">
            <template #button>
              <div class="goods-ranking-btn-wrapper">
                <button @click="currentGoodsRankingTab = 1" :class="{ active: currentGoodsRankingTab === 1 }" class="analysis-chart-btn">社区</button>
                <button @click="currentGoodsRankingTab = 2" :class="{ active: currentGoodsRankingTab === 2 }" class="analysis-chart-btn">商圈</button>
                <button @click="currentGoodsRankingTab = 3" :class="{ active: currentGoodsRankingTab === 3 }" class="analysis-chart-btn">商城</button>
              </div>
            </template>
            <GoodsRankingChart :chartData="goodsRankingData" ref="goodsRankingChartRef"></GoodsRankingChart>
          </StatisticsPanel>
        </div>
      </div>
      <div class="right">
        <!-- <StatisticsPanel :filters="['address']" title="网点统计" style="width: 100%; height: 860px; display: flex; flex-direction: column" @change="handleSiteFilterChange"> -->
        <StatisticsPanel title="网点统计" style="width: 100%; height: 860px; display: flex; flex-direction: column" @change="handleSiteFilterChange">
          <div class="data-statistics">
            <StatisticsItem class="item" v-for="item in sitedatastatistics" :key="item.label" :title="item.label" :value="dotStatistics[item.field] || 0" :style="item.itemStyles"></StatisticsItem>
          </div>
          <div class="map-pie-container">
            <SiteMapChart :chartData="nationalMapList" class="map-chart" ref="siteMapChartRef"></SiteMapChart>
            <SitePieChart :chartData="dotStatistics" class="pie-chart" ref="sitePieChartRef"></SitePieChart>
          </div>
        </StatisticsPanel>
      </div>
    </div>

    <PAndLWarning></PAndLWarning>
    <!-- 设置盈亏红线 -->
    <SetPLLine></SetPLLine>
  </div>
</template>

<script>
import * as _ from 'lodash'
import axios from 'axios'
import { getHomeStatisticsData, getHomeStatisticsShopList } from '@/api/home'
import { getDefaultBarData } from './utils/echarts'
import StatisticsPanel from './componets/StatisticsPanel.vue'
import AddresSelect from './componets/AddresSelect.vue'
import DateSelect from './componets/DateSelect.vue'
import StatisticsSection from './componets/StatisticsSection'
import TrendPanel from './componets/TrendPanel.vue'
import AnalysisChart from './componets/AnalysisChart.vue'
import LogisticsStatisticsChart from './componets/LogisticsStatisticsChart.vue'
import GoodsRankingChart from './componets/GoodsRankingChart.vue'
import StatisticsItem from './componets/StatisticsItem.vue'
import SiteMapChart from './componets/SiteMapChart.vue'
import SitePieChart from './componets/SitePieChart.vue'
import PAndLWarning from './componets/PAndLWarning.vue'
import SetPLLine from './componets/SetPLLine.vue'

import { statisticalArea, consumerProfile, financialStatistics, sitedatastatistics, searchType } from './data/dashboard.js'

// api docs: https://www.showdoc.com.cn/2275703555064913/11472635245710770
export default {
  components: {
    SetPLLine,
    PAndLWarning,
    StatisticsPanel,
    AddresSelect,
    StatisticsSection,
    TrendPanel,
    AnalysisChart,
    LogisticsStatisticsChart,
    GoodsRankingChart,
    StatisticsItem,
    SiteMapChart,
    SitePieChart,
    DateSelect
  },
  data() {
    return {
      observer: null,
      isLoading: false,
      statisticalArea: Object.freeze(statisticalArea),
      consumerProfile: Object.freeze(consumerProfile),
      financialStatistics: Object.freeze(financialStatistics),
      sitedatastatistics: Object.freeze(sitedatastatistics),
      totalSearch: {
        selectAddress: 1,
        selectShop: 1
      },
      topSearchForm: {
        agents: undefined,
        shop: undefined,
        franchise: undefined,
        type: undefined
      },
      dymicStyle: {
        siteContainerHeight: '891px',
        statisticalAreaItemWidth: '32%'
      },
      selectOptions: {
        addressSelectOptions: [
          { label: '佛山市', value: 1 }
          // { label: '乌鲁木齐市', value: 2 }
        ],
        shopListOptions: [
          { label: '全部', value: 1 }
          // { label: '文智瑜沙雕皮业', value: 2 }
        ],
        dateOptions: [
          // { label: '今天', value: 1 },
          // { label: '近一周', value: 2 },
          // { label: '近一月', value: 3 },
          // { label: '近一年', value: 4 }
        ],
        sourceChannelOptions: [
          // { label: '社区', value: 1 },
          // { label: '商圈', value: 2 },
          // { label: '商城', value: 3 }
        ],

        shopList: [], // 商家列表
        agents: [], // 代理商列表
        franchise: [] // 加盟商列表
      },

      // 分析图相关
      currentAnalysisTab: 1, // 交易额1，订单量2，会员量3

      // 销售排名
      currentGoodsRankingTab: 1, // 社区1，商圈2，商城3

      /* 数据区域 */

      statisticalRegionData: {
        memberStatistics: {
          // 会员统计
          memberTotal: 0, //会员总数
          normalMemberTotal: 0, // 普通会员数量
          headquarterTotal: 0, // 团长数量
          partnerTotal: 0, // 合伙人数量
          todayMember: 0 // 今日新增会员数
        },
        orderStatistics: {
          // 订单统计
          orderTotal: 0, // 订单总数
          todayOrderTotal: 0, // 今日订单量
          todayFinishOrderTotal: 0 // 今日完成订单
        },

        platformTransactionDataStatistics: {
          // 平台交易数据统计
          totalTransactionAmount: 0, // 总交易额
          todayTransactionAmount: 0, // 今日交易额
          totalExpense: 0, // 总支出
          totalIncome: 0 // 总输入
        },

        voucherStatistics: {
          // 平台代金券统计
          voucherTotal: 0, // 总库存
          voucherStock: 0, // 新增库存
          todayVoucherUseTotal: 0, // 今日使用量
          todayRealAmount: 0, // 今日使用量
          todayRechargeTotal: 0 // 今日充值量
        },

        commissionStatistics: {
          // 佣金统计
          totalIncome: 0, // 累计收入佣金
          todayTotalIncome: 0, // 今日总收入佣金
          headquarterCommission: 0, // 团长佣金分配总额
          partnerCommission: 0, // 合伙人佣金分配总额
          joinCommission: 0, // 加盟商佣金分配总额
          agentCommission: 0 // 代理商佣金分配总额
        },

        consumptionStatistics: {
          // 消费金统计
          totalIncome: 0, // 消费金总收入
          totalConsumption: 0, // 消费金总支付
          todayConsumptionOrderAmount: 0, //今日消费金支出订单金额
          todayConsumptionOrderTotal: 0 //今日消费金支付订单数
        }
      },

      // 消费画像
      memberConsumptionStatistics: {
        memberConsumptionTotal: 0, // 会员消费总额
        memberOrderTotal: 0, // 会员总下单次数
        memberAfterSaleTotal: 0 // 会员总售后次数
      },

      // 财务统计
      financeStatistics: {
        receivableAmount: 0, // 应收金额
        discountAmount: 0, // 优免金额
        realAmount: 0, // 实收金额
        customerFlow: 0, // 客流量
        profitLossRate: 0 // 盈亏达成率
      },

      // 分析图数据
      analysisChartStatistics: {
        memberQuantity: getDefaultBarData(), // 会员量
        orderQuantity: getDefaultBarData(), // 订单量
        transactionAmount: getDefaultBarData() // 交易额
      },

      // 商品排名
      goodsRanking: {
        community: [],
        shop: [],
        businessDistrict: []
      },

      // 物流统计
      logisticsStatistics: {
        totalAmount: 0,
        totalQuantity: 0
      },

      // 网点统计
      dotStatistics: {
        masterWorkerQuantity: 0 // 师傅数量
      },

      nationalMapList: []
    }
  },

  provide() {
    return {
      addressList: this.selectOptions.addressSelectOptions,
      dateList: this.selectOptions.dateOptions,
      sourceChannelList: this.selectOptions.sourceChannelOptions
    }
  },

  created() {
    this.getFranchiseesOrAgents(1)
    this.getFranchiseesOrAgents(2)
    this.getShopList()
  },

  mounted() {
    this.getHomeData()
    this.observeContainerSize()
  },

  methods: {
    // 获取代理商或者加盟商列表 1=代理商 2=加盟商
    async getFranchiseesOrAgents(type = 1) {
      try {
        const res = await axios.get(`${process.env.VUE_APP_LAOA_BASE_API}/api/hz/shop/third/getShopsByType`, {
          params: { type, shopName: '' }
        })
        const target = type === 1 ? 'agents' : 'franchise'
        this.selectOptions[target] = res.status === 200 && res.data.statusCode === 20000 ? res.data.data : []
      } catch (error) {
        console.error('Error fetching data:', error)
        const target = type === 1 ? 'agents' : 'franchise'
        this.selectOptions[target] = []
      }
    },

    // 获取商家列表
    async getShopList() {
      try {
        const res = await getHomeStatisticsShopList()
        this.selectOptions.shopList = res.data
      } catch (error) {
        this.selectOptions.shopList = []
      }
    },

    // 一次性获取首页数据
    async getHomeData() {
      this.isLoading = true
      try {
        const type = this.topSearchForm.type
        let address = undefined
        if (type) {
          address = this.topSearchForm[searchType.find((item) => item.value === type).key]
          if (address) {
            address = address.split(':')[0]
          }
        }

        const res = await getHomeStatisticsData({
          type: type || null,
          address
        })
        const { data } = res

        Object.assign(this.statisticalRegionData.memberStatistics, data.memberStatistics, data.memberStatistics.memberIncreaseRate)
        Object.assign(this.statisticalRegionData.orderStatistics, data.orderStatistics)
        Object.assign(this.statisticalRegionData.platformTransactionDataStatistics, data.platformTransactionDataStatistics)
        Object.assign(this.statisticalRegionData.voucherStatistics, data.voucherStatistics)
        Object.assign(this.statisticalRegionData.commissionStatistics, data.commissionStatistics)
        Object.assign(this.statisticalRegionData.consumptionStatistics, data.consumptionStatistics)
        Object.assign(this.memberConsumptionStatistics, data.memberConsumptionStatistics)
        Object.assign(this.analysisChartStatistics, data.analysisChartStatistics)
        Object.assign(this.logisticsStatistics, data.logisticsStatistics)

        // 商品排名
        const { mallProductStatisticsTotalList, communityProductStatisticsTotalList, businessDistrictProductStatisticsTotalList } = data.goodsSortStatistics
        this.goodsRanking.community = communityProductStatisticsTotalList
        this.goodsRanking.shop = mallProductStatisticsTotalList
        this.goodsRanking.businessDistrict = businessDistrictProductStatisticsTotalList

        // 网点统计
        this.dotStatistics = {
          ...data.dotStatistics,
          ...this.statisticalRegionData.memberStatistics
        }
        // 地图数据
        this.nationalMapList = data.nationalMapList
      } catch (error) {
      } finally {
        this.isLoading = false
      }
    },

    // 最上面的搜索区域发生变化
    handleChangeTotalSearchAddress(addressInfo) {
      const { label, value } = addressInfo
      this.totalSearch.selectAddress = value
    },

    // 监听容器变化重新渲染图标
    observeContainerSize() {
      const _this = this
      this.observer = new ResizeObserver(
        _.debounce(() => {
          _this.$refs.analysisChartRef.resize()
          _this.$refs.lLogisticsStatisticsChartRef.resize()
          _this.$refs.goodsRankingChartRef.resize()
          _this.$refs.siteMapChartRef.resize()
          _this.$refs.sitePieChartRef.resize()
        }, 500)
      )
      this.observer.observe(this.$refs.dashboardContainerRef)
    },

    handleResetForm() {
      this.topSearchForm = {
        agents: undefined,
        shop: undefined,
        franchise: undefined,
        type: undefined
      }
      this.getHomeData()
    },

    // 统计区域的筛选发生变化
    handleStatisticsAreaFilterChnage(form) {
      console.log('统计区域的筛选发生变化', form)
    },

    // 财务统计筛选发生变化
    handleFinancialStatisticsFilterChange(form) {
      console.log('财务统计区域筛选发生变化', form)
    },

    // 分析图区域筛选发生变化
    handleAnalysisChartFilterChange(form) {
      console.log('分析图区域筛选发生变化', form)
    },

    // 物流统计区域筛选发生变化
    handlelLogisticsStatisticsChartFilterChange(form) {
      console.log('物流统计区域筛选发生变化', form)
    },

    // 网点统计筛选区域发生变化
    handleSiteFilterChange(form) {
      console.log('网点统计筛选区域发生变化', form)
    },

    // 二级区域的筛选发生变化
    handleFilterChange(label, data) {
      console.log('二级区域发生变化了', label, data)
    },

    handleChangeTopSelect(currentKey) {
      for (const key in this.topSearchForm) {
        if (Object.hasOwnProperty.call(this.topSearchForm, key) && currentKey !== key) {
          this.topSearchForm[key] = undefined
        }
      }

      this.topSearchForm.type = searchType.find((item) => item.key === currentKey).value || null
    }
  },

  computed: {
    // 分析图数据
    diagramsData() {
      return this.analysisChartStatistics[{ 1: 'transactionAmount', 2: 'orderQuantity', 3: 'memberQuantity' }[this.currentAnalysisTab]]
    },

    // 商品排名数据
    goodsRankingData() {
      return this.goodsRanking[{ 1: 'community', 2: 'businessDistrict', 3: 'shop' }[this.currentGoodsRankingTab]]
    }
  },

  beforeDestroy() {
    if (this.observer) {
      this.observer.unobserve(this.$refs.dashboardContainerRef)
      this.observer = null
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  @media (max-width: 1540px) {
    &-item {
      flex-basis: calc((100% - 16px) / 2) !important;
      margin: 0 16px 16px 0 !important;

      &:nth-child(2n) {
        margin-right: 0 !important;
      }
    }
  }

  @media (max-width: 1340px) {
    display: block;
    &-item {
      margin: 0 0 16px !important;
    }
  }
}

.section {
  display: flex;

  .consumer-profile-wrapper {
    flex: 325;
    margin-right: 24px;
  }

  .financial-statistics-wrapper {
    flex: 481;
  }

  .consumer-profile-container,
  .financial-statistics-container {
    display: flex;
    justify-content: space-between;
  }

  @media (max-width: 1390px) {
    display: block;

    .consumer-profile-wrapper,
    .financial-statistics-wrapper {
      width: 100%;
    }

    .financial-statistics-container {
      display: flex;

      .item {
        flex: 1;
      }
    }
  }

  @media (max-width: 730px) {
    .financial-statistics-container {
      display: flex;
      flex-wrap: wrap;

      .item {
        flex: 0 0 48%;
        margin-right: 0 !important;
        margin-bottom: 20px !important;
      }
    }
  }

  @media (max-width: 570px) {
    .consumer-profile-container {
      display: flex;
      flex-wrap: wrap;

      .item {
        flex: 0 0 48%;
        margin-right: 0 !important;
        margin-bottom: 20px !important;
      }
    }
  }
}

.dashboard-container {
  width: 100%;
  height: calc(100vh - 50px);
  background-color: #f4f7fc;
  padding: 24px;
  box-sizing: border-box;
  overflow: auto;

  .total-search {
    min-height: 72px;
    background-color: #fff;
    padding: 16px 24px;
    box-sizing: border-box;

    .wrapper {
      ::v-deep .el-form-item__label {
        font-size: 16px;
        font-weight: normal;
        padding-right: 16px;
      }

      .el-form-item {
        margin-right: 24px;
      }

      .select {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
      }

      .btn {
        height: 40px;
        width: 96px;
        font-size: 16px;
        font-weight: 500;
        &.el-button--default {
          border: 1px solid #dcdfe6;
        }
        &.el-button--primary {
          background-color: #3a68f2;
          border: none;

          &:hover {
            background-color: rgba($color: #3a68f2, $alpha: 0.8);
          }
        }
      }
    }
  }

  .charts-container {
    display: flex;
    justify-content: space-between;
    width: 100%;

    @media (max-width: 1373px) {
      display: block;

      .left,
      .right {
        width: 100% !important;
      }
    }

    @media (max-width: 875px) {
      .left-footer {
        display: block !important;

        ::v-deep .statistics-panel-container {
          width: 100% !important;
        }
      }
    }

    .left {
      width: 60%;
      margin-right: 24px;

      .analysis-chart-btn {
        font-size: 14px;
        color: #424e66;
        line-height: 1.5;
        padding: 3px 12px;
        cursor: pointer;
        margin-left: 16px;
        background-color: transparent;

        &.active {
          color: #0519d4;
          background-color: #f1f4ff;
          border-radius: 4px;
        }

        @media (max-width: 1540px) {
          font-size: 12px;
          padding: 2px 8px;
          margin-right: 0;
        }
      }

      .left-footer {
        display: flex;
      }
    }

    .right {
      /* flex: 1; */
      width: 40%;
      .data-statistics {
        display: flex;
        align-items: center;

        .item {
          @media (max-width: 1540px) {
            margin-right: 30px !important;
          }

          @media (max-width: 1317px) {
            margin-right: 51px !important;
          }
        }
      }

      .map-pie-container {
        flex: 1;
        display: flex;
        align-items: center;
        flex-direction: column;

        .map-chart {
          flex: 1;
          width: 100%;
        }

        .pie-chart {
          width: 100%;
        }
      }
    }
  }
}

.memberIncreaseRate-tooltip {
  .item {
    display: flex;
    align-items: center;
    line-height: 1.5;
    font-size: 14px;

    div {
      &:nth-child(2) {
        font-weight: bold;
        color: #f40;
      }
    }
  }
}
</style>
