<template>
  <div class="app-container scroll-auto">
    <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="company" v-if="false">
        <el-select
          style="margin-right: 8px"
          size="mini"
          v-model="queryParams.company"
          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: "",
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        company: "", // 作业单位
        startDate: "", // 显示开始时间
        endDate: "", // 显示结束时间
      },
      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 { workList, appointmentList, illegalList, nextList, planList } =
        await getReportWeek(this.queryParams);
      this.$nextTick(() => {
        this.$refs["weeklyPlanSituationTableRef"].tableData = planList;
        this.$refs["level3AbovePlansTableRef"].tableData = workList;
        this.$refs["nextWeekPlanSituationTableRef"].tableData = nextList;
        this.$refs["weeklyViolationSituationTableRef"].tableData = illegalList;
        this.$refs["thoughtfulJobSituationTableRef"].tableData =
          appointmentList;
      });
      this.loading = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.company = "";
      // 设置默认为最近的一周
      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.queryParams.startDate = this.formatDate(startOfWeek);
      this.queryParams.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}`;
    },
    //根据日期获取第几周
    getWeek(dateTime) {
      var time,
        week,
        checkDate = new Date(dateTime);
      checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
      time = checkDate.getTime();
      checkDate.setMonth(0);
      checkDate.setDate(1);
      week = Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
      return week;
    },
    formatDateToYYYYMMDD(dateStr) {
      // 检查输入字符串是否为8位数字，即yyyymmdd格式
      if (!/^\d{8}$/.test(dateStr)) {
        throw new Error("Invalid date format. Expected yyyymmdd.");
      }
      // 提取年月日部分
      const year = dateStr.substring(0, 4);
      const month = dateStr.substring(4, 6);
      const day = dateStr.substring(6, 8);

      // 格式化并返回yyyy-mm-dd格式的字符串
      return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
    },
    async onExport() {
      const res = await weekExport(
        this.queryParams.startDate,
        this.queryParams.endDate
      );
      const weekNum = this.getWeek(
        this.formatDateToYYYYMMDD(this.queryParams.startDate)
      );
      if (res) {
        const elink = document.createElement("a");
        elink.download = `配电专业生产周例会汇报材料（第` + weekNum + `周).doc`;
        elink.style.display = "none";
        const blob = new Blob([res], {
          type: "application/msword;charset=UTF-8",
        });
        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>
