<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="选择月份">
          <el-date-picker
            v-model="queryParams.month"
            type="month" value-format="yyyy-MM"
            placeholder="选择月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="部门" prop="orgId">
            <treeselect v-model="queryParams.orgId" :options="deptOptions" :normalizer="normalizer" @select="handleSelect" placeholder="选择部门" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入姓名"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="typeList">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center" width="80" type="index">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="所属部门" align="center" prop="orgName" />
        <el-table-column label="应出勤天数" align="center" prop="requiredDays" />
        <el-table-column label="正常打卡天数" align="center" prop="normalNum">
          <template slot-scope="scope">
              <div
              @click="openRecord(scope.row,title1)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.normalNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="迟到次数" align="center" prop="lateNum">
          <template slot-scope="scope">
              <div
              @click="openRecord(scope.row,title2)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.lateNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="早退次数" align="center" prop="earlyNum">
          <template slot-scope="scope">
              <div
              @click="openRecord(scope.row,title3)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.earlyNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="旷工次数" align="center" prop="skippingNum">
          <template slot-scope="scope">
              <div
              @click="openRecord(scope.row,title4)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.skippingNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="打卡地异常次数" align="center" prop="addressErrorNum">
          <template slot-scope="scope">
            <div
            @click="openRecord(scope.row,title5)" style="color: #02a7f0; cursor: pointer">
                {{ scope.row.addressErrorNum}}
            </div>
        </template>
        </el-table-column>
        <el-table-column label="出入异常次数" align="center" prop="einErrorNum">
          <template slot-scope="scope">
              <div
              @click="openRecord(scope.row,title6)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.einErrorNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="请假天数" align="center" prop="leaveNum">
          <template slot-scope="scope">
              <div @click="openRecord(scope.row,title7)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.leaveNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="轮休天数" align="center" prop="restNum">
          <template slot-scope="scope">
              <div @click="openRecord(scope.row,title8)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.restNum}}
              </div>
          </template>
        </el-table-column>
        <el-table-column label="临时外出天数" align="center" prop="outNum">
          <template slot-scope="scope">
              <div @click="openRecord(scope.row,title9)" style="color: #02a7f0; cursor: pointer">
                  {{ scope.row.outNum}}
              </div>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      
      <!-- 相关记录 -->
      <el-dialog :title="title" :visible.sync="showRecord" width="1300px" height="1000px" append-to-body @close="cancelRecord">
        <el-form :model="queryRecord" ref="queryFormRecord" size="small" :inline="true" v-show="showSearch" label-width="110px">
        <el-form-item  label="选择考勤时间段">
          <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryRecord">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetRecord">重置</el-button>
        </el-form-item>
        </el-form>

        <el-table   :data="tableDataRecord" width="900px" height = "600px" row-key="id">
          <el-table-column label="序号" align="center" width="80" type="index">
          <template slot-scope="scope">
            <span>{{ (queryRecord.pageNum - 1) * queryRecord.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
          <el-table-column label="id" align="center" prop="id" v-if="false" />
          <el-table-column label="姓名" align="center" prop="name" width="80" sortable/>
          <el-table-column label="所属部门" align="center" prop="orgName" width="150" sortable/>
          <el-table-column label="考勤日期" align="center" prop="attCurrent" width="150" sortable>\
            <template slot-scope="scope">
              <span>{{ formatDate(scope.row.attCurrent) }}</span>
          </template>
          </el-table-column> 
          <el-table-column label="上班打卡时间" align="center" prop="goWorkTime" width="180" sortable/>
          <el-table-column label="上班状态" align="center" prop="goWorkStatus" width="100" sortable>
            <template slot-scope="scope">
                <dict-tag :options="dict.type.att_status" :value="scope.row.goWorkStatus"/>
              </template>
          </el-table-column> 
          <el-table-column label="上班打卡地址" align="center" prop="goWorkAddress" sortable width="180"/>
          <el-table-column label="下班打卡时间" align="center" prop="offWorkTime" width="180" ortable/>
          <el-table-column label="下班状态" align="center" prop="offWorkStatus" width="100" sortable>
              <template slot-scope="scope">
                <dict-tag :options="dict.type.att_status" :value="scope.row.offWorkStatus"/>
              </template>
          </el-table-column> 
          <el-table-column label="下班打卡地址" align="center" prop="offWorkAddress" width="180" sortable/>
        </el-table>
    
        <pagination
          v-show="totalTwo>0"
          :total="totalTwo"
          :page.sync="queryRecord.pageNum"
          :limit.sync="queryRecord.pageSize"
          @pagination="getListRecord"
        />

      </el-dialog>
    
    </div>
  </template>
  
  <script>
  import { getDetail} from "@/api/report/monthlyError";
  import { getMonthAttReport,exportMonthReport } from "@/api/report/monthReport";
  import { listDept } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  var monstr="";
  export default {
    name: "Dict",
    dicts: ['sys_normal_disable'],
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        title1: "打卡记录",
        title2: "迟到记录",
        title3: "早退记录",
        title4: "旷工记录",
        title5: "打卡地异常记录",
        title6: "出入异常记录",
        title7: "请假记录",
        title8: "轮休记录",
        title9: "临时外出记录",
        // 是否显示弹出层
        open: false, 
        showRecord:false,
        dateRange: [],
        attCurrentMonth:"",
        pickerOptions: {
          disabledDate: this.disabledDate,
        },
        queryRecord: {
          pageNum: 1,
          pageSize: 10,
          userId: undefined,
          attStatis: undefined,
        },
        tableDataRecord: [],
        totalTwo: 0,
        dialogQueryForm:{
            pageNum: 1,
            pageSize: 10,
        },
        dialogList:[],
        dialogTotal: 0,
       
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          month: undefined,
          userName: undefined,
          orgId: undefined,
          orgName: undefined,
        },
        deptOptions: [],
      };
    },
    created() {
      this.getDeptList();
      this.getMonth();
      this.getList();
    },
    methods: {
 
        formatDate(dateString){
            const date = new Date(dateString); // 创建日期对象
            const year = date.getFullYear(); // 获取年份
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份（注意：月份从0开始）
            const day = String(date.getDate()).padStart(2, '0'); // 获取日期
            const weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; // 星期几数组
            const weekday = weekdays[date.getDay()]; // 获取星期几

            return `${year}-${month}-${day} ${weekday}`; // 组合成所需格式
        },
        getMonth(){
          // 默认当月
          var nowDate = new Date();
          var date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            day: nowDate.getDate()
          };
          const dayDate = date.year + "-" + (date.month >= 10 ? date.month : "0" + date.month);
          this.$set(this.queryParams, "month", dayDate.toString());
        },
        getDeptList(){
            listDept().then(response => {
                this.deptOptions = this.handleTree(response.data, "id");
            });
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.orgName,
                children: node.children
            };
        },
        handleSelect(value, instanceId) { 
            console.log('Selected:', value);
            // 在这里处理选择事件
            this.queryParams.orgName=value.orgName;
        },
         /** 查询字典类型列表 */
        getList() {
            this.loading = true;
            console.log(this.queryParams)
            getMonthAttReport(this.queryParams).then(response => {
                this.typeList = response.rows;
                this.total = response.total;
                this.loading = false;
            }
            );
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.getMonth()
            this.resetForm("queryForm");
            this.handleQuery();
        },
        //打开月异常详情页面
        openRecord(row,titleBoss){
          this.id = row.id;
          this.title = titleBoss;
          this.queryRecord.userId = row.userId;
          this.attCurrentMonth = row.attCurrentMonth;
          if(titleBoss=='打卡记录'){
            this.queryRecord.attStatis=1;
          }else if(titleBoss=='迟到记录'){
            this.queryRecord.attStatis=2;
          }else if(titleBoss=='早退记录'){
            this.queryRecord.attStatis=4;
          }else if(titleBoss=='旷工记录'){
            this.queryRecord.attStatis=3;
          }else if(titleBoss=='打卡地异常记录'){
            this.queryRecord.attStatis=9;
          }else if(titleBoss=='出入异常记录'){
            this.queryRecord.attStatis=8;
          }else if(titleBoss=='请假记录'){
            this.queryRecord.attStatis=6;
          }else if(titleBoss=='轮休记录'){
            this.queryRecord.attStatus=5;
          }else if(titleBoss=='临时外出记录'){
            this.queryRecord.attStatus=7;
          }
          this.showRecord = true;
          this.getListRecord();
        },
        disabledDate(time) {
          const str=this.attCurrentMonth+'-01'; 
          // 获取当前日期
          var currentDate = new Date(str);
          // 获取当前月份的第一天
          var firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
          // 获取当前月份的最后一天
          var lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
          return time < firstDayOfMonth || time > lastDayOfMonth;
        },
        /** 查询月异常详情列表 */
        getListRecord() { 
          getDetail(this.addDateRange(this.queryRecord, this.dateRange)).then(response => {
            this.tableDataRecord = response.rows;
            this.totalTwo = response.total; 
          });
        },

        /** 搜索按钮操作 */
        handleQueryRecord() {
          this.queryRecord.pageNum = 1;
          this.getListRecord();
        },

        cancelRecord() {
            this.showRecord = false;
            this.resetRecord();
        },
        /** 重置按钮操作 */
        resetRecord() {
            // this.resetForm("queryFormRecord");
            this.handleQueryRecord();
        },

        /** 导出按钮操作 */
        handleExport() {
            exportMonthReport(this.queryParams).then(res => {
              this.downloadFile({ fileName: `月报表记录_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
            })
        },
 
    }
  };
  </script>