<template>
  <cs-page :selected="0" title="智慧生态" isTab>
    <view class="view-container">
      <van-dropdown-menu safe-area-tab-bar active-color="#17C653">
        <van-dropdown-item
          :value="queryParams.deptId"
          :options="getDropdownOption('dept')"
          @change="
            v => {
              querySelect(v, 'deptId')
            }
          "
        />
        <van-dropdown-item
          :value="queryParams.selectWeek"
          :options="getDropdownOption('select_week')"
          @change="
            v => {
              querySelect(v, 'selectWeek')
            }
          "
        />
      </van-dropdown-menu>
      <scroll-view
        :scroll-y="true"
        :style="{ maxHeight: `${viewHeigth}px` }"
        class="view"
        :refresher-enabled="true"
        @refresherrefresh="refresherrefresh"
        :refresher-triggered="refresherTriggered"
        @refresherpulling="refresherpulling"
      >
        <view class="box row-1">
          <view class="wd-flex" style="justify-content: space-around">
            <view
              class="wd-flex wd-flex-col wd-flex-center"
              style="gap: 4px"
            >
              <u-count-to
                :start-val="0"
                :end-val="detail.taskCount"
                bold
                font-size="24"
                color="#071437"
              ></u-count-to>
              <view class="">任务数量</view>
            </view>
            <view
              class="wd-flex wd-flex-col wd-flex-center"
              style="gap: 4px"
            >
              <u-count-to
                :start-val="0"
                :end-val="detail.inspectionsCount"
                bold
                font-size="24"
                color="#071437"
              ></u-count-to>
              <view class="">执法记录</view>
            </view>
            <view
              class="wd-flex wd-flex-col wd-flex-center"
              style="gap: 4px"
            >
              <u-count-to
                :start-val="0"
                :end-val="detail.enterpriseCount"
                bold
                font-size="24"
                color="#071437"
              ></u-count-to>
              <view class="">企业数量</view>
            </view>
          </view>
          <qiun-data-charts
            type="ring"
            :opts="opts"
            :chartData="chartData"
            :canvas2d="true"
            style="height: 144px"
          ></qiun-data-charts>
          <view class="wd-flex" style="gap: 12px; flex-wrap: wrap">
            <view
              class="wd-flex wd-flex-col wd-flex-center"
              v-for="item in detail.legendData"
              :key="item"
              style="
                border: 1px solid #f9f9f9;
                width: calc(100% / 3 - 8px);
                padding: 12px;
                gap: 4px;
                border-radius: 4px;
              "
            >
              <view class="wd-flex wd-flex-col" style="gap: 4px">
                <view
                  class="wd-flex"
                  style="align-items: center; gap: 4px"
                >
                  <view
                    :style="{
                      width: '8px',
                      height: '4px',
                      borderRadius: '4px',
                      backgroundColor: item.color
                    }"
                  ></view>
                  <view class="">{{ item.name }}</view>
                </view>
                <view class="wd-flex wd-flex-center">
                  <u-count-to
                    :start-val="0"
                    :end-val="Number(item.value)"
                    bold
                    font-size="16"
                    color="#071437"
                  ></u-count-to>
                  %
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="box row-1">
          <view
            class="wd-flex"
            style="margin-top: 12px; justify-content: center"
          >
            <view
              style="
                background-color: #f9f9f9;
                display: inline-flex;
                padding: 4px;
              "
            >
              <view
                class="tab"
                v-for="(item, index) in tabs"
                :key="index"
                :style="{
                  '--index': tabs.findIndex(
                    i => i.type == queryParams.type
                  )
                }"
                @tap="changeTab(item.type)"
              >
                <view
                  class="name"
                  :style="{
                    color:
                      queryParams.type == item.type ? '#071437' : '#78829d'
                  }"
                >
                  {{ item.name }}
                </view>
              </view>
            </view>
          </view>
          <view style="min-height: 220px">
            <view
              v-for="(item, index) in list"
              :key="index"
              class="wd-flex"
              style="justify-content: space-between; padding: 12px"
            >
              <view class="wd-font-800">{{ item.name }}</view>
              <view class="wd-font-800" style="color: #ff6f1e">
                <view>
                  <u-count-to
                    :start-val="0"
                    :end-val="item.count"
                    bold
                    font-size="14"
                    color="#FF6F1E"
                  ></u-count-to>
                  <text>{{ queryParams.type == 1 ? '天' : '次' }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </cs-page>
</template>

<script>
import { getDictBatchByType, getDeptTree } from '@/api/system/dict.js'
import { HomeApi } from '@/api/common/home.js'
export default {
  data() {
    return {
      dictMap: {},
      queryParams: {
        selectWeek: '',
        deptId: '',
        type: 1
      },
      detail: {},
      opts: {},
      chartData: {},
      viewHeigth: 0,
      tabs: [
        {
          name: '资质逾期',
          type: 1
        },
        {
          name: '整改次数',
          type: 2
        }
      ],
      refresherTriggered: false,
      list: [],
      color: ['#1B84FF', '#7239EA', '#F6B100', '#F8285A', '#17C653']
    }
  },
  onLoad: async function () {
    await uni.hideTabBar()
    uni.hideTabBar({
      animation: false
    })
    this.getDict()
    if (!this.$roles.checkRole(['director'])) {
      this.queryParams.deptId = this.$store.getters.deptId
    }
    this.init()
  },
  onReady() {
    this.$nextTick(() => {
      this.getPageHeight()
    })
  },
  onShow() {
    this.init()
  },
  methods: {
    getPageHeight() {
      const query = uni.createSelectorQuery().in(this)
      query
        .select('.view-container')
        .boundingClientRect(data => {
          this.viewHeigth = data.height - 35 - 25
        })
        .exec()
    },
    async getDict() {
      const dict = await getDictBatchByType({
        type: ['select_week'].join(',')
      })
      const dept = await getDeptTree()
      this.dictMap = {
        ...dict.data,
        dept: dept.data
      }
    },
    getDropdownOption(key) {
      if (!this.dictMap[key]) return []
      const keyMap = {
        select_week: '周期',
        dept: '部门'
      }
      if (key == 'dept') {
        const data = [
          ...this.dictMap[key].map(d => {
            return {
              value: d.id,
              text: d.name
            }
          })
        ]
        if (!this.$roles.checkRole(['director'])) {
          this.queryParams.deptId = this.$store.getters.deptId
          return [...data]
        }
        return [...data, { value: '', text: keyMap[key] }]
      }
      return [
        ...this.dictMap[key].map(d => {
          return {
            value: d.value,
            text: d.label
          }
        }),
        { value: '', text: keyMap[key] }
      ]
    },
    async init() {
      // if (!this.$roles.checkRole(['director'])) {
      //   this.queryParams.deptId = this.$store.getters.deptId
      // }
      const res = await HomeApi.getPieData(this.queryParams)
      this.detail = res.data
      let curIndex = 0
      const data = this.detail.completionRate.map((item, index) => {
        const res = { ...item, color: this.color[curIndex] }
        curIndex > this.color.length ? 0 : curIndex++
        return res
      })
      this.detail.legendData = data
      this.setPieData(data, this.detail.taskCompletionRate)
      this.getList()
    },
    async getList() {
      const res = await HomeApi.getListData(this.queryParams)
      this.list = res.data
    },
    setPieData(data, max) {
      const pieData = data.map(i => {
        return {
          name: i.name,
          value: Number(i.pieValue)
        }
      })
      if (Number(max) < 100) {
        pieData.push({
          name: '',
          value: 100 - Number(max),
          color: '#fff'
        })
      }
      this.opts = {
        legend: {
          show: false
        },
        color: this.color,
        rotate: false,
        rotateLock: false,
        padding: [0, 0, 0, 0],
        dataLabel: false,
        enableScroll: false,
        title: {
          name: `${max}%`,
          fontSize: 24,
          color: '#071437',
          fontWeight: 'bold'
        },
        subtitle: {
          name: '完成率',
          fontSize: 14,
          color: '#78829D'
        },
        extra: {
          ring: {
            ringWidth: 15,
            activeOpacity: 0.5,
            offsetAngle: 90,
            labelWidth: 15,
            border: false,
            borderColor: '#FFFFFF',
            linearType: 'none'
          }
        }
      }
      this.chartData = {
        series: [
          {
            data: pieData
          }
        ]
      }
    },
    sectionChange(index) {
      this.queryParams.enterprise = index
    },
    querySelect(v, key) {
      this.queryParams[key] = v.detail
      this.init()
    },
    changeTab(type) {
      this.queryParams.type = type
      this.getList()
    },
    refresherpulling() {
      const that = this
      if (!this.refresherTriggered) {
        this.refresherTriggered = true
        setTimeout(() => {
          that.refresherTriggered = false
        }, 1000)
      }
    },
    refresherrefresh() {
      this.init()
    }
  }
}
</script>

<style lang="scss" scoped>
.view-container {
  height: 100%;
}
.view {
  padding: 0 12px;
  padding-bottom: 12px;
  display: flex;
  gap: 12px;
  flex-flow: column nowrap;
  .box {
    padding: 12px;
    background-color: #fff;
    border: 1px solid #f9f9f9;
    border-radius: 12px;
    margin-top: 12px;
    &:last-child {
      margin-bottom: 12px;
    }
  }
  .row-1 {
    display: flex;
    flex-flow: column nowrap;
    gap: 12px;
  }
  .tab {
    position: relative;
    padding: 4px 16px;
    .name {
      z-index: 2;
      position: inherit;
      font-weight: bold;
    }
    &:first-child::before {
      content: '';
      position: absolute;
      inset: 0;
      background-color: #fff;
      border-radius: 2px;
      transform: translateX(calc(var(--index) * 100%));
      transition: 0.2s all;
      z-index: 1;
    }
  }
}
::v-deep .van-dropdown-menu {
  box-shadow: none;
  height: 35px !important;
  font-size: 13px;
  border-bottom: 1px solid #f1f1f4;
}
</style>
