<template>
  <!-- 检查部位 -->
  <div class="container_main">
    <div class="checkPoint">
      <div class="header_title">
        <el-form size="medium" :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="人员类型" prop="personType">
            <el-select clearable v-model="queryParams.personType" placeholder="请选择">
              <el-option
                v-for="item in personTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属企业" prop="enterpriseId">
            <el-select
              filterable
              clearable
              @change="onEnterpriseChange"
              v-model="queryParams.enterpriseId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.enterpriseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属班组" prop="teamId">
            <el-select
              filterable
              clearable
              v-model="queryParams.teamId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in teamOptions"
                :key="item.id"
                :label="item.teamName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门" prop="departmentId">
            <el-select
              filterable
              clearable
              v-model="queryParams.departmentId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in departmentOptions"
                :key="item.id"
                :label="item.departmentName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="workerName">
            <el-input v-model="queryParams.workerName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="日期范围" prop="effectiveTime">
            <el-date-picker
            :picker-options="pickerOptions"
              v-model="queryParams.effectiveTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleQuery">查询</el-button>
            <el-button type="warning" plain @click="handleRefresh">刷新</el-button>
            <el-button @click="handleCommandExport(1)" type="primary" plain
              >导出</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="table-header">{{ $store.state.currentProDetail.projectName }}项目工时统计表({{daterangeUp}})</div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        row-key="id"
        :height="450"
        class="new-tables"
        border
        :key="itemKey"
      >
        <!-- <el-table-column type="selection" align="center" width="55"></el-table-column> -->
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="workerName"
          label="姓名"
          width="90"
        >
          <template slot-scope="scope">
            {{ scope.row.workerName ? scope.row.workerName : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="enterpriseName"
          label="单位"
          width="90"
        >
          <template slot-scope="scope">
            {{ scope.row.enterpriseName ? scope.row.enterpriseName : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="personType"
          label="人员类别"
          width="90"
        >
          <template v-slot="{ row }">
            {{
              row.personType == 1 ? "施工人员" : row.personType == 2 ? "管理人员" : "--"
            }}
          </template>
        </el-table-column>
        <el-table-column
          :prop="'day' + item.date"
          :label="String(item.day)"
          v-for="(item, index) in showTime"
          :key="index"
          align="center"
          width="60"
        >
          <template slot="header">
            <div>
              <div>{{ String(item.date) }}</div>
              <!-- <div>{{ getWeek(item.date) }}</div> -->
            </div>
          </template>
          <template slot-scope="scope">
            <span>{{scope.row.dailyHourMap[item.date] ? scope.row.dailyHourMap[item.date] : '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="checkWorkerNames"
          show-overflow-tooltip
          label="合计"
          align="center"
          width="90"
        >
          <template slot-scope="scope">
            {{ scope.row.checkWorkerNames ? scope.row.checkWorkerNames : "--" }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="Number(total)"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getQualityRegionList"
        :pageSizes="[...$store.state.PAGESIZRS, 100, 200, 500, 1000]"
        layout="total,sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>
<script>
import { getCountDailyAttendanceByDateRangeApi } from "@/assets/js/api/attendanceManage";

import {
  getEnterpriseInfoList,
  selectHierarchyEnterpriseListApi,
} from "@/assets/js/api/laborPerson";
import { teamList, departmentList } from "@/assets/js/api/laborManagement/payoff";
import dayjs from "dayjs";
export default {
  name: "workHoursStatisticsTable",
  data() {
    return {
      projectSn: "",
      tableData: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        personType: "",
        enterpriseId: "",
        teamId: "",
        departmentId: "",
        workerName: "",
        effectiveTime: [],
      },
      total: 0,
      personTypeList: [
        {
          label: "施工人员",
          value: 1,
        },
        {
          label: "管理人员",
          value: 2,
        },
      ],
      enterpriseList: [],
      teamOptions: [],
      departmentOptions: [],
      showTime: [],
      systemInfo: {
        platformName: "",
      },
      itemKey: "",
      pickDate:'',
      pickerOptions: {
         onPick: this.getPickDate,
	      disabledDate: this.disabledDate
     },
    };
  },
  created() {
    if (localStorage.getItem("systemInfo")) {
      this.systemInfo = JSON.parse(localStorage.getItem("systemInfo"));
    }
    this.projectSn = this.$store.state.projectSn;
    this.queryParams.effectiveTime = [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().endOf("month").format("YYYY-MM-DD"),
    ];
    this.getQualityRegionList();

    this.getEnterpriseListFn();
    this.getTeamList();
    this.getDepartmentList();
  },
  methods: {
    getPickDate(pick) {
      this.pickDate = pick;
    },
    disabledDate(date) {
      const { minDate, maxDate } = this.pickDate;
      if (minDate && !maxDate) {
        const diff = Math.abs(minDate.valueOf() - date.valueOf());
        if (diff > 1000 * 3600 * 24 * 90) {
          return true;
        }
      }
    },
    // 获取今天星期几
    getWeek(day) {
      const time = dayjs(day).format("YYYY-MM-DD");
      let datas = dayjs(time).day();
      let week = ["日", "一", "二", "三", "四", "五", "六"];
      return week[datas];
    },
    // 获取企业列表
    getEnterpriseListFn() {
      let that = this;
      let reqeustData = {
        projectSn: this.$store.state.projectSn,
      };
      getEnterpriseInfoList(reqeustData).then((res) => {
        that.enterpriseList = res.result;
      });
    },
    onEnterpriseChange() {
      //   this.queryParams.teamId = "";
      //   this.queryParams.departmentId = "";
      //   this.getTeamList();
      //   this.getDepartmentList();
    },
    /** 查询班组列表 */
    getTeamList() {
      const params = {
        // enterpriseId: this.queryParams.enterpriseId,
        projectSn: this.$store.state.projectSn,
      };
      teamList(params).then((res) => {
        console.log("查询班组列表: ", res);
        this.teamOptions = res.result.list;
      });
    },
    /** 查询部门列表 */
    getDepartmentList() {
      const params = {
        // enterpriseId: this.queryParams.enterpriseId,
        projectSn: this.$store.state.projectSn,
      };
      departmentList(params).then((res) => {
        console.log("查询部门列表: ", res);
        this.departmentOptions = res.result.list;
      });
    },
    handleCommandExport(command) {
      const objFn = {
        1: "xmgl/workerDailyAttendanceStatisticsV2/exportHourStatisticsXls",
      };

      if (command == 1) {
        const requestData = {
          projectSn: this.projectSn,
          startTime:
            this.queryParams.effectiveTime instanceof Array &&
            this.queryParams.effectiveTime.length > 1
              ? this.queryParams.effectiveTime[0]
              : "",
          endTime:
            this.queryParams.effectiveTime instanceof Array &&
            this.queryParams.effectiveTime.length > 1
              ? this.queryParams.effectiveTime[1]
              : "",
          personType: this.queryParams.personType,
          enterpriseId: this.queryParams.enterpriseId,
          teamId: this.queryParams.teamId,
          departmentId: this.queryParams.departmentId,
          workerName: this.queryParams.workerName,
        };
        this.exportDownload(requestData, objFn[command], "工时统计表.xlsx");
      }
    },
    exportDownload(requestData, url, name) {
      fetch(this.$http.defaults.baseURL + url, {
        method: "post",
        headers: {
          Authorization: this.$store.state.userInfo.token,
          "Content-Type": "application/json", // 设置请求头的内容类型为JSON
        },
        body: JSON.stringify(requestData),
      })
        .then((response) => {
          // 处理响应
          if (!response.ok) {
            throw new Error("导出失败");
          }
          return response.blob();
        })
        .then((blob) => {
          console.log("导出成功");
          // 创建一个下载链接
          const url = window.URL.createObjectURL(blob);
          // 创建一个<a>元素
          const link = document.createElement("a");
          link.href = url;
          link.download = name; // 指定下载文件的文件名
          // 模拟点击下载链接
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放URL对象
          window.URL.revokeObjectURL(url);
          // 处理导出的文件
          // 这里可以使用blob对象来获取导出的文件内容或者将其保存到本地
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getQualityRegionList();
    },
    handleRefresh() {
      this.queryParams.pageNo = 1;
      this.queryParams.personType = "";
      this.queryParams.enterpriseId = "";
      this.queryParams.teamId = "";
      this.queryParams.departmentId = "";
      this.queryParams.workerName = "";
      this.queryParams.effectiveTime = [
        dayjs().startOf("month").format("YYYY-MM-DD"),
        dayjs().endOf("month").format("YYYY-MM-DD"),
      ];
      this.getQualityRegionList();
    },
    // 获取列表信息
    getQualityRegionList() {
      let data = {
        projectSn: this.projectSn,
        startTime:
          this.queryParams.effectiveTime instanceof Array &&
          this.queryParams.effectiveTime.length > 1
            ? this.queryParams.effectiveTime[0]
            : "",
        endTime:
          this.queryParams.effectiveTime instanceof Array &&
          this.queryParams.effectiveTime.length > 1
            ? this.queryParams.effectiveTime[1]
            : "",
        pageNo: this.queryParams.pageNo,
        pageSize: this.queryParams.pageSize,
        personType: this.queryParams.personType,
        enterpriseId: this.queryParams.enterpriseId,
        teamId: this.queryParams.teamId,
        departmentId: this.queryParams.departmentId,
        workerName: this.queryParams.workerName,
      };
      // getQualityRegionListApi

      getCountDailyAttendanceByDateRangeApi(data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.tableData = res.result.records;
          this.total = res.result.total;
          if(data.pageNo == 1) {
            this.itemKey = Math.random();
          }
          if (res.result.records instanceof Array) {
            const dateTime =
              res.result.records.length > 0 ? res.result.records[0].dailyHourMap : {};
            let dataList = [];
            for (const key in dateTime) {
              dataList.push({
                date: dayjs(key).format("YYYY/MM/DD"),
                day: dayjs(key).format("DD"),
              });
            }
            this.showTime = dataList;
            console.log("woshi", this.showTime);
          }
        }
      });
    },
  },
  computed: {
    daterangeUp() {
        return this.queryParams.effectiveTime.length > 0 ? `${dayjs(this.queryParams.effectiveTime[0]).format("YYYY/MM/DD")}～${dayjs(this.queryParams.effectiveTime[1]).format("YYYY/MM/DD")}` : "--"
    }
  }
};
</script>
<style lang="less" scoped>
.table-header {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 800;
  font-size: 32px;
  color: #333333;
}
.new-tables {
  width: calc(100% - 32px);
  margin: 20px 16px 0;
  font-size: 15px;
  border-color: #e9e9e9;
  /deep/ .el-table__cell {
    border-color: #e9e9e9 !important;
  }
}
:deep(.el-dialog__body) {
  padding: 10px 20px 20px;
  .dialog_content {
    padding-left: 0;
    padding-right: 0pc;
  }
  .form_box {
    margin: 0 65px;
    color: #272d45;
    font-size: 14px;
    > div {
      margin-top: 6px;
    }
  }
}
.riskpoint-dialog {
  display: flex;
  justify-content: space-between;
  height: 420px;
  .unselected_point {
    width: 280px;
    .treeBox {
      margin-top: 12px;
      height: calc(100% - 12px - 24px - 16px);
      // background-color: rgba(216, 216, 216, 0.2);
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 12px 6px;
      position: relative;
      :deep(.el-checkbox.is-disabled) {
        display: none;
      }
      .treeStyle();
    }
  }
  .selected_point {
    width: 280px;
    .selected_point_scroll {
      margin-top: 12px;
      height: calc(100% - 2px - 24px);
      max-height: initial;
      padding: 12px 6px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      .risk_point {
        width: 100%;
        margin-top: 6px;
        > div {
          justify-content: space-between;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
.source-danger {
  .pagination-container {
    padding: 16px 0 0 0;
  }
}
.tables {
  min-height: initial;
}
.check_box {
  display: flex;
  font-size: 14px;
  > .el-button {
    padding: 0;
    margin-left: 10px;
  }
  > .el-button:first-child {
    color: #eb4047;
  }
}
.flex {
  display: flex;
}
.flex2 {
  display: flex;
  align-items: center;
}
.container_main {
  height: calc(100% - 49px);
}
.checkPoint {
  box-sizing: border-box;
  position: relative;
  height: 100%;
  .header_title {
    padding: 20px 20px 0 20px;
    :deep(.el-cascader__search-input) {
      min-width: 10px;
    }
  }
  :deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
    color: #5181f6;
    background-color: transparent;
    border-color: #d7dbe9;
    box-shadow: none;
  }
  .pagination-container {
    padding: 0;
    width: 100%;
    position: absolute;
    bottom: 16px;
    left: 50%;
    transform: translateX(-50%);
  }
  .el-form-item {
    margin-bottom: 20px;
    margin-right: 30px;
  }
  .el-form-item:last-child {
    margin-right: 0;
  }
  .el-button + .el-button {
    margin-left: 20px;
  }
  .el-radio {
    margin-right: 20px;
  }
  .el-select,
  .el-input {
    width: 192px;
    height: 34px;
  }
  .el-date-editor {
    width: 247px;
    height: 34px;
  }
  .radio-group {
    /deep/ .el-form-item__content {
      display: flex;
    }
    /deep/ .el-radio-group {
      height: 34px;
    }
    /deep/ .el-radio-button__inner {
      height: 34px;
      color: #b2b8c2;
    }
  }
  .edit {
    width: 100%;
    justify-content: center;
    cursor: pointer;
    img {
      margin-right: 5px;
    }
  }
}
.treeStyle() {
  /deep/.el-tree {
    font-size: 15px;
    width: 100%;
    background-color: transparent;
    .el-tree-node {
      white-space: normal;
      &:focus > .el-tree-node__content {
        background-color: transparent;
      }
      &.is-current > .el-tree-node__content {
        background-color: rgba(81, 129, 246, 0.14);
        color: #5181f6;
      }
    }
    .el-tree-node__content {
      // height: 32px;
      padding: 7px 0;
      height: auto;
      line-height: 16px;
      position: relative;
      // margin-bottom: 7px;
      &:hover {
        background-color: rgba(81, 129, 246, 0.14);
        color: #5181f6;
      }

      .videoName {
        font-size: 14px;
      }
      .projectName {
        font-size: 14px;
        width: calc(100% - 55px);
        display: inline-block;
      }
      .companyName2 {
        font-size: 16px;
        font-weight: bold;
        display: inline-block;
        width: 192px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .el-tree-node__expand-icon {
      font-size: 16px;
      padding: 0 6px;
      &.is-leaf {
        color: transparent !important;
      }
    }
    .treeTitle {
      background-color: #f7f7f7;
      margin-bottom: 10px;
    }
  }
}
.risk_detail_main_title {
  font-size: 16px;
  font-weight: bold;
  color: #4d4d4d;
  margin-bottom: 20px;
}
.risk_detail_main {
  .detail_flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 36px;
  }
  .detail_table2 {
    width: calc(100% - 320px) !important;
    :deep(.el-input-number) {
      width: 320px !important;
      .el-input__inner {
        width: 320px !important;
      }
    }
  }
  .detail_table3 {
    width: calc(100% - 320px - 120px) !important;
    .el-select,
    .el-input,
    .box1 {
      width: 440px !important;
    }
  }
  .detail_table {
    width: 100%;
    > div:first-child {
      display: flex;
      align-items: center;
      padding: 10px 17px;
      background-color: #fafafa;
      margin-bottom: 10px;
      justify-content: space-between;
      > .box1 {
        width: 320px;
      }
      > .box1:last-child {
        text-align: center;
      }
      > .box2 {
        margin: 0 6px;
      }
    }
    > div:last-child {
      display: flex;
      justify-content: space-between;
      padding: 10px 17px;
      border: 1px dashed #e4e7ed;
      .el-select,
      .el-input {
        width: 320px;
        height: 34px;
        :deep(.el-input__inner) {
          height: 34px;
          line-height: 34px;
        }
      }
    }
  }
  .detail_table1 {
    display: flex;
    padding: 10px 17px;
    border: 1px dashed #e4e7ed;
    .el-radio-group {
      display: flex;
      flex-wrap: wrap;
      // justify-content: space-between;
      .el-radio:nth-child(n + 3) {
        margin-top: 10px;
      }
      .el-radio {
        width: 604px;
        :deep(.el-input-number) {
          width: 320px !important;
          height: 34px !important;
          .el-input__inner {
            width: 320px !important;
            height: 34px !important;
          }
        }
        :deep(.el-radio__label) {
          span {
            width: 70px;
            display: inline-block;
          }
          > span:last-child {
            margin: 0 20px;
            color: #aaabb6;
          }
        }
      }
    }
  }
}
.detail_table4 {
  margin: 16px 0;
  .detail_table4_title {
    margin-bottom: 16px;
  }
  table {
    width: 100%;
    border: 1px solid #ccc;
    border-collapse: collapse;
    font-size: 14px;
  }
  th,
  td {
    height: 30px;
    border: 1px solid #ccc;
    text-align: center;
    min-width: 80px;
  }
  thead {
    background-color: #f2f2f2;
  }
}
.risk_detail_top {
  width: 76%;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  .el-input,
  .el-select,
  .el-date-editor,
  .el-input-number,
  .el-textarea,
  .risk_detail_top_box {
    width: 320px;
    height: 34px;
  }
}

.detailBox {
  .grid-content {
    overflow: hidden;
    margin-bottom: 10px;
    .label {
      float: left;
      width: 80px;
      text-align: right;
      color: #a2a4af;
    }
    .value {
      float: left;
      width: calc(80% - 80px);
      margin-left: 10px;
      // text-overflow: ellipsis;
      // overflow: hidden;
      // white-space: nowrap;
    }
  }
}
.btn-box {
  height: 50px;
  margin-top: 30px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.inputStyle {
  ::v-deep .el-input__inner {
    height: 200px;
  }
}
.radiusD {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 10px;
  margin-top: 3px;
  margin: 2px 0px;
}
.headerLeft {
  height: 35px;
  background: #ededed;
  font-size: 16px;
  font-weight: 800;
  color: #616266;
  line-height: 30px;
  padding: 0 10px;
  margin-bottom: 20px;
}

.riskcolor {
  color: white;
  padding: 4px 6px;
  width: 64px;
}
.riskcolor_table {
  padding: 1px 6px;
  display: inline-block;
}
.riskcolor1 {
  background-color: #eb4047;
}
.riskcolor2 {
  background-color: #ffbf00;
}
.riskcolor3 {
  background-color: #ffff00;
}
.riskcolor4 {
  background-color: #006fbf;
}
</style>
