<template>
  <m-card title="勤务分析">
    <div class="nav">
      <div>
        <Tabs :list="tabs" horizontal @select="curTab = $event" />
      </div>
      <div>
        <span
          v-for="option in options"
          :key="option.key"
          :class="{ on: curOption === option.key }"
          @click="curOption = option.key"
        >
          {{ option.name }}
        </span>
      </div>
    </div>
    <div>
      <SubTitle>事件类型</SubTitle>
      <div class="duty-type">
        <div v-if="showChart && pieData.source.length > 0" class="chart">
          <m-pie :dataset="pieData" :option="pieOption" />
        </div>
        <m-empty v-else />
        <div class="legend">
          <div v-for="(item, i) in pieData.source" :key="item.name">
            <p>
              <span :style="{ background: pieOption.color[i] }" />
              {{ item.name }}
            </p>
            <p>
              {{ Math.ceil((item.value / total) * 100).toFixed(0) }}%
              <m-count :value="item.value" />件
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="bar-chart">
      <SubTitle>居委事件数量</SubTitle>
      <div v-if="showChart && barOption.series.length > 0" class="chart">
        <m-bar :dataset="barData" :option="barOption" />
      </div>
      <m-empty v-else />
    </div>
    <div class="rank">
      <SubTitle>分类排行</SubTitle>
      <div v-if="rankList.length > 0" class="content">
        <m-scroll :length="rankList.length" :limit="4">
          <m-progress
            v-for="rank in rankList"
            :key="rank.name"
            :value="rank.rate"
            :msg="rank"
          />
        </m-scroll>
      </div>
      <m-empty v-else />
    </div>
    <div class="place">
      <SubTitle>多发地点</SubTitle>
      <div v-if="placeList.length > 0" class="content">
        <div v-for="item in placeList" :key="item.name">
          <Place :data="item" />
        </div>
      </div>
      <m-empty v-else />
    </div>
  </m-card>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watch } from 'vue'
import Tabs, { TabsProp } from '../components/tabs.vue'
import SubTitle from '../components/sub-title.vue'
import Place, { PlaceProp } from '../components/place.vue'
import store from '@/store'

export default defineComponent({
  name: 'DutyAnalysis',
  components: { Tabs, SubTitle, Place },
  setup() {
    const fontSize = computed(() => Math.floor((screen.height * 1.6) / 100))
    const showChart = computed(() => store.state.curView.type !== 'street')
    const curTab = ref('综合')
    const tabs = ref<TabsProp[]>([
      { name: '综合管理', key: '综合' },
      { name: '街面管理', key: '街面' },
      { name: '小区管理', key: '小区' },
    ])
    const options = ref([
      { name: '日', key: 'day' },
      { name: '周', key: 'week' },
      { name: '月', key: 'month' },
    ])
    const curOption = ref('month')
    watch(
      [() => curTab.value, () => store.state.curView.id],
      ([type, id]) => {
        if (!id) return
        store.dispatch('getDutyRank', {
          gridId: id,
          managementType: type,
        })
        store.dispatch('getDutyEvents', {
          gridId: id,
          managementType: type,
        })
        store.dispatch('getDutyPlaces', {
          gridId: id,
          managementType: type,
        })
        store.dispatch('getDutyRanking', {
          gridId: id,
          managementType: type,
        })
      },
      { immediate: true }
    )

    const rankList = computed(() => {
      const data = store.state.dutyRanking[curOption.value] || []
      const total = data.reduce((acc, cur) => acc + cur.num, 0)
      return data.map((item: any) => ({
        name: item.businsessType || item.businessType,
        rate: +Math.ceil((item.num / total) * 100).toFixed(0),
        value: item.num,
        unit: '件',
      }))
    })
    const placeList = computed(() => {
      const data = store.state.dutyPlaces[curOption.value] || []
      return data.map((item: any) => ({
        name: item.address,
        value: item.num,
        type: '路段',
      }))
    })
    const barData = computed(() => {
      const data = store.state.dutyEvents[curOption.value] || []
      const types: string[] = []
      data.forEach((item: any) =>
        types.push(
          ...item.data.map((e: any) => e.businsessType || e.businessType)
        )
      )
      const dic: any = {}
      const defaultData: any = {}
      const dimensions = [
        { name: 'name', displayName: '居委' },
        ...Array.from(new Set(types)).map((item: string, i: number) => {
          const name = `data${i + 1}`
          dic[item] = name
          defaultData[name] = 0
          return {
            name,
            displayName: item,
          }
        }),
      ]
      return {
        dimensions,
        source: data.map((item: any) => {
          const datas: { [key: string]: unknown } = {}
          item.data.forEach((e: any) => {
            datas[dic[e.businsessType || e.businessType]] = e.num || 0
          })
          return {
            name: item.cmtName,
            ...defaultData,
            ...datas,
          }
        }),
      }
    })
    const barOption = computed(() => ({
      color: ['#5BD5FF', '#6EB629', '#FFCE34', '#FF9D27', '#826AFA'],
      legend: {
        right: '2%',
        left: '10%',
        top: '-2%',
        itemWidth: fontSize.value * 0.6,
        itemHeight: fontSize.value * 0.6,
      },
      grid: { top: '25%', right: '2%' },
      series: [
        ...new Array(barData.value.dimensions.length - 1 || 0).keys(),
      ].map(() => ({
        type: 'bar',
        barWidth: '10%',
        itemStyle: { borderRadius: 8 },
        barGap: 0,
        stack: '总量',
      })),
    }))

    const pieData = computed(() => {
      const data = store.state.dutyRank[curOption.value] || []
      return {
        dimensions: [
          { name: 'name', displayName: '类型' },
          { name: 'value', displayName: '数量' },
        ],
        source: data.map((item: any) => ({
          name: item.businsessType,
          value: item.num,
        })),
      }
    })
    const total = computed(() => {
      if (!pieData.value.source) return 0
      return pieData.value.source.reduce((acc, cur) => acc + cur.value, 0)
    })
    const pieOption = ref({
      color: ['#00BFFF', '#FFCE34', '#826AFA', '#589C20', '#F47C1F'],
      legend: { show: false },
      series: [
        {
          type: 'pie',
          radius: [0, '80%'],
          center: ['40%', '50%'],
          label: {
            show: false,
          },
        },
      ],
    })
    return {
      showChart,
      total,
      curTab,
      tabs,
      options,
      curOption,
      rankList,
      placeList,
      barData,
      barOption,
      pieData,
      pieOption,
    }
  },
})
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.nav
  width 100%
  display flex
  align-items center
  justify-content space-between
  margin .03rem 0
  >div
    width 75%
    &:last-child
      width 20%
      display flex
      >span
        $center()
        width .22rem
        height @width
        color $primary-border
        border .01rem solid @color
        cursor pointer
        &:hover
        &.on
          color $secondary-color
          border-color @color
          background rgba(50,197,255,.2)
.rank
  min-height 1rem
  .content
    height 1rem
    overflow hidden
.place
  .content
    display flex
    justify-content space-between
    >div
      width 32%
      height .6rem
.bar-chart
  height 1.6rem
  .chart
    width 100%
    height 90%
.duty-type
  width 100%
  height .8rem
  display flex
  .chart
    width 25%
    height 100%
  .legend
    display flex
    flex-wrap wrap
    align-items center
    flex 1
    font-size .09rem
    >div
      min-width 32%
      margin-left .03rem
      p
        span
          width .06rem
          height @width
          display inline-block
          margin-right .04rem
          border-radius 50%
        &:last-child
          font-size .08rem
          margin-left .08rem
</style>
