<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="/personHealthLedger">健康打卡情况</a>
        <!-- 包含测温和健康上报 -->
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--
      要resetFields起作用，必须配置:model和prop
    -->
    <el-form
      ref="queryForm"
      :model="queryModel"
      :rules="ruleValidate"
      inline
      class="demo-form-inline"
    >
      <el-row>
        <el-form-item label="日期" prop="queryTime">
          <el-date-picker
            size="mini"
            v-model="queryModel.queryTime"
            type="date"
            placeholder="选择日期"
            style="width:100%"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="单位" prop="companyId">
          <el-select-tree
            :props="props"
            :options="companyResult"
            v-model="queryModel.companyId"
            height="200"
          ></el-select-tree>&nbsp;&nbsp;
          <el-checkbox v-model="queryModel.subordinate">是否包含下级单位</el-checkbox>
        </el-form-item>
      </el-row>
      <el-row>
        <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="healthStatus">
          <el-select
            v-model="queryModel.healthStatus"
            filterable
            placeholder="请选择"
            style="width:50%"
          >
            <el-option
              size="mini"
              v-for="result in healthData"
              :key="result.id"
              :label="result.name"
              :value="result.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="ios-search"
            @click="handleQuery"
            :loading="loading"
          >查询</el-button>&nbsp;
          <el-button
            type="info"
            size="mini"
            style="margin-left: 8px"
            @click="handleReset('queryForm')"
          >重置</el-button>&nbsp;
        </el-form-item>
      </el-row>
    </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="exportXls"
      >导出健康打卡情况</el-button>
      <el-button
        type="success"
        size="small"
        plain
        icon="el-icon-download"
        :loading="downloadLoading"
        @click="handleExportDetail"
      >导出健康信息明细表</el-button>
      <el-button type="warning" size="small" plain icon="el-icon-download" :loading="downloadLoading" @click="exportXlsWC">导出外出信息台账</el-button>
      <el-button type="danger" size="small" plain icon="el-icon-download" :loading="downloadLoading" @click="exportXlsTWYC">导出体温异常信息台账</el-button>
      <el-button type="danger" size="small" plain icon="el-icon-download" :loading="downloadLoading" @click="exportXlsZZYC">导出症状异常信息台账</el-button>
    </el-row>
    <el-table
      ref="formTable"
      :data="tableData"
      style="min-height:400px;" 
      :height="tableHeight"
      v-loading="loading"
      stripe
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" :index="indexMethod" width="100"></el-table-column>
      <el-table-column prop="name" label="姓名" width="150"></el-table-column>
      <el-table-column prop="personHealthLedger.temperature" label="记录温度" width="150"></el-table-column>
      <el-table-column prop="companyName" label="单位" width="220"></el-table-column>
      <el-table-column prop="healthStatusN" label="健康情况" width="120">
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.healthStatusN}}</span>
          <span v-else>未提交</span>
        </template>
      </el-table-column>
      <el-table-column prop="familyStatusN" label="家庭健康情况" width="120">
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.familyStatusN}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="isGoto" sort-by="is_goto" label="是否前往疫区" width="150">
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.isGoto == 1 ? "是" : "否"}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="isTouch" label="是否接触高危人员" width="150">
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.isTouch == 1 ? "是" : "否"}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="打卡地址" width="150" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.address}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="180" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="上传日期" width="180">
        <template slot-scope="{row}">
          <span v-if="row.isUpHealth">{{row.personHealthLedger.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100">
          <template slot-scope="{row}">
              <el-button size="mini" type="success" @click="showHistoryList(row)">历史轨迹</el-button>
          </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>
    <personHealthLedger-detail
      v-if="showModal"
      :businessKey="businessKey"
      :title="modalTitle"
      @close="onDetailModalClose"
    ></personHealthLedger-detail>
    <personHealthLedger-list-detalExport
      v-if="showModal2"
      :businessKey="businessKey"
      :title="modalTitle2"
      @close="onDetailModalClose2"
    ></personHealthLedger-list-detalExport>
    <el-dialog
        :visible.sync="showMapDialog"
        title="历史位置"
        :modal-append-to-body="true"
        :append-to-body="true"
        style="text-align:left;"
        :close-on-click-modal="false"
    >
        <el-amap
            ref="map"
            vid="vehicleMap"
            :center="pointPosition"
            :zoom="15"
            style="width:100%;height:400px;"
        >
            <el-amap-marker :position="pointPosition" :title="selectedRow.licensePlateNumber"></el-amap-marker>
        </el-amap>
        <el-input :value="pointPosition[0] + ',' + pointPosition[1]" :readonly="true"/>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showMapDialog=false;">关闭</el-button>
        </span>
    </el-dialog>
    <el-dialog
        :visible.sync="showHistoryDialog"
        title="历史轨迹"
        :modal-append-to-body="true"
        :append-to-body="true"
        width="1000px"
        style="text-align:left;"
        :close-on-click-modal="false"
    >
        <vehicle-history-list
            ref="vehicleHistoryList"
            :personId="selectedRow.id"
        ></vehicle-history-list>
    </el-dialog>
  </div>
</template>
<script>
import Constant from "@/constant";
import personHealthLedgerApi from "@/api/base/personHealthLedger";
import dataDictionaryApi from "@/api/sys/dataDictionary";
import companyInfoApi from "@/api/base/companyInfo";
import SelectTree from "@/components/SelectTree";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import pageUtil from "@/utils/page";
import personHealthLedgerListDetalExport from "./personHealthLedger-list-detalExport";
import VehicleHistoryList from './vehicleHistory-list';

export default {
  name: 'basePersonHealthLedgerListAll',
  data() {
    var self = this;

    return {
      ruleValidate: {
        companyId: [{ required: true, message: "不能为空", trigger: "blur" }],
        queryTime: [{ required: true, message: "请选择时间", trigger: "blur" }]
      },
      queryModel: {
        personName: "",
        healthStatus: "",
        companyId: "",
        subordinate: true,
        queryTime: ""
      },
      loading: false,
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalPages: 0,
      totalElements: 0,
      field: "",
      direction: "",
      pageSizeList: [10, 20, 30],
      multipleSelection: [],
      showModal: false,
      showModal2: false,
      modalTitle: "",
      modalTitle2: "",
      businessKey: "",
      healthData: [],
      companyResult: [],
      treeData: [],
      tableHeight: 400,
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children"
      },
      downloadLoading: false,
      showMapDialog: false,
      pointPosition: [112.240222, 30.337053],
      selectedRow: {
          licensePlateNumber : "",
          deviceNo: ""
      },
      showHistoryDialog: false,
    };
  },
  created() {
    var self = this;
    var formData = new FormData();
    formData.append("catalogName", "健康情况");
    dataDictionaryApi.findByCatalogName(formData).then(response => {
      var jsonData = response.data;
      this.healthData = jsonData.data;
    });

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

    this.loadTree();
    this.setDefaultTime();

    setTimeout(()=>{
      //45为分页栏的高度
      //页面高度-列表上面的高度-分页栏高度
      self.tableHeight = pageUtil.autoAdjustHeight(self.$refs.formTable.$el);
    },1000);
  },
  methods: {
    showMap(row) {
        this.pointPosition = [parseFloat(row.longitude),parseFloat(row.latitude)];
        this.selectedRow = row;
        this.showMapDialog = true;
    },
    showHistoryList(row) {
        this.selectedRow = row;
        this.showHistoryDialog = true;
        
        this.$nextTick(()=>{
            this.$refs.vehicleHistoryList.getCurrentMonthFirst();
            this.$refs.vehicleHistoryList.changePage(1);
        });            
    },
    indexMethod(index) {
      return (this.pageIndex - 1) * this.pageSize + (index + 1);
    },
    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 + "");
        }
      });
    },
    handleExportDetail() {
      this.modalTitle2 = "导出健康信息明细表";
      this.businessKey = "";
      this.showModal2 = true;
    },
    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("personName", self.queryModel.personName);
      formData.append("healthStatus", self.queryModel.healthStatus);
      if (self.queryModel.companyId == null) {
        self.queryModel.companyId = "";
      }
      formData.append("companyId", self.queryModel.companyId);
      formData.append("subordinate", self.queryModel.subordinate);
      formData.append("queryTime", self.queryModel.queryTime);

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

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

      personHealthLedgerApi
        .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;
        })
        .catch(error => {
          self.loading = false;
          // self.$message.error(error + "");
        });
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;

      this.$nextTick(() => {
        this.changePage(this.pageIndex);
      });
    },
    sortChange(data) {
      this.field = data.column.field;
       this.direction = data.order == "ascending" ? "asc" : "desc";

      this.changePage(this.pageIndex);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleQuery() {
      var self = this;
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.changePage(1);
        }
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
      //this.queryModel.companyId = "";
      this.queryModel.queryTime = "";
      this.queryModel.subordinate = false;
    },
    onDetailModalClose(refreshed) {
      //保存成功后回调
      this.showModal = false;

      if (refreshed) {
        this.changePage(this.pageIndex);
      }
    },
    onDetailModalClose2(refreshed) {
      //保存成功后回调
      this.showModal2 = false;
    },
    setDefaultTime() {
      var self = this;
      var date = new Date();
      var month = parseInt(date.getMonth() + 1);
      var nowTime = date.getFullYear() + "-" + month + "-" + date.getDate();

      self.queryModel.queryTime = nowTime;
    },
    exportXls() {
      var self = this;

      //导出
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.downloadLoading = true;
          self.loading = true;

          var formData = new FormData();
          formData.append("pageIndex", self.pageIndex);
          formData.append("pageSize", self.pageSize);

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

          personHealthLedgerApi.exportXls(formData).then(function(response) {
            var jsonData = response.data;

            self.downloadLoading = false;
            self.loading = false;

            if (jsonData.result) {
              self.$message({
                type: "success",
                showClose: true,
                message: `报表已生成，<a href="${jsonData.data}">请点击链接下载</a>`,
                dangerouslyUseHTMLString: true,
                duration: 30000
              });
            } else {
              self.$message({
                type: "warning",
                message: jsonData.message
              });
            }
          });
        }
      });
    },
    exportXlsWC() {
      var self = this;

      //导出
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.downloadLoading = true;
          self.loading = true;

          var formData = new FormData();
          if (self.queryModel.companyId == null) {
            self.queryModel.companyId = "";
          }
          formData.append("companyId", self.queryModel.companyId);
          formData.append("subordinate", self.queryModel.subordinate);
          formData.append("queryTime", self.queryModel.queryTime);

          personHealthLedgerApi.exportXlsWC(formData).then(function(response) {
            var jsonData = response.data;

            self.downloadLoading = false;
            self.loading = false;

            if (jsonData.result) {
              self.$message({
                type: "success",
                showClose: true,
                message: `报表已生成，<a href="${jsonData.data}">请点击链接下载</a>`,
                dangerouslyUseHTMLString: true,
                duration: 30000
              });
            } else {
              self.$message({
                type: "warning",
                message: jsonData.message
              });
            }
          });
        }
      });
    },
    exportXlsTWYC() {
      var self = this;

      //导出
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.downloadLoading = true;
          self.loading = true;

          var formData = new FormData();
          if (self.queryModel.companyId == null) {
            self.queryModel.companyId = "";
          }
          formData.append("companyId", self.queryModel.companyId);
          formData.append("subordinate", self.queryModel.subordinate);
          formData.append("queryTime", self.queryModel.queryTime);

          personHealthLedgerApi.exportXlsTWYC(formData).then(function(response) {
            var jsonData = response.data;

            self.downloadLoading = false;
            self.loading = false;

            if (jsonData.result) {
              self.$message({
                type: "success",
                showClose: true,
                message: `报表已生成，<a href="${jsonData.data}">请点击链接下载</a>`,
                dangerouslyUseHTMLString: true,
                duration: 30000
              });
            } else {
              self.$message({
                type: "warning",
                message: jsonData.message
              });
            }
          });
        }
      });
    },
    exportXlsZZYC() {
      var self = this;

      //导出
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.downloadLoading = true;
          self.loading = true;

          var formData = new FormData();
          if (self.queryModel.companyId == null) {
            self.queryModel.companyId = "";
          }
          formData.append("companyId", self.queryModel.companyId);
          formData.append("subordinate", self.queryModel.subordinate);
          formData.append("queryTime", self.queryModel.queryTime);

          personHealthLedgerApi.exportXlsZZYC(formData).then(function(response) {
            var jsonData = response.data;

            self.downloadLoading = false;
            self.loading = false;

            if (jsonData.result) {
              self.$message({
                type: "success",
                showClose: true,
                message: `报表已生成，<a href="${jsonData.data}">请点击链接下载</a>`,
                dangerouslyUseHTMLString: true,
                duration: 30000
              });
            } else {
              self.$message({
                type: "warning",
                message: jsonData.message
              });
            }
          });
        }
      });
    }
  },
  mounted: function() {
    //this.changePage(1);
  },
  components: {
    "el-select-tree": SelectTree,
    "vehicle-history-list" : VehicleHistoryList,
    "personHealthLedger-list-detalExport": personHealthLedgerListDetalExport,
  }
};
</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>