<template>
  <div class="educationStatistics">
    <NavBar/>
    <div class="statistics-container">
      <org-tree v-model="orgId" @change="getOrgDataList"></org-tree>
      <van-row>
        <van-col span="12">
          <van-cell title="开始月份" @click="showStartMonth = true" is-link arrow-direction="down"
                    :value="showStartSelectTimeText"/>
          <van-popup v-model="showStartMonth" round position="bottom">
            <van-datetime-picker
              v-model="startMonth"
              show-toolbar
              @cancel="onCancel"
              type="year-month"
              @confirm="onStartMonthConfirm"
              confirm-button-text="确定"
              :default-index="yearSelect"
              title="开始月份"
              :formatter="formatter"
            />
          </van-popup>
        </van-col>
        <van-col span="12">
          <van-cell title="结束月份" @click="showEndMonth = true" is-link arrow-direction="down"
                    :value="showEndSelectTimeText"/>
          <van-popup v-model="showEndMonth" round position="bottom">
            <van-datetime-picker
              v-model="endMonth"
              show-toolbar
              @cancel="onCancel"
              type="year-month"
              :formatter="formatter"
              @confirm="onEndMonthConfirm"
              confirm-button-text="确定"
              :default-index="yearSelect"
              title="结束月份"
            />
          </van-popup>
        </van-col>
      </van-row>

      <div class="card-list">
        <empty v-if="!dataList || dataList.length === 0"/>
        <ve-table
          v-else
          maxHeight="calc(100vh - 252px)"
          fixedHeader
          borderX
          borderY
          borderAround
          :columns="columns"
          :table-data="dataList"
        />
      </div>
    </div>
  </div>
</template>
<script>
import NavBar from '@/components/NavBar'
import OrgTree from '@/components/orgTree'
import dateCell from '@/components/dateCell'
import selectCell from '@/components/selectCell'
import {getrehearsalList, getTableRehearsalList} from '@/api/drillTask.js'
import {mapGetters} from 'vuex'
import {formatDate} from '@/filters/filter'
import {newDateMonth} from '@/utils/date.js'
import {Toast} from 'vant'
import dayjs from "dayjs";
import {listReport, safeCheckReport} from "views/menu/securityCheckRegister/api";

export default {
  components: {
    NavBar,
    OrgTree,
    dateCell,
    selectCell
  },
  data() {
    return {
      // active: '',
      orgId: '',
      showStatus: false, //状态显示隐藏
      // yearColumns: [],
      showStartMonth: false, //月份显示隐藏
      showEndMonth: false, //月份显示隐藏
      fieldValue: '', //状态名称
      startMonth: newDateMonth(), //年份
      endMonth: newDateMonth(), //年份
      showStartSelectTimeText: this.getDayStr(new Date(), 'YYYY-MM'),
      showEndSelectTimeText: this.getDayStr(new Date(), 'YYYY-MM'),
      yearSelect: null,
      prop: {
        label: 'name',
        value: 'id'
      },
      loading: false,
      columns: [
        {
          field: 'index',
          key: 'index',
          title: '序号',
          width: 50,
          align: 'center',
          renderBodyCell: ({row, column, rowIndex}, h) => {
            return ++rowIndex
          }
        },
        {field: 'orgName', key: 'a', title: '单位名称', align: 'center'},
        {field: 'planInspectNumber', key: 'b', title: '应检数', align: 'center'},
        {field: 'realityInspectNumber', key: 'c', title: '已检数', align: 'center'},
        {field: 'inspectRate', key: 'd', title: '完成率', align: 'center'}
      ],
      dataList: []
    }
  },
  created() {
    this.startMonth = new Date(newDateMonth())
    this.endMonth = new Date(newDateMonth())
  },
  mounted() {
    this.initData()
  },
  computed: {},
  methods: {
    formatter(type, val) {
      if (type === 'month') {
        return `${val}月`;
      } else if (type === 'year') {
        return `${val}年`;
      }
      return val;
    },
    getDayStr(date, format = 'YYYY-MM-DD') {
      return dayjs(date).format(format);
    },
    initData() {
      this.orgId = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + ''

    },
    //机构搜索
    getOrgDataList(val) {
      this.orgId = val

      this.getDataList()
    },
    getDataList() {
      let data = {
        orgId: this.orgId || '',
        startTime: this.showStartSelectTimeText + '-01',
        endTime: this.showEndSelectTimeText + '-01',
        appSelect : 1,
      }

      safeCheckReport(data).then(res => {
        if (res.data.length > 0){
          let arr=res.data;
          // 将百分比字符串转换为数字
          arr.forEach(item => {
            item.inspectRate = parseFloat(item.inspectRate).toFixed(2);
          });

          // 根据percentage字段进行降序排列
          arr.sort((a, b) => b.inspectRate - a.inspectRate);
          // 将排序后的数字转换回带有百分比符号的字符串
          arr.forEach(item => {
            item.inspectRate = `${item.inspectRate}%`;
          });
          // 重新赋值给dataList
          this.dataList = arr;
        }else {
          this.dataList = []
        }
      })
    },
    onCancel() {
      this.showStartMonth = false
      this.showEndMonth = false
    },

    //日期格式
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    //日期选中触发
    onStartMonthConfirm(val) {
      let st = dayjs(this.startMonth).month()+1;
      let ed = dayjs(val).month()+1;
      console.log("123",st,ed)
      if (ed < st) {
        return Toast('结束月份不能小于开始月份')
      }
      this.showStartSelectTimeText = this.getDayStr(val, 'YYYY-MM');
      this.startMonth = val;
      this.showStartMonth = false;
      this.showEndMonth = true;
    },
    //年份选中触发
    onEndMonthConfirm(val) {
      let st = dayjs(this.startMonth).month()+1;
      let ed = dayjs(val).month()+1;
      console.log("123",st,ed)
      if (ed < st) {
        return Toast('结束月份不能小于开始月份')
      }
      this.showEndSelectTimeText = this.getDayStr(val, 'YYYY-MM');
      this.endMonth = val
      this.showEndMonth = false
      this.getDataList()
    },
  }
}
</script>
<style lang="scss">
.van-cell-group {
  margin-bottom: 20px;
}

.van-cell-group:last-child {
  margin-bottom: 0;
}

.vue-table-root {
  tr,
  td,
  th {
    font-size: 25px !important;
    color: #666 !important;
  }
}
</style>
<style lang="scss" scoped>
.educationStatistics {
}

.statistics-container {
}

.card-list {
  padding: 20px;
  height: calc(100vh - 420px);
  overflow: hidden;
}

.card-num {
  display: flex;
  align-items: center;
  font-size: 28px;
  color: #009dff;
}

.flex-box {
  display: flex;
  align-items: center;

  > div {
    margin-right: 40px;
  }
}

.search-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;

  > div {
    width: 50%;
  }
}

.van-cell__value {
  color: black;
  text-align: left;
}
</style>
