<template>
  <div class="app-container">
    <el-form size="small" :inline="true">
      <el-form-item label="日期" prop="menuName">
        <el-date-picker
          style="width: 240px; margin-right: 8px"
          size="mini"
          v-model="dateRange"
          type="week"
          format="yyyy 第 WW 周"
          placeholder="选择周"
          :picker-options="{ firstDayOfWeek: 1 }"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="作业单位" prop="status">
        <el-select
          style="margin-right: 8px"
          size="mini"
          v-model="workUnit"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            v-for="item in workUnitOptions"
            :key="item.organAbbr"
            :label="item.organAbbr"
            :value="item.organAbbr"
          >
          </el-option>
        </el-select>
      </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-button icon="el-icon-download" size="mini" @click="onExport"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="本周计划执行情况" name="weeklyPlanSituationTableRef">
        <WeeklyPlanSituationTable ref="weeklyPlanSituationTableRef" />
      </el-tab-pane>
      <el-tab-pane
        label="三级及以上作业风险计划"
        name="level3AbovePlansTableRef"
      >
        <Level3AbovePlansTable ref="level3AbovePlansTableRef" />
      </el-tab-pane>
      <el-tab-pane
        label="下周计划安排情况"
        name="nextWeekPlanSituationTableRef"
      >
        <NextWeekPlanSituationTable ref="nextWeekPlanSituationTableRef" />
      </el-tab-pane>
      <el-tab-pane
        label="本周违章查处情况"
        name="weeklyViolationSituationTableRef"
      >
        <WeeklyViolationSituationTable ref="weeklyViolationSituationTableRef" />
      </el-tab-pane>
      <el-tab-pane
        label="本周到岗到位履职情况"
        name="thoughtfulJobSituationTableRef"
      >
        <ThoughtfulJobSituationTable ref="thoughtfulJobSituationTableRef" />
      </el-tab-pane>
      <el-tab-pane
        v-if="false"
        label="防外人触电隐患排查"
        name="updateOnExternalRisksTableRef"
      >
        <UpdateOnExternalRisksTable ref="updateOnExternalRisksTableRef" />
      </el-tab-pane>
      <el-tab-pane
        v-if="false"
        label="线路杆号牌缺失情况"
        name="lineMissingSituationTableRef"
      >
        <LineMissingSituationTable ref="lineMissingSituationTableRef" />
      </el-tab-pane>
    </el-tabs>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handleQuery"
    />
  </div>
</template>

<script>
import Level3AbovePlansTable from "./components/level3-above-plans-table.vue";
import LineMissingSituationTable from "./components/line-missing-situation-table.vue";
import NextWeekPlanSituationTable from "./components/next-week-plan-situation-table.vue";
import ThoughtfulJobSituationTable from "./components/thoughtful-job-situation-table.vue";
import UpdateOnExternalRisksTable from "./components/update-on-external-risks-table.vue";
import WeeklyPlanSituationTable from "./components/weekly-plan-situation-table.vue";
import WeeklyViolationSituationTable from "./components/weekly-violation-situation-table.vue";
import moment from "moment";
import {
  getReportWeek,
  getWorkUnitList,
  weekExport,
} from "@/api/secure/daily-newspaper";
export default {
  components: {
    Level3AbovePlansTable,
    LineMissingSituationTable,
    NextWeekPlanSituationTable,
    ThoughtfulJobSituationTable,
    UpdateOnExternalRisksTable,
    WeeklyPlanSituationTable,
    WeeklyViolationSituationTable,
  },
  name: "weekly-report",
  data() {
    return {
      activeName: "weeklyPlanSituationTableRef",
      // 日期范围
      dateRange: "",
      startDate: "", // 显示开始时间
      endDate: "", // 显示结束时间
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      workUnit: "", // 作业单位
      workUnitOptions: [],
    };
  },
  watch: {
    dateRange(newVal) {
      this.calculateStartAndEndDates(newVal);
    },
  },
  mounted() {
    // 设置默认为最近的一周
    this.setRecentWeek();
    this.getWorkUnit();
    this.handleQuery();
  },
  methods: {
    moment,
    async getWorkUnit() {
      const { data } = await getWorkUnitList();
      this.workUnitOptions = data;
    },
    setRecentWeek() {
      const today = new Date();
      const diffDays = today.getDay() === 0 ? -6 : 1 - today.getDay(); // 调整到周一作为一周的开始
      const startOfWeek = new Date(today);
      startOfWeek.setDate(today.getDate() + diffDays);
      this.dateRange = startOfWeek;

      this.calculateStartAndEndDates(startOfWeek);
    },
    handleClick(tab, event) {
      console.log(tab, event, "---------ddd");
      this.activeName = tab.name;
      // this.handleQuery();
    },
    /** 搜索按钮操作 */
    async handleQuery() {
      this.loading = true;
      const { appointmentList, illegalList, nextList, planList } =
        await getReportWeek(this.startDate, this.endDate);
      this.$nextTick(() => {
        this.$refs["weeklyPlanSituationTableRef"].tableData = planList;
        this.$refs["level3AbovePlansTableRef"].tableData = [];
        this.$refs["nextWeekPlanSituationTableRef"].tableData = nextList;
        this.$refs["weeklyViolationSituationTableRef"].tableData = illegalList;
        this.$refs["thoughtfulJobSituationTableRef"].tableData =
          appointmentList;
      });
      this.loading = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.workUnit = "";
      // 设置默认为最近的一周
      this.setRecentWeek();
      this.handleQuery();
    },
    calculateStartAndEndDates(date) {
      if (!date) return;

      const startOfWeek = new Date(date.getTime());
      const dayOfWeek = startOfWeek.getDay();
      const diffDays = dayOfWeek === 0 ? -6 : 1 - dayOfWeek; // 调整到周一作为一周的开始
      startOfWeek.setDate(startOfWeek.getDate() + diffDays);

      const endOfWeek = new Date(startOfWeek);
      endOfWeek.setDate(endOfWeek.getDate() + 6);

      this.startDate = this.formatDate(startOfWeek);
      this.endDate = this.formatDate(endOfWeek);
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}${month}${day}`;
    },
    async onExport() {
      const res = await weekExport(this.startDate, this.endDate);
      if (res) {
        const elink = document.createElement("a");
        elink.download = `周报-${this.startDate}_${this.endDate}.xls`;
        elink.style.display = "none";
        const blob = new Blob([res], { type: "application/x-msdownload" });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      } else {
        this.$message.error("导出异常请联系管理员");
      }
    },
  },
};
</script>
<style lang="scss" scoped></style>
