<template>
  <m-card title="应急物资储备" style="height: 1rem">
    <div class="emergency">
      <div v-for="(item, index) in list" :key="index">
        <m-count class="count orange-count" :value="item.value" />
        <span>处</span>
        <p>{{ item.name }}</p>
      </div>
    </div>
  </m-card>
  <m-card title="房屋外立面">
    <div class="out-house">
      <div class="view-selector">
        <a-select
          :value="year"
          dropdown-class-name="view-selector-drop-down"
          @select="changeYear"
        >
          <a-select-option
            v-for="option in yearOptions"
            :key="option"
            :value="option"
          >
            {{ option }}
          </a-select-option>
        </a-select>
      </div>
      <Summary
        :list="houseSum"
        :avatar="avatar8"
        click-able
        @select="selectBuilding(null)"
      />
      <div class="chart-container">
        <div class="info">
          <div v-for="item in info" :key="item.name">
            <img :src="item.icon" />
            <div>
              <m-count class="count" :value="item.value" />
              <p>{{ item.name }}</p>
            </div>
          </div>
        </div>
        <div v-if="showChart" class="chart">
          <m-bar :option="barOption" />
        </div>
      </div>
      <div class="bottom-box">
        <m-sub2>重点关注楼宇</m-sub2>
        <a class="check-btn" @click="listModal = true">查看清单>></a>
        <div class="content">
          <div v-for="item in buildings" :key="item.id">
            <div>
              <span>{{ item.projectName }}</span>
              <img
                src="@/assets/images/location.png"
                @click="selectBuilding(item)"
              />
            </div>
            <div class="secRow">
              <span>
                <span>隐患 </span>
                <m-count
                  class="count"
                  :value="item.outerWallFacilityHiddenPoint"
                />
              </span>
              <span>
                <span>危险 </span>
                <m-count
                  class="count"
                  :value="item.outerWallFacilityDangerPoint"
                />
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </m-card>
  <m-modal
    v-model="listModal"
    width="40%"
    offset="60%"
    title="重点关注楼宇清单"
    :mask-closable="false"
  >
    <div>
      <m-table
        :template="[
          '楼宇名称|房屋地址*2|检测日期|房屋用途|建造年份|平面形式|建筑面积|结构类别|层数|隐患点|危险点',
          'projectName|houseAddr|inspectionDate|useType|buildYear|planeSituation|constructArea|structureType|floor|outerWallFacilityHiddenPoint|outerWallFacilityDangerPoint',
        ]"
        :data="buildings"
      />
    </div>
  </m-modal>
</template>

<script lang="ts">
import { defineComponent, watch, computed, ref } from 'vue'
import store from '@/store'
import Summary from '../components/summary.vue'
import avatar8 from '@/assets/images/avatar8.png'
import one from '@/assets/images/1.png'
import two from '@/assets/images/2.png'
import three from '@/assets/images/3.png'
import { ajax, api } from '@/ajax'
import emergencyIcon from '@/assets/images/a7.png'

export default defineComponent({
  name: 'EmergencyStore',
  components: { Summary },
  setup() {
    const showChart = computed(() => store.state.curTheme === 'safety')
    const listModal = ref(false)
    const SOSMaterail = computed(() => store.state.pubulicSafeSOSMaterail)
    const pieData = computed(() => store.state.pubulicSafePieData)
    const outHouseWall = computed(() => store.state.pubulicSafeOutHouseWall)

    const year = ref('2020') //年份
    const yearOptions = ref(['2020', '2019']) //年份option
    const houseSum = ref([
      { name: '检查楼数', value: 0 },
      { name: '隐患点数', value: 0 },
      { name: '危险点数', value: 0 },
    ])

    const pubulicSafeBuildings = computed(
      () => store.state.pubulicSafeBuildings
    )
    const buildings = computed(() =>
      pubulicSafeBuildings.value.filter((e: any) => e.year === year.value)
    )
    const locations = ref<any>({})
    watch(
      () => pubulicSafeBuildings.value,
      async (list) => {
        if (list.length === 0) return
        const ids = list
          .map((item: any) => (item && item.sectId) || '')
          .join(',')
        const { content } = (
          await ajax.get({
            url: api.GET_COMMUNITY,
            params: { pageSize: 1000, sectId_in: ids },
          })
        ).data
        if (content && content.length > 0) {
          const obj: any = {}
          content.forEach((item: any) => {
            obj[item.sectId] = {
              x: item.maxx || item.minx,
              y: item.maxy || item.miny,
            }
          })
          locations.value = obj
        }
      },
      { immediate: true }
    )
    const emergencyPoints = computed(() => store.state.emergencyPoints)
    const selectBuilding = async (data: any) => {
      let points = buildings.value.map((item: any) => ({
        ...(locations.value[item.sectId] || {}),
        ...item,
        icon: emergencyIcon,
      }))
      points = [points.find((e: any) => e.id === data.id)]
      // if (data) {
      //   if (!data.sectId) return
      //   if (emergencyPoints.value.length > 0) {
      //     points.find((e: any) => e.sectId === data.sectId).size = 22
      //   } else {
      //     points = [points.find((e: any) => e.sectId === data.sectId)]
      //   }
      // }
      points = await Promise.all(
        points.map(async (item) => {
          const { x, y } =
            (
              await ajax.get({
                url: api.GET_BUILDING,
                params: { sectId: item?.sectId },
              })
            )?.data?.content?.[0] || {}
          item.x = x
          item.y = y
          return item
        })
      )
      store.commit('SET_EMERGENCY_POINTS', points)
    }

    //切换年份
    const changeYear = (value: string) => {
      year.value = value
    }

    const list = computed(() => {
      return [
        {
          value: SOSMaterail.value.floodPreventionUnits || 0,
          name: '防汛防台',
        },
        {
          value: SOSMaterail.value.warmAntifreeze || 0,
          name: '防寒抗冻',
        },
        {
          value: SOSMaterail.value.emergencySupplies || 0,
          name: '疫情控制',
        },
        {
          value: SOSMaterail.value.emergencyRescue || 0,
          name: '应急抢险',
        },
      ]
    })

    const population = ref([
      { name: '楼宇名称', value: 4, danger: 1 },
      { name: '楼宇名称', value: 4, danger: 1 },
      { name: '楼宇名称', value: 4, danger: 1 },
      { name: '楼宇名称', value: 4, danger: 1 },
      { name: '楼宇名称', value: 4, danger: 1 },
      { name: '楼宇名称', value: 4, danger: 1 },
    ])

    const info = ref([
      { name: '第一工作站', value: 0, icon: one },
      { name: '第二工作站', value: 0, icon: two },
      { name: '第三工作站', value: 0, icon: three },
    ])

    watch(
      // 监听年份切换更改检查楼数  隐患点数 危险点数
      [() => outHouseWall.value, () => year.value],
      ([data, year]) => {
        if (data.length === 0) return
        const { checkNum = 0, hiddenPoint = 0, dangerPoint = 0 } = data.find(
          (e: any) => e.year === year
        )
        houseSum.value = [
          { name: '检查楼数', value: checkNum },
          { name: '隐患点数', value: hiddenPoint },
          { name: '危险点数', value: dangerPoint },
        ]
      },
      { immediate: true }
    )

    const keys = [
      'outerWallHiddenPoint',
      'outerWallDangerPoint',
      'outerWallFacilityHiddenPoint',
      'outerWallFacilityDangerPoint',
    ]
    const barData = ref<any[]>([])
    const barOption = computed(() => ({
      color: ['#5BD5FF', '#6BE1B2', '#FF9500'],
      legend: { show: false },
      xAxis: [
        {
          type: 'category',
          axisTick: { show: false },
          data: keys.map((key) => getTypeName(key)),
          axisLabel: {
            interval: 0,
            formatter: (value: string) => {
              const i = Math.ceil(value.length / 2) || 0
              return value.slice(0, i) + '\n' + value.slice(i)
            },
          },
        },
      ],
      series: barData.value.map((item) => ({
        name: item.workstationName,
        type: 'bar',
        barWidth: '14%',
        barGap: '50%',
        data: keys.map((key: string) => item[key] || 0),
      })),
    }))
    function getTypeName(type: string) {
      switch (type) {
        case 'outerWallHiddenPoint':
          return '外墙面层隐患点'
        case 'outerWallDangerPoint':
          return '外墙面层危险点'
        case 'outerWallFacilityHiddenPoint':
          return '外立面附加设施隐患点'
        case 'outerWallFacilityDangerPoint':
          return '外立面附加设施危险点'
        default:
          return ''
      }
    }
    watch(
      [() => pieData.value, () => year.value],
      ([data, year]) => {
        if (data.length === 0) return
        const curData = data.filter((item: any) => item.year === year)
        const first: any = curData.find((item: any) =>
          item.workstationName.includes('第一')
        )
        const second: any = curData.find((item: any) =>
          item.workstationName.includes('第二')
        )
        const third: any = curData.find((item: any) =>
          item.workstationName.includes('第三')
        )
        barData.value = [first, second, third]
        // // 将第二张饼图的数据更新
        info.value = [
          {
            name: '第一工作站',
            value: keys.reduce((acc, cur) => acc + first[cur], 0) || 0,
            icon: one,
          },
          {
            name: '第二工作站',
            value: keys.reduce((acc, cur) => acc + second[cur], 0) || 0,
            icon: two,
          },
          {
            name: '第三工作站',
            value: keys.reduce((acc, cur) => acc + third[cur], 0) || 0,
            icon: three,
          },
        ]
      },
      { immediate: true }
    )

    return {
      avatar8,
      list,
      houseSum,
      listModal,
      population,
      info,
      showChart,
      changeYear,
      year,
      yearOptions,
      SOSMaterail,
      buildings,
      outHouseWall,
      pieData,
      barOption,
      selectBuilding,
    }
  },
})
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'

.emergency
  display flex
  align-items center
  justify-content space-between
  height 80%
  >div
    text-align center
    width 20%
    .count
      font-family $font-barlow
      font-size .14rem
    span
      font-size .08rem
      color #ccc
.out-house
  flex 1
  .chart-container
    height 1.8rem
    display flex
    .info
      flex 1
      display flex
      flex-direction column
      justify-content space-around
      >div
        display flex
        align-items center
        img
          width .3rem
          margin-right .05rem
        .count
          font-size .12rem
          font-family $font-barlow
    .chart
      width 75%
      height 100%
  .bottom-box
    position relative
    margin-top .1rem
    .check-btn
      position absolute
      right .1rem
      top 0
      transform translateY(14%)
    .content
      display flex
      flex-wrap wrap
      overflow-y auto
      max-height 27vh
      >div
        width 31%
        padding .05rem .08rem
        margin-top .08rem
        margin-right .06rem
        border-radius .03rem
        background linear-gradient(to right bottom, rgba(124,139,154,.3), rgba(70,83,97,.3))
        box-shadow 0 0 .4rem 0 rgba(45,51,66,.5)
        .count
          font-size 0.12rem
          font-family $font-barlow
        >div
          display flex
          align-items center
          justify-content space-between
          img
            width 0.1rem
            height @width
            cursor pointer
            &:hover
              transform scale(1.2)
        .secRow
          >span
            display flex
            align-items center
            color #ccc
            &:last-child
              .count
                color #FF5C5C
            .count
              color #fff
              margin-left .05rem
  .view-selector
    float right
    height 8%
    padding 0.03rem 0
</style>
