<template>
  <div v-loading="downloadLoading" 
    element-loading-text="加载中"
    element-loading-spinner="el-icon-loading">
    <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="/workAttendance">考勤统计</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"
    >
      <div>
        <el-row>
        <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>
        </el-form-item>
        <el-form-item label="统计区间" prop="timeRanges">
          <el-date-picker
            v-model="queryModel.timeRanges"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :default-time="timeRangesDefaultTime"
            size="mini"
          ></el-date-picker>
        </el-form-item>
        </el-row>
        <el-row>
        <el-form-item label="姓名" prop="name">
          <el-input type="text" size="mini" v-model="queryModel.name"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="jobNumber">
          <el-input type="text" size="mini" v-model="queryModel.jobNumber"></el-input>
        </el-form-item>
        <el-form-item>
           <el-button
            type="primary"
            size="mini"
            style="margin-left: 8px"
            @click="handleQuery('queryForm')"
          >查询</el-button>&nbsp;
          <el-button
            type="info"
            size="mini"
            style="margin-left: 8px"
            @click="handleReset('queryForm')"
          >重置</el-button>
        </el-form-item>
        </el-row>
      </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="exportXls"
      >导出数据</el-button>
    </el-row>
    <el-table
      ref="table"
      stripe
      :data="tableData"
      :height="tableHeight"
      style="width: 100%">
      <el-table-column label="序号" fixed="left" type="index" :index="indexMethod"></el-table-column>
      <el-table-column label="姓名" fixed="left" prop="name"></el-table-column>
      <el-table-column label="单位" prop="company"></el-table-column>
      <el-table-column label="部门" prop="department"></el-table-column>
      <el-table-column label="工号" prop="jobNumber"></el-table-column>
      <el-table-column label="出勤天数" prop="workDays"></el-table-column>
      <el-table-column label="休息天数" prop="restDays"></el-table-column>
      <el-table-column label="迟到次数" prop="lateNum"></el-table-column>
      <el-table-column label="早退次数" prop="leaveNum"></el-table-column>
      <el-table-column label="上班缺卡次数" prop="missCardOnWorkCount"></el-table-column>
      <el-table-column label="下班缺卡次数" prop="missCardOffWorkCount"></el-table-column>
      <el-table-column label="旷工天数" prop="missCardAllDayCount"></el-table-column>
      <template v-for="col in dayColumns">
        <el-table-column :label="col.label" :prop="col.name" :key="col.name" width="200px">
          <template slot-scope="{row}">
            <div style="display:flex;flex-direction:column;">
            <template v-for="(item,index) in row.workAttendanceMap[col.name]">
                <div v-html="showItem(item)" :key="index"></div>
            </template>
            </div>
          </template> 
        </el-table-column>
      </template>
    </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 workAttendanceApi from "@/api/business/workAttendance";
import companyInfoApi from "@/api/base/companyInfo";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

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

    return {
      ruleValidate: {
        companyId: [{ required: true, message: "不能为空", trigger: "blur" }],
        timeRanges: [
          { required: true, message: "请选择事件范围", trigger: "blur" }
        ]
      },
      queryModel: {
        companyId: "",
        timeRanges: "",
        name:"",
        jobNumber:""
      },
      loading: false,
      tableData: [],
      pageIndex: 1,
      pageSize: 20,
      totalPages: 0,
      totalElements: 0,
      field: "",
      direction: "",
      pageSizeList: [20, 30, 50],
      multipleSelection: [],
      showModal: false,
      modalTitle: "",
      businessKey: "",
      downloadLoading: false,
      tableHeight: "",
      timeRangesDefaultTime: [],
      companyResult: "",
      editorOption: {
        modules: {
          toolbar: "title" // 设置文本编辑器的头部是否展示
        },
        placeholder: "", // 文本框为空时 , 占位文本
        theme: "snow" // 或者为 `bubble`
      },
      downloadUrl: "",
      dayColumns: [],
      tmplKey: ""
    };
  },
  created() {
    var self = this;
    companyInfoApi.list().then(function(response) {
      var jsonData = response.data;
      if (jsonData.result) {
        if (jsonData.data != null && jsonData.data != "") {
          self.companyResult = jsonData.data;
        }
      }
    });

    this.getCurrentMonthFirst();
  },
  methods: {
    indexMethod(index){
      return (this.pageIndex-1)*this.pageSize + (index+1);
    },
    changePage(pageIndex) {
      var self = this;
      self.pageIndex = pageIndex;

      var formData = new FormData();

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

      formData.append("companyId", self.queryModel.companyId);
      formData.append("name", self.queryModel.name);
      formData.append("jobNumber", self.queryModel.jobNumber);

      var startDate = "";
      var endDate = "";
      var timeRanges = self.queryModel.timeRanges + "";

      if (timeRanges != "" && timeRanges != null) {
        timeRanges = timeRanges.split(",");
        startDate = timeRanges[0];
        endDate = timeRanges[1];
      }

      formData.append("startDate", startDate);
      formData.append("endDate", endDate);
      
      self.downloadLoading = true;

      workAttendanceApi.statList(formData).then(function(response) {
        var jsonData = response.data;

        self.downloadLoading = false;
        
        if (jsonData.result) {
          self.tableData = jsonData.data.data;
          self.totalPages = jsonData.data.totalPage;
          self.totalElements = jsonData.data.totalElements;

          self.tableHeight = window.innerHeight - 280;
          self.dayColumns = jsonData.data.dayColumns;
          self.tmplKey = jsonData.data.tmplKey;
        } else {
          self.$message({
            type: "warning",
            message: jsonData.message
          });
        }
      });
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.changePage(1);
    },
    showItem(item){
      var content = [];

      var arr = item.recordTime.split(' ');

      if(arr.length>1){
        content.push(arr[1]);
      }
      else{
        content.push(arr[0]);
      }

      content.push(" ");

      if(item.classifier==1){
        content.push("上班");
      }
      else{
        content.push("下班");
      }

      var fontColor = "";

      if(item.result=="0"){
        content.push("缺卡");
        fontColor = "red";
      }
      else if(item.result=="1"){
        content.push("打卡");
        fontColor = "green";
      }
      else if(item.result=="2"){
        content.push("迟到");
      }
      else if(item.result=="3"){
        content.push("早退");
      }

      return `<font color='${fontColor}'>` + content.join("") + '</font>';
    },
    handleQuery(){
      var self = this;

      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.changePage(1);
        }
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    exportXls() {
      var self = this;

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

          var formData = new FormData();

          formData.append("companyId", self.queryModel.companyId);
          formData.append("name", self.queryModel.name);
          formData.append("jobNumber", self.queryModel.jobNumber);

          var startDate = "";
          var endDate = "";
          var timeRanges = self.queryModel.timeRanges + "";

          if (timeRanges != "" && timeRanges != null) {
            timeRanges = timeRanges.split(",");
            startDate = timeRanges[0];
            endDate = timeRanges[1];
          }

          formData.append("startDate", startDate);
          formData.append("endDate", endDate);
          
          workAttendanceApi.exportXls(formData).then(function(response) {
            var jsonData = response.data;

            self.downloadLoading = false;
            
            if (jsonData.result) {
              self.$message({
                type: "success",
                message: `报表已生成，<a href="${jsonData.data}">请点击链接下载</a>`,
                dangerouslyUseHTMLString: true,
                duration: 30000
              });
            } else {
              self.$message({
                type: "warning",
                message: jsonData.message
              });
            }
          });
        }
      });
    },
    //初始化日期
    getCurrentMonthFirst() {
      var self = this;
      var date = new Date();
      date.setDate(1);
      var month = parseInt(date.getMonth() + 1)
      var startTime =
        date.getFullYear() + "-" + month + "-" + date.getDate();

      var lastDate = new Date();
      //设置为第一天
      lastDate.setDate(1);
      var lastMonth = parseInt(lastDate.getMonth() + 2)
      var endTime =
        lastDate.getFullYear() +
        "-" +
        lastMonth +
        "-" +
        lastDate.getDate();
      self.queryModel.timeRanges = [startTime, endTime];
    }
  },
  mounted: function() {}
};
</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>