

<template>
  <div class="d-flex flex-wrap pb-3">
    <div>
      <a-range-picker
        :default-value="[$moment(timeObj.startTime, dateFormat), $moment(timeObj.endTime, dateFormat)]"
        :format="dateFormat"
        @change="onChange"
      />
      <a-button @click="handleTableChange" class="mx-2" type="primary">搜索</a-button>
      <a-button @click="downFile" icon="download" class="mx-2 down-btn" type="primary">下载</a-button>
    </div>
  </div>
</template>

<script>
import { weightExport } from 'config/api';

export default {
  name: 'Search',
  data() {
    return {
      timeObj: {
        startTime: this.$moment(Date.parse(new Date()) - 3600 * 30 * 24 * 1000).format('YYYY-MM-DD'),
        endTime: this.$moment(Date.parse(new Date())).format('YYYY-MM-DD'),
      },
      dateFormat: 'YYYY-MM-DD',
      clear: true,
    };
  },
  methods: {
    onChange(e) {
      // this.timeObj.endTime = this.$moment(e._d).unix() * 1000 + 3600 * 24 * 1000;
      console.log(e);
      this.timeObj.startTime = this.$moment(e[0]._d).unix() * 1000;
      this.timeObj.endTime = this.$moment(e[1]._d).unix() * 1000;
    },
    handleTableChange() {
      if (typeof this.timeObj.startTime === 'string') {
        this.timeObj.startTime = this.$moment(this.timeObj.startTime).unix() * 1000;
      }
      if (typeof this.timeObj.endTime === 'string') {
        this.timeObj.endTime = this.$moment(this.timeObj.endTime).unix() * 1000;
      }
      const mistake = this.timeObj.endTime - this.timeObj.startTime;
      if (mistake > 3600 * 24 * 30 * 1000) {
        this.$message.error('时间跨度请不要超过30天');
      } else {
        this.$emit('getData', this.timeObj);
      }
    },
    // 下载附件
    downFile() {
      if (typeof this.timeObj.startTime === 'string') {
        this.timeObj.startTime = this.$moment(this.timeObj.startTime).unix() * 1000;
      }
      if (typeof this.timeObj.endTime === 'string') {
        this.timeObj.endTime = this.$moment(this.timeObj.endTime).unix() * 1000;
      }
      const mistake = this.timeObj.endTime - this.timeObj.startTime;
      if (mistake > 3600 * 24 * 30 * 1000) {
        this.$message.error('时间跨度请不要超过30天');
      } else {
        console.log(`http://www.tall.wiki/gateway/wisdomcar/record/weightExport?
          startTime=${this.timeObj.startTime}&&endTime=${this.timeObj.endTime}`);
        this.$message.success('导出成功');
        window.open(
          `https://www.tall.wiki/gateway/wisdomcar/record/weightExport?` +
            `startTime=${this.timeObj.startTime}&&endTime=${this.timeObj.endTime}`,
        );
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
.down-btn {
  position: absolute;
  right: 25px;
}
</style>
