<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="#">系统管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/personDeviceLog">测温记录</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--
      要resetFields起作用，必须配置:model和prop
    -->
    <el-form ref="queryForm" :model="queryModel" inline class="demo-form-inline">
      <div>
        <el-form-item label="记录时间" prop="timeRanges">
          <el-date-picker
            v-model="queryModel.timeRanges"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="timeRangesDefaultTime"
            size="mini"
          ></el-date-picker>
          <!-- <el-date-picker
            v-model="queryModel.timeRanges"
            type="datetimerange"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['12:00:00', '08:00:00']"
          ></el-date-picker>-->
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input type="text" size="mini" v-model="queryModel.deviceNo"></el-input>
        </el-form-item>
        <el-form-item label="设备别称" prop="aliasName">
          <el-input type="text" size="mini" v-model="queryModel.aliasName"></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="单位" prop="companyId">
          <!-- <el-select
            v-model="queryModel.companyId"
            size="mini"
            filterable
            placeholder="请选择"
            style="width:220px"
          >
            <el-option
              v-for="company in companyResult"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            ></el-option>
          </el-select>&nbsp;-->
          <el-select-tree
            :props="props"
            :options="optionData"
            :value="queryModel.companyId"
            @getValue="getSelectedValue($event)"
            height="200"
          ></el-select-tree>&nbsp;
          <el-checkbox v-model="queryModel.subordinate">是否包含下级单位</el-checkbox>
          <el-checkbox v-model="queryModel.distinct">是否去重</el-checkbox>
        </el-form-item>
        <el-form-item label="人员姓名" prop="personName">
          <el-input type="text" size="mini" v-model="queryModel.personName"></el-input>
        </el-form-item>
        <el-form-item label="温度区间" prop="temperatureBegin">
          <el-input
            type="text"
            size="mini"
            style="width:50px;"
            v-model="queryModel.temperatureBegin"
          ></el-input>-
          <el-input type="text" size="mini" style="width:50px;" v-model="queryModel.temperatureEnd"></el-input>
        </el-form-item>
        <el-form-item label="匹配状态" prop="matchMsg">
          <el-input type="text" size="mini" style="width:80px;" v-model="queryModel.matchMsg"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="ios-search"
            @click="changePage(1)"
            :loading="loading"
          >查询</el-button>&nbsp;
          <el-button
            type="info"
            size="mini"
            style="margin-left: 8px"
            @click="handleReset('queryForm')"
          >重置</el-button>&nbsp;
        </el-form-item>
      </div>
    </el-form>
    <el-divider></el-divider>
    <el-row class="button-group">
      <el-button
        type="primary"
        size="small"
        plain
        icon="el-icon-download"
        :loading="downloadLoading"
        @click="downloadXls"
      >导出数据</el-button>
    </el-row>
    <el-table
      ref="tablesssssss"
      :data="tableData"
      style="min-height:400px;"
      v-loading="loading"
      stripe
      :height="tableHeight"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column prop="recordTime" label="记录时间" width="180"></el-table-column>
      <el-table-column prop="faceImage" width="120">
        <template slot-scope="{row}">
          <a :href="row.faceImage" target="_blank">
            <el-avatar
              :size="60"
              :src="row.faceImage+'?x-oss-process=image/resize,m_lfit,h_100,w_100'"
              :key="row.id"
            ></el-avatar>
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="person" label="人员姓名" width="120">
        <template slot-scope="{row}">{{row.person == null ? "匿名用户" : row.person.name}}</template>
      </el-table-column>
      <el-table-column prop="temperature" label="测温度数" width="120"></el-table-column>
      <!-- <el-table-column prop="matchStatus" label="匹配状态" width="180"></el-table-column> -->
      <el-table-column prop="matchMsg" label="匹配状态" width="250"></el-table-column>
      <!-- <el-table-column prop="matchFaceId" label="匹配的人脸id" width="180"></el-table-column> -->
      <!-- <el-table-column prop="position1" label="一级位置" width="150"></el-table-column>
      <el-table-column prop="position2" label="二级位置" width="150"></el-table-column>
      <el-table-column prop="position3" label="三级位置" width="150"></el-table-column>
      <el-table-column prop="position4" label="四级位置" width="150"></el-table-column>
      <el-table-column prop="position5" label="五级位置" width="150"></el-table-column>-->
      <el-table-column prop="deviceNo" label="设备编号" width="220"></el-table-column>
      <el-table-column prop="device" label="设备别称" width="220">
        <template slot-scope="{row}">{{row.device == null ? "" : row.device.aliasName}}</template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="pageIndex"
      :total="totalElements"
      :page-sizes="pageSizeList"
      @current-change="changePage"
      @size-change="pageSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>
<script>
import Constant from "@/constant";
import personDeviceLogApi from "@/api/base/personDeviceLog";
import companyInfoApi from "@/api/base/companyInfo";
import SelectTree from "@/components/SelectTree";

import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

export default {
  data() {
    var self = this;

    return {
      queryModel: {
        deviceNo: "",
        aliasName: "",
        personName: "",
        matchStatus: "",
        timeRanges: "",
        faceImage: "",
        position: "",
        temperatureBegin: "",
        temperatureEnd: "",
        temperatureRanges: "",
        matchMsg: "",
        companyId: "",
        subordinate: false,
        distinct: false
      },
      loading: false,
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalPages: 0,
      totalElements: 0,
      field: "",
      direction: "",
      pageSizeList: [10, 20, 30],
      multipleSelection: [],
      showModal: false,
      modalTitle: "",
      businessKey: "",
      downloadLoading: false,
      tableHeight: "",
      timeRangesDefaultTime: [],
      companyResult: [],
      treeData: [],
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children"
      }
    };
  },
  computed: {
    /* 转树形数据 */
    optionData() {
      let cloneData = JSON.parse(JSON.stringify(this.companyResult)); // 对源数据深度克隆
      return cloneData.filter(father => {
        // 循环所有项，并添加children属性
        let branchArr = cloneData.filter(child => father.id == child.parentId); // 返回每一项的子级数组
        branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
        return father.parentId == null; //返回第一层
      });
    }
  },
  created() {
    var self = this;
    this.getCurrentMonthFirst();

    companyInfoApi.list().then(function(response) {
      var jsonData = response.data;
      if (jsonData.result) {
        if (jsonData.data != null && jsonData.data != "") {
          self.companyResult = jsonData.data;
        }
      }
    });

    this.loadTree();
  },
  methods: {
    getSelectedValue(value) {
      this.queryModel.companyId = value;
    },
    loadTree() {
      var formData = new FormData();

      companyInfoApi.loadChildren(formData).then(resp => {
        var jsonData = resp.data;

        if (jsonData.result) {
          this.treeData = jsonData.data;
        } else {
          this.$message.error(jsonData.message + "");
        }
      });
    },
    loadChildren(tree, treeNode, resolve) {
      console.log(tree);

      var formData = new FormData();
      formData.append("parentId", tree.id);

      companyInfoApi.loadChildren(formData).then(resp => {
        var jsonData = resp.data;

        if (jsonData.result) {
          resolve(jsonData.data);
        } else {
          this.$message.error(jsonData.message + "");
        }
      });
    },
    changePage(pageIndex) {
      var self = this;

      self.loading = true;

      self.pageIndex = pageIndex;
      var formData = new FormData();

      formData.append("pageIndex", self.pageIndex);
      formData.append("pageSize", self.pageSize);

      formData.append("faceImage", self.queryModel.faceImage);
      formData.append("timeRanges", self.queryModel.timeRanges);
      formData.append("matchStatus", self.queryModel.matchStatus);
      formData.append("personName", self.queryModel.personName);
      formData.append("deviceNo", self.queryModel.deviceNo);
      formData.append("aliasName", self.queryModel.aliasName);
      formData.append("position", self.queryModel.position);
      formData.append("matchMsg", self.queryModel.matchMsg);

      if(self.queryModel.companyId == null){
        self.queryModel.companyId = "";
      }
      formData.append("companyId", self.queryModel.companyId);
      formData.append("subordinate", self.queryModel.subordinate);
      formData.append("distinct", self.queryModel.distinct);

      formData.append(
        "temperatureRanges",
        self.queryModel.temperatureBegin + "," + self.queryModel.temperatureEnd
      );

      if (this.field != null) {
        formData.append("field", this.field);
      }

      if (this.direction != null) {
        formData.append("direction", this.direction);
      }

      personDeviceLogApi
        .pageList(formData)
        .then(function(response) {
          self.loading = false;

          var jsonData = response.data.data;

          self.tableData = jsonData.data;
          self.totalPages = jsonData.totalPages;
          self.totalElements = jsonData.recordsTotal;
          self.tableHeight = window.innerHeight - 320;
        })
        .catch(error => {
          self.loading = false;
          // self.$message.error(error + "");
        });
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
    },
    sortChange(data) {
      this.field = data.column.field;
      this.direction = data.order;

      this.changePage(this.pageIndex);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleReset(name) {
      this.$refs[name].resetFields();
      this.queryModel.timeRanges = "";
      this.queryModel.temperatureEnd = "";
      this.queryModel.subordinate = false;
      this.queryModel.distinct = false;
    },
    onDetailModalClose(refreshed) {
      //保存成功后回调
      this.showModal = false;

      if (refreshed) {
        this.changePage(this.pageIndex);
      }
    },
    downloadXls() {
      //导出
      var self = this;
      self.downloadLoading = true;
      var formData = new FormData();

      formData.append("faceImage", self.queryModel.faceImage);
      formData.append("timeRanges", self.queryModel.timeRanges);
      formData.append("matchStatus", self.queryModel.matchStatus);
      formData.append("personName", self.queryModel.personName);
      formData.append("deviceNo", self.queryModel.deviceNo);
      formData.append("aliasName", self.queryModel.aliasName);
      if(self.queryModel.companyId == null){
        self.queryModel.companyId = "";
      }
      formData.append("companyId", self.queryModel.companyId);
      formData.append("position", self.queryModel.position);

      formData.append("subordinate", self.queryModel.subordinate);
      formData.append("distinct", self.queryModel.distinct);

      personDeviceLogApi.exportXls(formData).then(function(response) {
        var jsonData = response.data;
        self.downloadLoading = false;
        if (jsonData.result) {
          if (jsonData.data != null) {
            //下载有错误信息提示的报表
            self.$message({
              showClose: true,
              dangerouslyUseHTMLString: true,
              message: `<a href="${jsonData.data}" target="_blank">点击下载报表</a>&nbsp;`,
              duration: 30000
            });
          }
        }
      });
    },
    //初始化日期
    getCurrentMonthFirst() {
      var self = this;
      var date = new Date();
      var startDate = new Date();
      var month = parseInt(date.getMonth() + 1);

      //获取三天前时间
      var startMonth = month;
      if (startDate.getDate() < 7) {
        startMonth = startDate.getMonth();
        startDate.setDate(0);
      }
      startDate = startDate.getDate() - 7;

      var startTime =
        date.getFullYear() + "-" + startMonth + "-" + startDate + " 00:00:00";

      var endTime =
        date.getFullYear() + "-" + month + "-" + date.getDate() + " 23:59:59";

      self.queryModel.timeRanges = [startTime, endTime];
    }
  },
  mounted: function() {
    this.changePage(1);
  },
  components: {
    "el-select-tree": SelectTree
  }
};
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  margin: 10px;
  line-height: 20px;
}

.el-divider {
  margin: 5px 0;
}

.demo-form-inline {
  margin-left: 10px;
  text-align: left;
}

.button-group {
  margin-left: 10px;
  text-align: left;
}
</style>