<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="showStartPicker = true" is-link arrow-direction="down"
                    :value="startWeekStr"/>
          <van-popup v-model="showStartPicker" position="bottom" custom-style="height: 20%;">
            <week-date-type :defaults="defaults" @onConfirm="onStartTimeConfirm" @onCancel="onCancel"/>
          </van-popup>
        </van-col>
        <van-col span="12">
          <van-cell title="结束时间" @click="showEndPicker = true" is-link arrow-direction="down" :value="endWeekStr"/>
          <van-popup v-model="showEndPicker" position="bottom" custom-style="height: 20%;">
            <week-date-type :defaults="defaults" @onConfirm="onEntTimeConfirm" @onCancel="onCancel"/>
          </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 WeekDateType from "views/menu/monitorStatistics/components/WeekDateType.vue";
import dayjs from "dayjs";
import {selectMonitorReport} from "api/toConsult";

export default {
  components: {
    WeekDateType,
    NavBar,
    OrgTree,
    dateCell,
    selectCell
  },
  data() {
    return {
      orgId: '',
      showStartPicker: false,
      showEndPicker: false,
      startWeekStr: '', //年份
      endWeekStr: '', //年份
      startTime: new Date(),
      endTime: new Date(),
      defaults: new Date(),
      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: 'planAccessNumber', key: 'b', title: '应调阅次数', align: 'center'},
        {field: 'realityAccessNumber', key: 'c', title: '调阅次数', align: 'center'},
        {field: 'accessRate', key: 'd', title: '完成率', align: 'center'}
      ],
      dataList: []
    }
  },
  created() {

  },
  mounted() {
    this.initData()

  },
  computed: {},
  methods: {
    dayjs,
    formatter(type, val) {
      if (type === 'month') {
        return `${val}月`;
      } else if (type === 'year') {
        return `${val}年`;
      }
      return val;
    },

    initData() {
      this.orgId = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + '';
      this.initializeDates();
      this.getDataList();
    },

    //机构搜索
    getOrgDataList(val) {
      this.orgId = val
      this.getDataList()
    },
    getDataList() {
      let data = {
        orgId: this.orgId || '',
        startDate: dayjs(this.startTime).startOf('day').format('YYYY-MM-DD'),
        endDate: dayjs(this.endTime).endOf('day').format('YYYY-MM-DD'),
      }
      selectMonitorReport(data).then(res => {
        if (res.data.length > 0){
          let arr=res.data;
          // 将百分比字符串转换为数字
          arr.forEach(item => {
            item.accessRate = parseFloat(item.accessRate).toFixed(2);
          });

          // 根据percentage字段进行降序排列
          arr.sort((a, b) => b.accessRate - a.accessRate);
          // 将排序后的数字转换回带有百分比符号的字符串
          arr.forEach(item => {
            item.accessRate = `${item.accessRate}%`;
          });
          // 重新赋值给dataList
          this.dataList = arr;
        }else {
          this.dataList = []
        }
      })
    },
    //搜索选择状态时触发
    onStartTimeConfirm(value, index) {
      // 假设 value 是一个对象，其中包含了 text 属性
      const weekText = value[1].text;
      this.startTime = value[1].weekStart;
      this.startWeekStr = this.getWeekStr(weekText)
      this.showStartPicker = false; // 关闭弹窗
      if (!this.validateDates()) {
        // 显示错误消息
        this.$toast('开始时间不能晚于结束时间！');
        this.showStartPicker=true;
        return;
      }
      this.getDataList();
    },
    //搜索选择状态时触发
    onEntTimeConfirm(value, index) {
      // 假设 value 是一个对象，其中包含了 text 属性
      const weekText = value[1].text;
      this.endTime = value[1].weekEnd;
      this.endWeekStr = this.getWeekStr(weekText);
      this.showEndPicker = false; // 关闭弹窗
      if (!this.validateDates()) {
        // 显示错误消息
        this.$toast('开始时间不能晚于结束时间！');
        this.showEndPicker=true;
        return;
      }
      console.log(this.startTime, this.endTime)
      this.getDataList();
    },

    onCancel() {
      this.showStartPicker = false;
      this.showEndPicker = false;
    },

    //日期格式
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    initializeDates() {
      const today = dayjs();
      const startOfYear = today.startOf('year');
      const startOfWeek = today.startOf('week');
      const weekOfYear = Math.ceil(startOfWeek.diff(startOfYear, 'weeks', true) + 1);
      this.startWeekStr = `第${weekOfYear}周`;
      this.endWeekStr = `第${weekOfYear}周`;
      this.startTime = today.startOf('week').toDate();
      this.endTime = today.endOf('week').toDate();
    },
    validateDates() {
      if (!this.startWeekStr || !this.endWeekStr) {
        return;
      }
      // 将周数字符串转换为数字进行比较
      const startWeekNumber = parseInt(this.startWeekStr.replace(/[第周]/g, ''), 10);
      const endWeekNumber = parseInt(this.endWeekStr.replace(/[第周]/g, ''), 10);
      // 开始时间晚于结束时间，显示错误消息或重新打开弹窗
      return startWeekNumber <= endWeekNumber;
    },
    getWeekStr(text) {
      if (!text) {
        return '';
      }
      const weekMatch = text.match(/第(\d+)周/);
      if (weekMatch && weekMatch[1]) {
        return `第${weekMatch[1]}周`;
      }
      return '';

    },

  }
}
</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>
