<template>
  <div>
    <header-panel>
      <m-filter :option="filter" :show-btn="false"></m-filter>
      <scroll-tabs :items="list" @handleClick="handleToHref"></scroll-tabs>
      <v-divider></v-divider>
    </header-panel>
    <div class="box pa-3" ref="box" :style="`height: ${height}px;`">
      <div class="d-flex">
        <m-card :title="`城市样本分布 - ${title ? title : '全部'}`" style="flex: 1" v-loading="loading" id="city">
          <low-code :option="option.city" :height="800"></low-code>
        </m-card>
        <div style="width: 12px;"></div>
        <m-card
          :title="`小于十个样本的城市数据 - ${title ? title : '全部'}`"
          class="pb-3"
          style="flex: 1"
          id="citySampleOther"
        >
          <template #title>
            <v-btn text color="primary" :loading="exportLoading" @click="exportAsImage">导出</v-btn>
          </template>
          <m-table
            ref="tableRef"
            :headers="headers"
            :items="citySampleOther"
            :disable-sort="true"
            :loading="loading"
            :is-tools="false"
            :show-select="false"
            :elevation="0"
          ></m-table>
        </m-card>
      </div>

      <div class="d-flex mt-3">
        <m-card :title="`按城市等级样本分布 - ${title ? title : '全部'}`" style="flex: 1" v-loading="loading" id="urbanAgglomeration">
          <low-code :option="option.urbanAgglomeration"></low-code>
        </m-card>
        <div style="width: 12px;"></div>
        <m-card :title="`按城市集群样本分布 - ${title ? title : '全部'}`" style="flex: 1" v-loading="loading" id="cityTier">
          <low-code :option="option.cityTier"></low-code>
        </m-card>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import HeaderPanel from '@/components/ScrollTabs/headerPanel'
import ScrollTabs from '@/components/ScrollTabs'
import MFilter from '@/components/Filter'
import MCard from '@/components/MCard'
import LowCode from '@/charts/lowCode.vue'
import MTable from '@/components/List/table'
import { getStatistics, getCityClassification } from '@/api/report'
export default {
  name: 'sample-statistics',
  components: { MCard, LowCode, MTable, MFilter, HeaderPanel, ScrollTabs },
  data () {
    return {
      exportLoading: false,
      list: [
        { label: '城市样本分布', id: 'city' },
        { label: '小于十个样本的城市数据', id: 'citySampleOther' },
        { label: '按城市等级样本分布', id: 'urbanAgglomeration' },
        { label: '按城市集群样本分布', id: 'cityTier' }
      ],
      filter: {
        list: [
          {
            type: 'select',
            key: 'hotelType ',
            value: null,
            clearable: true,
            label: '样本类型',
            items: ['酒店', '集团办公室'],
            change: this.handleChange
          }
        ]
      },
      option: {
        city: {
          legend: {
            show: false
          },
          tooltip: {
            show: true
          },
          grid: {
            left: 20,
            right: 20,
            top: 20,
            bottom: 20,
            containLabel: true
          },
          xAxis: [
            {
              type: 'value',
              splitLine: {
                show: false
              }
            }
          ],
          yAxis: [
            {
              type: 'category',
              data: [],
              axisLabel: {
                interval: 0
              },
              splitLine: {
                show: false
              }
            }
          ],
          series: [
            {
              type: 'bar',
              stack: 'chart',
              z: 3,
              barMaxWidth: 40,
              label: {
                position: 'right',
                show: true
              },
              data: []
            },
            {
              type: 'bar',
              stack: 'chart',
              barMaxWidth: 40,
              silent: true,
              itemStyle: {
                color: '#eee'
              },
              data: []
            }
          ]
        },
        urbanAgglomeration: {
          series: [
            {
              type: 'pie',
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)'
              },
              data: []
            }
          ]
        },
        cityTier: {
          series: [
            {
              type: 'pie',
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)'
              },
              data: []
            }
          ]
        }
      },
      title: null,
      loading: false,
      height: 100,
      headers: [
        { text: '样本数量', value: 'count', width: 100 },
        { text: '城市', value: 'city' }
      ],
      yAxis: [],
      citySampleOther: [],
      dict: {}
    }
  },
  created () {
    this.initDict()
    this.init()
  },
  mounted () {
    const el = this.$refs.box.getBoundingClientRect()
    this.height = window.innerHeight - el.top - 12
  },
  methods: {
    async initDict () {
      try {
        const { data } = await getCityClassification()
        this.dict = data
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async init () {
      this.loading = true
      try {
        const { data } = await getStatistics({ hotelType: this.title })
        const yAxis = Object.keys(data.citySample).reverse()
        this.option.city.yAxis[0].data = yAxis

        this.yAxis = Object.keys(data.citySample).reverse()
        const list = Object.values(data.citySample)
        const max = Math.max(...list)
        const min = Math.min(...list)
        this.option.city.series[0].data = Object.values(data.citySample).reverse()
        this.option.city.series[1].data = yAxis.map(_e => {
          return {
            label: {
              show: false
            },
            value: max + min - data.citySample[_e]
          }
        })
        this.citySampleOther = Object.keys(data.citySampleOther).reverse().map(key => {
          return {
            count: key,
            city: data.citySampleOther[key]
          }
        })
        this.option.cityTier.series[0].data = Object.keys(data.cityTier).map(key => {
          return {
            name: key,
            value: data.cityTier[key]
          }
        })
        this.option.urbanAgglomeration.series[0].data = Object.keys(data.urbanAgglomeration).map(key => {
          return {
            name: key,
            value: data.urbanAgglomeration[key]
          }
        })
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    handleChange (val) {
      this.title = val
      this.init()
    },
    handleToHref (item) {
      const id = item.id
      const selector = document.getElementById(id)
      if (!selector) return
      this.$refs.box.scrollTo({
        top: selector.offsetTop - this.$refs.box.offsetTop - 12,
        behavior: 'smooth'
      })
    },
    // 不做IE兼容
    async exportAsImage () {
      this.exportLoading = true
      const table = this.$refs.tableRef.$refs.table.$el.childNodes[0].childNodes[0]
      const canvas = await html2canvas(table)
      const image = canvas.toDataURL('image/png')
      const a = document.createElement('a')
      a.href = image
      a.download = 'table_image.png'
      a.click()
      this.exportLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  overflow-y: auto;
  &-content {
    width: 100%;
    height: 1000px;
    position: relative;
    &-table {
      width: 50%;
      height: 40%;
      bottom: 0;
      left: 50px;
      position: absolute;
      overflow: hidden;
    }
    // background: #ccc;
  }
}
.title {
  font-size:18px !important;
  font-family:Microsoft YaHei !important;
  font-weight:bold;
}
</style>
