import { Component, OnInit } from "@angular/core";
import { MainService } from "../../services/main.service";
import { ActivatedRoute, Router } from "@angular/router";

import { NzMessageService } from "ng-zorro-antd/message";
import { ToolService } from "src/app/services/tool.service";
import { format } from "date-fns";

@Component({
  selector: "app-holidays-management",
  templateUrl: "./holidays-management.component.html",
  styleUrls: ["./holidays-management.component.less"],
})
export class HolidaysManagementComponent implements OnInit {
  constructor(
    private mainService: MainService,
    private msg: NzMessageService,
    private route: ActivatedRoute,
    private tool: ToolService
  ) {}

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initDates(); //初始化日历选中情况
    this.getSyncWorkDay();
  }

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  setDay: boolean = false; //设置工作日模态框
  dates = [];
  dateChecked: any = {}; //日历选择
  syncWorkDay = "0"; //自动同步国家法定节假日
  syncWorkDayObj; //自动同步国家法定节假日
  weeks = [
    { label: "周一", value: "1" },
    { label: "周二", value: "2" },
    { label: "周三", value: "3" },
    { label: "周四", value: "4" },
    { label: "周五", value: "5" },
    { label: "周六", value: "6" },
    { label: "周日", value: "7" },
  ]; //工作日设置：周
  btnLoading: boolean = false; //提交按钮loading状态

  // 初始化增删改按钮
  coopBtns: any = {};
  maskFlag: any = false;
  //设置自动同步国家法定节假日
  setSyncWorkDay(e) {
    this.syncWorkDayObj.valueconfig = Number(e);
    let postData = { syncWorkDay: JSON.stringify(this.syncWorkDayObj) };
    this.maskFlag = this.msg.loading("加载中", { nzDuration: 0 }).messageId;
    this.mainService.coopConfig("syncWorkDay", postData).subscribe((result) => {
      this.msg.remove(this.maskFlag);
      this.maskFlag = false;
      if (result["state"] == 200) {
        this.msg.success("设置成功");
        this.initDates(
          this.lastSelectMonth.getFullYear(),
          this.lastSelectMonth.getMonth()
        );
      } else {
        this.msg.error("设置失败");
      }
    });
  }
  //获取自动同步国家法定节假日
  getSyncWorkDay() {
    let postData = {
      idx: 0,
      sum: 99,
      systemConfiguration: { keyconfig: "syncWorkDay" },
    };
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.syncWorkDay = result.list[0].valueconfig;
          this.syncWorkDayObj = result.list[0];
        }
      });
  }
  getMonthData(date: Date): number | null {
    if (date.getMonth() === 8) {
      return 1394;
    }
    return null;
  }
  // 切换日历上本日工作日/节假日选中情况（checkBox）
  onDateClick(d) {
    console.log(d);
    d = d - 0;
    let that = this;
    if (!that.coopBtns.edit) {
      that.msg.warning("暂无修改权限！", {
        nzDuration: 1000,
      });
      return;
    }
    if (new Date(d).getFullYear() < new Date().getFullYear()) {
      that.msg.warning("禁止修改！", {
        nzDuration: 1000,
      });
      return;
    }
    let postData = {
      workDayException: {
        date:
          new Date(d).getFullYear() +
          "-" +
          (new Date(d).getMonth() + 1) +
          "-" +
          new Date(d).getDate() +
          " 00:00:00",
        isWork: !that.dateChecked["" + d],
      },
    };
    // console.log(postData)
    // return
    that.mainService
      .coopTypeConfig("addData", "workDayException", postData)
      .subscribe((data) => {
        // console.log(data);
        if (data.status == 200) {
          that.msg.success("设置成功！");
        } else {
          that.msg.error(data.msg);
        }
      });
  }

  // change当前选中日期
  lastSelectMonth = new Date(); //上次点击月份的日期；
  selected; //当前选中日期
  onValueChange(value: Date): void {
    let lastYear = this.lastSelectMonth.getFullYear(); //上次选中年
    let lastMonth = this.lastSelectMonth.getMonth() + 1; //上次选中月
    let newYear = value.getFullYear(); //本次选中年
    let newMonth = value.getMonth() + 1; //本次选中月
    // console.log(lastYear, lastMonth, newYear, newMonth)
    if (lastYear != newYear || lastMonth != newMonth) {
      // console.log('已切换了年/月，需重新获取当前年/月数据')
      this.initDates(value.getFullYear(), value.getMonth());
    }
    console.log(
      format(value, "yyyy-MM-dd"),
      format(this.lastSelectMonth, "yyyy-MM-dd"),
      "seimin"
    );
    this.lastSelectMonth = value;
  }

  // 初始化日历选中情况
  loading1 = false;
  initDates(year?, month?) {
    console.log(year, month);
    let that = this;
    // dates 一个月内的 “日”
    that.dates = [];
    if (year !== undefined && month !== undefined) {
      let n = 0;
      if (month == 0) {
        n = 31;
      } else {
        n = new Date(year, month + 1, 0).getDate();
      }
      for (var i = 1; i <= n; i++) {
        let d = new Date(new Date(year, month, i)).getTime() + "";
        that.dates.push(d);
      }
    } else {
      let n = 0;
      if (new Date().getMonth() == 0) {
        n = 31;
      } else {
        n = new Date(
          new Date().getFullYear(),
          new Date().getMonth() + 1,
          0
        ).getDate();
      }
      for (var i = 1; i <= n; i++) {
        let d =
          new Date(
            new Date(new Date().getFullYear(), new Date().getMonth(), i)
          ).getTime() + "";
        that.dates.push(d);
      }
    }
    console.log(that.dates);

    let postData = {
      idx: 0,
      sum: 31,
      workDay: {
        year: year ? year : new Date().getFullYear(),
        month: month + 1 ? month + 1 : new Date().getMonth() + 1,
      },
    };
    // return
    this.loading1 = true;
    that.mainService
      .getFetchDataList("configuration", "workDay", postData)
      .subscribe((data) => {
        this.loading1 = false;
        console.log(data);
        let k = "";
        let dateChecked = {};
        data.list.forEach((e) => {
          let k =
            new Date(e.year, e.month - 1, e.date.substring(8, 10)).getTime() +
            "";
          dateChecked[k] = e.isWork;
        });
        console.log(dateChecked);
        this.dateChecked = dateChecked;
      });
  }

  // 获取当前年
  getYear(): any {
    return new Date().getFullYear();
  }

  // 设置工作日模态框
  showModal() {
    this.setDay = true;
    this.getDaySet(); //工作日设置（小弹窗）
  }
  hideModal() {
    this.setDay = false;
  }
  // 工作日设置已选中box
  weeksChecked: any = {
    1: false,
    2: false,
    3: false,
    4: false,
    5: false,
    6: false,
    7: false,
  };
  saveStr: string = ""; //工作日设置保存参数
  hasChange: boolean = false; //是否修改工作日设置选项
  // 工作日设置操作checkBox
  changeWeeks() {
    this.hasChange = true;
    let str = "";
    for (let i in this.weeksChecked) {
      str += "" + (this.weeksChecked[i] ? 1 : 2);
    }
    str = str.slice(0, 6);
    str = "" + (this.weeksChecked[7] ? 1 : 2) + str;
    str = new Date().getFullYear() + "-" + str;
    this.saveStr = str;
  }
  // 保存工作日设置
  save() {
    let that = this;
    that.btnLoading = true;
    if (!that.hasChange) {
      that.changeWeeks();
    }
    let postData = { workDayConfigure: { rule: that.saveStr } };
    that.mainService
      .coopTypeConfig("addData", "workDayConfigure", postData)
      .subscribe((data) => {
        that.btnLoading = false;
        that.setDay = false;
        if (data.status == 200) {
          that.showPromptModal("保存", true, "");
          that.initDates();
        } else {
          that.showPromptModal("保存", false, data.msg);
        }
      });
  }

  // 获取工作日设置
  loading2 = false;
  getDaySet() {
    let postData = {
      workDayConfigure: {
        year: new Date().getFullYear(),
        state: 1,
      },
      idx: 0,
      sum: 1000,
    };
    this.loading2 = true;
    this.mainService
      .getFetchDataList("configuration", "workDayConfigure", postData)
      .subscribe((data) => {
        this.loading2 = false;
        if (data.list && data.list[0]) {
          this.weeksChecked[1] = data.list[0]["monday"] == 1 ? true : false;
          this.weeksChecked[2] = data.list[0]["tuesday"] == 1 ? true : false;
          this.weeksChecked[3] = data.list[0]["wednesday"] == 1 ? true : false;
          this.weeksChecked[4] = data.list[0]["thursday"] == 1 ? true : false;
          this.weeksChecked[5] = data.list[0]["friday"] == 1 ? true : false;
          this.weeksChecked[6] = data.list[0]["saturday"] == 1 ? true : false;
          this.weeksChecked[7] = data.list[0]["sunday"] == 1 ? true : false;
          console.log(data.list[0]);
          console.log(this.weeksChecked);
        }
      });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }
}
