<template>
  <div>
    <div class="topbar-right"><b>月统计</b></div>
    <b-navbar type="light" variant="faded" class="my-2">
      

          <b-form-datepicker
            id="start-date"
            v-model="startTime"
            v-bind="calendarLabels[locale] || {}"
            :locale="locale"
            :start-weekday="weekday"
            :show-decade-nav="showDecadeNav"
            :hide-header="hideHeader"
            class="calendar danger"
            :state="validStartTime"
          ></b-form-datepicker>

          <b-form-datepicker
            id="end-date"
            v-model="endTime"
            v-bind="calendarLabels[locale] || {}"
            :locale="locale"
            :start-weekday="weekday"
            :show-decade-nav="showDecadeNav"
            :hide-header="hideHeader"
            class="calendar mx-2"
            :state="validEndTime"
          ></b-form-datepicker>


        <b-input-group id="input-name" class="">
          <b-input-group-prepend is-text>
            <b-icon icon="person-square"></b-icon>
          </b-input-group-prepend>

          <b-form-input :state="validUserAccount" @input="selectEmployee" list="name" class="mr-sm-2" placeholder="请输入姓名"></b-form-input>

          <datalist id="name">
            <option v-for="employee in employeeList" :key="employee.id" :value="employee.account+' - '+employee.realname"></option>
          </datalist>

        </b-input-group>

        <b-button variant="primary" class="mx-1" @click="showData">查询</b-button>
        <b-button variant="primary" class="mx-1" @click="exportData">导出</b-button>
      
    </b-navbar>
    <b-card class="content-data mx-3 text-center">
      <div class="no-content my-4" v-if="!dataAvailable">请在上方输入搜索条件查询</div>
      <b-table class="datatable" sticky-header="100%" hover small :items="dataTable" v-if="dataAvailable" :tbody-tr-class="tableRowColor"></b-table>
    </b-card>
    
  </div>
</template>

<script>
export default {
  name: 'PersonalCollected',
  props: {
    
  },
  data() {
    return {
      year: undefined,
      month: undefined,
      date: '',
      userAccount:'',
      employeeList: [],
      dataAvailable: false,
      dataTable: [],
      startTime: undefined,
      endTime: undefined,
      locale: 'zh',
      weekday: 1,
      showDecadeNav: false,
      hideHeader: true,
      calendarLabels: {
        zh: {
          weekdayHeaderFormat: 'narrow',
          labelPrevDecade: '过去十年',
          labelPrevYear: '上一年',
          labelPrevMonth: '上个月',
          labelCurrentMonth: '当前月份',
          labelNextMonth: '下个月',
          labelNextYear: '明年',
          labelNextDecade: '下一个十年',
          labelToday: '今天',
          labelSelected: '选定日期',
          labelNoDateSelected: '未选择日期',
          labelCalendar: '日历',
          labelNav: '日历导航',
          labelHelp: '使用光标键浏览日期'
        }
      },
      validate: false
    };
  },
  computed: {
    validStartTime() {
      return this.validate ? (this.startTime ? true : false) : null;
    },
    validEndTime() {
      return this.validate ? (this.endTime ? true : false) : null;
    },
    validUserAccount() {
      return this.validate ? (this.userAccount ? true : false) : null;
    }
  },
  created() {
    this.$http.get('/api/personal/getUserList')
      .then((result) => {
        this.employeeList = result.data.data;
      });
  },
  mounted() {
    
    
    
  },
  methods: {
    reset() {
      this.dataAvailable = false;
      this.dataTable = [];
    },
    selectEmployee(e) {
      this.userAccount = e.split(' - ')[0];
      this.reset();
    },
    showData() {
      
      if(this.startTime && this.endTime && this.userAccount) {
        this.dataTable = [];
        this.$http.post('/api/personal/workByDayDetail', {
          "account": this.userAccount,
          "startTime": this.startTime,
          "endTime": this.endTime,
          "pageNum": 0,
          "pageSize": 1000,
          "searchKey": ""
        }).then((result) => {
          
          let data = result.data.data.list;

          let dataSummedUp = [];
          let days = [];
          
          data.forEach(entry => {
            if(days.indexOf(entry.date) === -1) {
              days.push(entry.date);
            }
          });

          days.forEach(day => {
            let filtered = data.filter(entry => entry.date === day);
            let sum = 0;
            let total;

            filtered.forEach(d => {
              let number = Number(d.consumed);
              
              sum += number;
              total = Number(parseFloat(sum).toPrecision(4));
            });
            dataSummedUp.push({
              date: filtered[0].date,
              consumed: total,
              deptName: filtered[0].deptName,
              realname: filtered[0].realname,
              account: filtered[0].account
            });
          });

          
          dataSummedUp.sort((a, b) => {
            return new Date(a.date) - new Date(b.date);
          });

          dataSummedUp.forEach(entry => {
            this.dataTable.push({
              '日期': entry.date,
              '消耗时间（单位：小时）': entry.consumed,
              '部门名称': entry.deptName,
              '姓名': entry.realname,
              '账号': entry.account
            });
          });
          this.dataAvailable = true;
        });
      } else {
        this.validate = true;
      }
    },
    exportData() {
      if(this.dataAvailable === true && this.dataTable.length > 0) {
        let csv = Object.keys(this.dataTable[0]).join() + '\n';
        this.dataTable.forEach(row => {
          csv += Object.values(row).join() + '\n';
        });

        let hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = this.startTime + '_' + this.endTime + '_' + this.userAccount + '.csv';
        hiddenElement.click();
      }
    },
    tableRowColor(item, type) {
      if (!item || type !== 'row') return
      if (item['消耗时间（单位：小时）'] > 12) return 'table-danger'
      if (item['消耗时间（单位：小时）'] < 8) return 'table-danger'
    }
  }
}


</script>


<style scoped>
  .topbar-right {
    width: 100%;
    height: 7vh;
    font-size: 1.2em;
    padding: 16px 16px;
    border-bottom: 2px solid lightgrey;
  }
  .content-data {
    position: absolute;
    height: 90%;
    width: calc(100% - 30px);
  }
  .calendar {
    width: 25%;
  }
  #input-name {
    width: 25%;
  }
  .card-body {
    padding: 0;
  }
  .datatable {
    overflow-y: scroll;
  }
  
</style>
