<template>
  <div>
    <div
      style="
        background-color: #f4f7fc;
        width: 90vw;
        height: 100vh;
        padding: 20px;
      "
    >
      <div style="padding: 20px">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="58px"
        >
          <el-form-item label="月份" prop="month">
            <el-date-picker
              clearable
              @change="changeTime"
              v-model="queryParams.month"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择月份"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleQuery"
              ><el-icon><Search /></el-icon>查询</el-button
            >
          </el-form-item>
        </el-form>
        <div style="display: flex; margin-bottom: 10px">
          <div>部门名称：{{ deptName }}</div>
          <div style="display: flex; margin-left: 50px; font-size: 15px">
            <div
              @click="preWeek(this.firstDay)"
              style="color: #409eff; cursor: pointer"
            >
              《 上一周
            </div>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <div
              @click="nextWeek(this.firstDay)"
              style="color: #409eff; cursor: pointer"
            >
              下一周 》
            </div>
          </div>
          <div style="margin-left: 18vw">
            第{{ weekNum }}周（{{ firstDay }}至{{ lastDay }}）
          </div>
        </div>
        <div>
          <el-table
            :data="tableData"
            border
            style="width: 100%; height: 65vh; overflow: auto"
          >
            <el-table-column
              prop="fullName"
              label="姓名"
              align="center"
              width="120"
            ></el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[0]"
              :label="weekList[0]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.mondayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    >
                    </el-option>
                  </el-select>
                  <!-- {{ scope.row[index] }} -->
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.mondayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[1]"
              :label="weekList[1]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.tuesdayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!-- {{ scope.row[index] }} -->
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.tuesdayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[2]"
              :label="weekList[2]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.wednesdayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!-- {{ scope.row[index] }} -->
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.wednesdayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[3]"
              :label="weekList[3]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.thursdayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!-- {{ scope.row[index] }} -->
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.thursdayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[4]"
              :label="weekList[4]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.fridayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!-- {{ scope.row[index] }} -->
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.fridayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[5]"
              :label="weekList[5]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.saturdayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.saturdayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :prop="weekList[6]"
              :label="weekList[6]"
            >
              <template #default="scope">
                <div>
                  上午：
                  <el-select
                    v-model="scope.row.sundayMorning"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
                <div style="margin-top: 10px">
                  下午：
                  <el-select
                    v-model="scope.row.sundayAfternoon"
                    clearable
                    style="width: 90px"
                  >
                    <el-option
                      v-for="dict in info_kq"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div
            v-if="this.queryParams.month == this.lastYearMonth"
            style="text-align: center; margin-top: 40px"
          >
            <el-button
              :disabled="disabled"
              size="large"
              style="padding: 0 70px"
              @click="submitAttendance()"
              type="primary"
              >保存</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  weeks,
  insertList,
  all,
  oneWeek,
  sxweek,
  deptList,
} from "@/api/clocking/weeklyAttendance";
import { selectByMonth, getDates } from "@/api/clocking/clockingSubmit";
import moment from "moment"; //导入文件
import { ElMessage, ElMessageBox } from "element-plus";
// import type { Action } from "element-plus";
import { useDict } from "@/utils/dict";
import { getInfo } from "@/api/login";
export default {
  name: "YinetoaWeeklyAttendance",
  data() {
    return {
      today: null,
      oneDay: null,
      fiveDay: null,
      disabled: true,
      lastYearMonth: "",
      dataStart: [],
      totalWeeks: 0,
      lastMonth: null,
      queryParams: {},
      loading: true,
      showSearch: true,
      disabled: true,
      selsectVal: "",
      deptName: "",
      startDate: "",
      endDate: "",
      weekNum: null,
      weekList: [],
      listDatas: [],
      listData: {},
      tableData: [],
      tableData1: [],
      tableData2: [],
      firstDay: "",
      nowDate: "",
      lastDay: "",
      lastDay1: "",
      firstDay1: "",
      clicked: false,
      info_kq: useDict("info_kq").info_kq,
    };
  },
  created() {
    this.getInfo();
    this.getLastMonth();
    this.selectByMonth();
    this.oneAndFive();
  },
  mounted() {
    // this.calculateTotalWeeks();
  },
  methods: {
    // 获取1-5号日期
    oneAndFive() {
      let today = new Date();
      // 计算1到5号之间的所有日期
      let startDate = new Date(today.getFullYear(), today.getMonth(), "01");
      let endDate = new Date(today.getFullYear(), today.getMonth(), "05");

      this.today = moment(today).format("YYYY-MM-DD").slice(8, 10);
      // this.today = "01";
      this.oneDay = moment(startDate).format("YYYY-MM-DD").slice(8, 10);
      this.fiveDay = moment(endDate).format("YYYY-MM-DD").slice(8, 10);
      if (this.today >= this.oneDay && this.today <= this.fiveDay) {
        this.disabled = false;
      }
    },
    // 查询
    handleQuery() {
      this.tableData = [];
      this.weekList = [];
      this.firstDay = "";
      this.lastDay = "";
      this.weekNum = null;
      this.selectByMonth(this.queryParams.month);
    },
    async getDates() {
      let res = await getDates(this.weekNum);
      this.firstDay = res[0];
      this.lastDay = res[6];
      var daysOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      this.weekList = [];
      this.weekList = res.map((date) => {
        return daysOfWeek[new Date(date).getDay()] + "（" + date + "）";
      });
    },
    async nextWeek() {
      if (this.queryParams.month.slice(5, 7) < this.lastDay.slice(5, 7)) {
        this.$modal.msgError("已是" + this.queryParams.month + "月的最后一周");
      } else {
        this.$modal.loading();

        this.weekNum++;
        this.getDates();
        this.tableData = [];
        for (let item in this.dataStart) {
          if (item == this.weekNum) {
            this.tableData = this.dataStart[item];
            this.startDate = this.dataStart[item][0].weekStart.slice(0, 10);
          }
        }
      }
      this.$modal.closeLoading();
    },
    preWeek() {
      if (this.queryParams.month.slice(5, 7) > this.firstDay.slice(5, 7)) {
        this.$modal.msgError("已是" + this.queryParams.month + "月的第一周");
      } else {
        this.$modal.loading();

        this.weekNum--;
        this.getDates();
        this.tableData = [];

        for (let item in this.dataStart) {
          if (item == this.weekNum) {
            this.tableData = this.dataStart[item];
          }
        }
      }
      this.$modal.closeLoading();
    },

    async selectByMonth() {
      let { data } = await selectByMonth(this.queryParams.month);
      this.dataStart = data;

      this.weekNum = Object.entries(data)[0][0];
      this.tableData = Object.entries(data)[0][1];
      this.firstDay = Object.entries(data)[0][1][0].weekStart.slice(0, 10);
      this.lastDay = Object.entries(data)[0][1][0].weekEnd.slice(0, 10);
      this.getDayAll(this.firstDay, this.lastDay);
      // this.getweekPreNext();
    },

    //两个日期之间的间隔日期
    getDayAll(starDay, endDay) {
      var arr = [];
      var dates = [];

      // 设置两个日期UTC时间
      var db = new Date(starDay);
      var de = new Date(endDay);

      // 获取两个日期GTM时间
      var s = db.getTime() - 24 * 60 * 60 * 1000;
      var d = de.getTime() - 24 * 60 * 60 * 1000;

      // 获取到两个日期之间的每一天的毫秒数
      for (var i = s; i <= d; ) {
        i = i + 24 * 60 * 60 * 1000;
        arr.push(parseInt(i));
      }

      // 获取每一天的时间  YY-MM-DD
      for (var j in arr) {
        var time = new Date(arr[j]);
        var year = time.getFullYear(time);
        var mouth =
          time.getMonth() + 1 >= 10
            ? time.getMonth() + 1
            : "0" + (time.getMonth() + 1);
        var day = time.getDate() >= 10 ? time.getDate() : "0" + time.getDate();
        var YYMMDD = year + "-" + mouth + "-" + day;
        dates.push(YYMMDD);
      }
      var daysOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      this.weekList = dates.map((date) => {
        return daysOfWeek[new Date(date).getDay()] + "（" + date + "）";
      });
      return dates;
    },
    //总周数
    calculateTotalWeeks() {
      const firstDay = new Date(
        this.queryParams.month.slice(0, 4),
        this.queryParams.month.slice(5, 7) - 1,
        1
      );
      const lastDay = new Date(
        this.queryParams.month.slice(0, 4),
        this.queryParams.month.slice(5, 7),
        0
      );
      // 获取月份的天数
      // 获取月份的天数
      const totalDays = lastDay.getDate();
      // 获取第一天是星期几
      const firstDayOfWeek = firstDay.getDay();
      //获取最后一天是星期几
      const lastDayOfWeek = lastDay.getDay();
      // 计算总周数

      // 从第一天开始向后累加，每逢星期一增加一周
      for (let i = 1 - firstDayOfWeek; i <= totalDays; i += 7) {
        if (i >= 1 && i + 6 <= totalDays) {
          this.totalWeeks++;
        }
      }
      if (firstDayOfWeek !== 1) {
        this.totalWeeks = this.totalWeeks + 1;
      }
      if (lastDayOfWeek !== 1) {
        this.totalWeeks = this.totalWeeks + 1;
      }
    },

    //上个月月份
    getLastMonth() {
      var year, lastMonth;
      var date = new Date();
      var nowYear = date.getFullYear(); //当前年：四位数字
      var nowMonth = date.getMonth(); //当前月：0-11
      if (nowMonth == 0) {
        //如果是0，则说明是1月份，上一个月就是去年的12月
        year = nowYear - 1;
        lastMonth = 12;
      } else {
        //不是1月份，年份为当前年，月份本来是要减1的，但是由于`getMonth()`的月份本身就是少了1的，所以月份不用变。
        year = nowYear;
        lastMonth = nowMonth;
      }
      lastMonth = lastMonth < 10 ? "0" + lastMonth : lastMonth; //月份格式化：月份小于10则追加个0
      let lastYearMonth = year + "-" + lastMonth;
      this.lastYearMonth = lastYearMonth;
      this.queryParams.month = lastYearMonth;
    },

    //获取上一周下一周
    async getweekPreNext() {
      this.loading = true;
      let res = await sxweek({ date: this.startDate });
      var daysOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      var convertedDateArray = res.map(function (dateObj) {
        var dateStr = dateObj[Object.keys(dateObj)[0]];
        var date = new Date(dateStr);

        var dayOfWeek = date.getDay();
        return daysOfWeek[new Date(date).getDay()] + "（" + date + "）";
      });
      this.weekList = convertedDateArray;
      // 使用正则表达式来匹配日期部分
      var datePattern = /\d{4}-\d{2}-\d{2}/;
      var extractedDates = [];

      // 遍历每个字符串并提取日期
      this.weekList.forEach(function (weekday) {
        var matches = weekday.match(datePattern);
        if (matches) {
          extractedDates.push(matches[0]);
        }
      });
      this.firstDay = extractedDates[0];
      this.lastDay = extractedDates[6];
      this.$nextTick(() => {
        this.loading = false;
      });
    },
    //上一周
    // preWeek(date) {
    //   this.loading = true;
    //   //获取当前日期
    //   let startDate = moment(date)
    //     //获取当前日期前7天
    //     .weekday(-7)
    //     //获取当前日期的开始时间
    //     .startOf("week")
    //     //添加1天
    //     .add(1, "days")
    //     //格式化时间
    //     .format("YYYY-MM-DD");
    //   let endDate = moment(date)
    //     .weekday(-7)
    //     .endOf("week")
    //     .add(1, "days")
    //     .format("YYYY-MM-DD");
    //   this.startDate = startDate;
    //   this.endDate = endDate;
    //   this.tableData.push({ weekStart: startDate });
    //   this.tableData.push({ weekEnd: endDate });
    //   this.getweekPreNext();
    //   this.weekNum -= 1;
    //   this.tableData.push({ weekNumber: this.weekNum });
    //   this.deptList();
    //   this.all();
    //   this.loading = false;
    // },
    //下一周
    // nextWeek(date) {
    //   this.loading = true;
    //   // //console.log("nextWeek", date);
    //   //获取当前日期
    //   let startDate = moment(date)
    //     //获取当前日期后7天
    //     .weekday(7)
    //     //获取当前日期的开始时间
    //     .startOf("week")
    //     //添加1天
    //     .add(1, "days")
    //     //格式化时间
    //     .format("YYYY-MM-DD");
    //   // //console.log("startDate", startDate);
    //   let endDate = moment(date)
    //     .weekday(7)
    //     .endOf("week")
    //     .add(1, "days")
    //     .format("YYYY-MM-DD");
    //   // //console.log("endDate", endDate);
    //   this.startDate = startDate;
    //   this.endDate = endDate;
    //   // //console.log("897789", this.tableData);

    //   this.weekNum += 1;
    //   for (let i = 0; i < this.tableData.length; i++) {
    //     this.tableData[i].weekStart = startDate;
    //     this.tableData[i].weekEnd = endDate;
    //     this.tableData[i].weekNumber = this.weekNum;
    //   }
    //   this.getweekPreNext();

    //   this.deptList();
    //   this.all();
    //   this.loading = false;
    // },
    //获取当前日期是第几周
    getWeekNum() {
      //获得当前日期是第几周的方法
      var year = new Date().getFullYear();
      var week = moment(new Date()).format("E"); //获得今天是星期几
      var startweek = moment(new Date(year + "-01-01")).format("E"); //获得今年的1月1号是星期几
      //今天到1月1号的时间戳之差
      var millisDiff =
        new Date(moment().format("yyyy-MM-DD")).getTime() -
        new Date(year + "-01-01").getTime();
      var days =
        (millisDiff -
          week * (24 * 60 * 60 * 1000) -
          (7 - startweek) * (24 * 60 * 60 * 1000)) /
        86400000;
      this.weekNum = days / 7 + 1;
      return this.weekNum;

      //这里加的2代表的是本周和今年1月1号所在的那一周
    },

    //基本信息
    async getInfo() {
      let { user } = await getInfo();
      this.deptName = user.dept.deptName;
    },
    //添加考勤
    submitAttendance() {
      let today = new Date();
      var y = today.getFullYear();
      var m = today.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = today.getDate();
      d = d < 10 ? "0" + d : d;
      // if (this.startDate < this.firstDay1 || this.lastDay1 < this.startDate) {
      //   ElMessage.error("不可编辑");
      // } else {
      ElMessageBox.confirm("是否确认保存该部门考勤？", "系统提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          insertList(this.tableData);
          this.disabled = false;
          ElMessage({
            type: "success",
            message: "保存成功",
          });
        })
        .catch(() => {});
      // }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-select [name="my-select-0"] {
  color: red;
}

.el-select [name="my-select-1"] {
  color: orange;
}
.el-select [name="my-select-2"] {
  color: yellow;
}

.el-select [name="my-select-3"] {
  color: rgb(236, 122, 175);
}
.el-select-dropdown__item.selected .red {
  color: orange;
}

.el-select-dropdown__item.selected .yellow {
  color: yellow;
}

.el-select-dropdown__item.selected .orange {
  color: orange;
}
</style>
